A Neural Network with PowerShell Version 5 Classes

I’ve had been waiting for PowerShell version 5 because it supports classes and true object oriented programming. Quite a few months ago, my work laptop, which was running Windows 8.1, was upgraded to Windows 10. PowerShell version 5 comes along with Windows 10. (At the time when I write this post, PowerShell v5 was not available for Windows 7 or 8 even though there were preview versions of v5 available for those OSes).

Anyway, for most PowerShell scripts, OOP with classes isn’t really needed. In fact, OOP is never required in any language (well, with a few exceptions) but OOP makes writing complicated code much easier.

I decided to test PowerShell v5 classes by writing a non-trivial neural network. My learning curve for PS classes was fairly easy. By that I mean PS classes closely resemble classes in other languages like C#, Java, and Python.


The class definition looks like this:

class NeuralNetwork
  [int] $numInput    # number input nodes
  [int] $numHidden
  [int] $numOutput

  [double[]] $inputs
  [double[][]] $ihWeights
  [double[]] $hBiases
  [double[]] $hOutputs

  [double[][]] $hoWeights # hidden-to-output
  [double[]] $oBiases
  [double[]] $outputs

  [Random] $rnd  # for initial wts

  # the ctor and methods go here

Notice that all class members are public scope. The class constructor looks like this:

NeuralNetwork([int] $ni, [int] $nh,
  [int] $no)
  $this.numInput = $ni
  $this.numHidden = $nh
  # etc.

Notice that class members are accessed using the ‘this’ keyword. The constructor is called like this:

[int] $numInput = 4
[int] $numHidden = 5
[int] $numOutput = 3
[NeuralNetwork] $nn =
  [NeuralNetwork]::new($numInput, $numHidden,

Nothing really unexpected here. PowerShell supports regular methods and static methods. A typical class method is called like this:

[double[]] $weights = $nn.Train($trainData,
  $maxEpochs, $learnRate, $momentum)

Again, nothing crazy. The bottom line is that PowerShell version 5 allows you to write very sophisticated scripts much easier than without using classes. It’s not clear to me exactly what scenarios OOP with PowerShell will be a great idea, but I’m glad to see classes in PowerShell.

This entry was posted in Machine Learning. Bookmark the permalink.