### Semantic Maps & Automated Text Generation

For the past few years I've been developing something I call Athena. Very simply, Athena has the ability to read natural language text documents and create a semantic map from the information contained - this is the dehydration phase. Athena also has the ability to reverse this process and automatically generate (near) natural language text from a semantic map - the rehydration phase.

To explain why this is useful imagine the following. In the real world a cartographer would survey a natural landscape, taking measurements between landmarks and other key features, and compress this information into a two dimensional representation (commonly known as a map). With this map you, as an explorer, are able to create an imaginary representation of that landscape, without ever having been there. Sure, some information is lost during the mapping process, such as the exact species of fauna and flora or weather you may encounter, but using generalisation you can infer what's likely to be there based on previous experience in similar surroundings.

Athena does something analogous to a real world cartographer. However, rather than creating a flat, two dimensional map, Athena stores its knowledge in a large, hyper-dimensional, vector array. Real world landmarks are replaced with key words, phrases and concepts. However, unlike the real world map example, where prior knowledge of fauna and flora is required, Athena holds a generalised set of context information, which allows the rehydration phase to occur.

Athena combines information from thousands of web pages and documents to form a single semantic map. As a new document is added the existing map is modified to accommodate the new information. During this process the map is compressed to form the most efficient representation of knowledge. Similar and related concepts are squeezed together, and duplicate and redundant information squeezed out. And, this is where the magic happens... By reducing the footprint of Athena's semantic map, new knowledge is inferred. Athena will create links between concepts it has not seen in existing documents.

Behind the scenes I’m using SQL Server 2012. The full text engine has been very useful as it contains a stemming algorithm, a list of stop words as well as the obvious full text search capability. Most of the useful functions are contained in sys.dm_fts_parser. On top of SQL, there’s plenty of hand written C#, which implements the semantic map generation. Semantic concepts are represented as vectors and I use cosine similarity to measure similarity between vectors. To establish which terms are important, I use a combination of isolating title case nouns and calculating tf–idf (term frequency–inverse document frequency).

Retrieving information from Athena is as simple as using a search engine. Just type in a word or phrase and Athena will display the relevant portion of its semantic map. Back in the early days of development I used to play a weird game of two word association with Athena. One day when I typed in "sky tank" and Athena replied with "apache gunship", I knew I was onto something. One of the side effects of knowledge compression is that Athena performs inference between concepts.

The next step was to scale up. I'm now able to load in complete documents, which Athena will summarise, and then append relevant information that it already holds in its semantic map. In a slight twist on the above, another way to use Athena is to type in a "news headline", real or imagined, and Athena will prepare an appropriate news article.

In the example below, I typed in "Google DARPA robotics challenge", as I knew that Google had entered into the recent DARPA robotics challenge. The result is a 2D overview graph representing Athena's knowledge.

Athena Semantic Map |

Alongside this Athena generates a text file from which I was able to create a news article. The generated text is not perfect. It's largely a collection of loosely ordered words that have been compressed into Athena's dialect of English. However, it's not much trouble to convert this back into something more human readable.

This is the result after cleaning up manually for a couple of minutes.

*Google acquires Redwood Robotics and Boston Dynamics.**Boston Dynamics makes the Atlas, Wildcat and Big Dog (LS3) robots.**Boston Dynamics employs scientists from Carnegie Mellon University.**Darpa is the Pentagon’s research and development unit.**The Darpa robotics challenge tests machines built to work in disaster areas like Fukushima.**The Darpa robotics challenge was held in Miami.**Google's Schaft robot wins Darpa challenge.**IHMC takes second place in the Darpa challenge.**Google Talk is an instant messaging service.**Google Reader was an RSS feed aggregator.*

There's still a lot of work to do to make Athena into a viable product, but much of the hard work has already been done.

### Linear Regression C#

When looking at time series data, such as a stream of prices, it can often be useful to establish a general trend and represent this with a single number. This can be achieved using a linear regression calculation.

Take this series of prices:

4.8, 4.8, 4.5, 3.9, 4.4, 3.6, 3.6, 2.9, 3.5, 3.0, 2.5, 2.2, 2.6, 2.1, 2.2

If you plot on an Excel graph and add a linear trend line, you should get something like this:

We can do the same thing in code:

- using System;
- class Regression
- {
- static void Main(string[] args)
- {
- double[] values = { 4.8, 4.8, 4.5, 3.9, 4.4, 3.6, 3.6, 2.9, 3.5, 3.0, 2.5, 2.2, 2.6, 2.1, 2.2 };
- double xAvg = 0;
- double yAvg = 0;
- for (int x = 0; x < values.Length; x++)
- {
- xAvg += x;
- yAvg += values[x];
- }
- xAvg = xAvg / values.Length;
- yAvg = yAvg / values.Length;
- double v1 = 0;
- double v2 = 0;
- for (int x = 0; x < values.Length; x++)
- {
- v1 += (x - xAvg) * (values[x] - yAvg);
- v2 += Math.Pow(x - xAvg, 2);
- }
- double a = v1 / v2;
- double b = yAvg - a * xAvg;
- Console.WriteLine("y = ax + b");
- Console.WriteLine("a = {0}, the slope of the trend line.", Math.Round(a, 2));
- Console.WriteLine("b = {0}, the intercept of the trend line.", Math.Round(b, 2));
- Console.ReadLine();
- }
- }

Now you have the slope of the trend line, this can be used as an input for neural networks analysing time series data. I use something similar in NNATS…

For a complete explanation of linear regression see Wikipedia.

John

### Flocking Boids C#

Note: The code supporting this post can be found on GitHub.

In this post, I shall demonstrate an example of swarm intelligence, which is based on the Boids model. In my ecosystem, two different types of Boids exist, namely Regular Boids and Zombie Boids. The Regular Boids are very social, fast moving creatures, which like to flock together. The Zombie Boids are solitary soles, whose single reason for living is to chase after Regular Boids, albeit very slowly.

There is no real problem I am trying to solve here, other than to enjoy watching the carnage that emerges! It would be very easy to add nicer graphics, or even turn this simulation into a screen saver. As usual, the full C# source code to generate this application is listed below.

Before I go into detail about the code, some background on Boids. In 1986, Craig Reynolds developed a computer model that simulated animal movement, such as flocks of birds and schools of fish. He called the simulated flocking creatures Boids.

As with most artificial life simulations, Boids is an example of emergent behaviour. The complexity of Boids arises from the interaction of individual agents complying with a simple set of rules. Reynolds basic flocking model consisted of three simple steering behaviours that determined how individual Boids should manoeuvre based on their velocity and position within the flock:

**Separation:** steer to avoid crowding local flock-mates

**Cohesion:** steer to move toward the average position of local flock-mates

**Alignment:** steer towards the average heading of local flock-mates

To provide even more life like effects, further rules could be added, such as obstacle avoidance and goal seeking.

The flocking algorithm requires that each Boid only react to flock-mates within its local neighbourhood. This neighbourhood is defined by the Boid’s field of view relative to the rest of the flock. Flock-mates outside of this neighbourhood are ignored.

The video below shows an example of the behaviour you can expect to emerge.

To implement Boids, I have used three classes, which are EcoSystem, Swarm and Boid. The EcoSystem class contains the entry point of the application, handles the graphics and serves as a container for the swarm. The Swarm class is responsible for creating and managing the entire the collection of Boids, known as the swarm. The Boid class encapsulates all logic pertaining to Boid behaviours, which, in this simulation, include separation, cohesion, alignment, avoidance and hunting.

- using System;
- using System.Collections.Generic;
- using System.Drawing;
- using System.Drawing.Drawing2D;
- using System.Windows.Forms;
- public class Boids : Form
- {
- private Timer timer;
- private Swarm swarm;
- private Image iconRegular;
- private Image iconZombie;
- [STAThread]
- private static void Main()
- {
- Application.Run(new Boids());
- }
- public Boids()
- {
- int boundary = 640;
- SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.DoubleBuffer, true);
- FormBorderStyle = FormBorderStyle.FixedToolWindow;
- StartPosition = FormStartPosition.CenterScreen;
- ClientSize = new Size(boundary, boundary);
- iconRegular = CreateIcon(Brushes.Blue);
- iconZombie = CreateIcon(Brushes.Red);
- swarm = new Swarm(boundary);
- timer = new Timer();
- timer.Tick += new EventHandler(this.timer_Tick);
- timer.Interval = 75;
- timer.Start();
- }
- protected override void OnPaint(PaintEventArgs e)
- {
- foreach (Boid boid in swarm.Boids)
- {
- float angle;
- if (boid.dX == 0) angle = 90f;
- else angle = (float)(Math.Atan(boid.dY / boid.dX) * 57.3);
- if (boid.dX < 0f) angle += 180f;
- Matrix matrix = new Matrix();
- matrix.RotateAt(angle, boid.Position);
- e.Graphics.Transform = matrix;
- if (boid.Zombie) e.Graphics.DrawImage(iconZombie, boid.Position);
- else e.Graphics.DrawImage(iconRegular, boid.Position);
- }
- }
- private static Image CreateIcon(Brush brush)
- {
- Bitmap icon = new Bitmap(16, 16);
- Graphics g = Graphics.FromImage(icon);
- Point p1 = new Point(0, 16);
- Point p2 = new Point(16, 8);
- Point p3 = new Point(0, 0);
- Point p4 = new Point(5, 8);
- Point[] points = { p1, p2, p3, p4 };
- g.FillPolygon(brush, points);
- return icon;
- }
- private void timer_Tick(object sender, EventArgs e)
- {
- swarm.MoveBoids();
- Invalidate();
- }
- }
- public class Swarm
- {
- public List<Boid> Boids = new List<Boid>();
- public Swarm(int boundary)
- {
- for (int i = 0; i < 15; i++)
- {
- Boids.Add(new Boid((i > 12), boundary));
- }
- }
- public void MoveBoids()
- {
- foreach (Boid boid in Boids)
- {
- boid.Move(Boids);
- }
- }
- }
- public class Boid
- {
- private static Random rnd = new Random();
- private static float border = 100f;
- private static float sight = 75f;
- private static float space = 30f;
- private static float speed = 12f;
- private float boundary;
- public float dX;
- public float dY;
- public bool Zombie;
- public PointF Position;
- public Boid(bool zombie, int boundary)
- {
- Position = new PointF(rnd.Next(boundary), rnd.Next(boundary));
- this.boundary = boundary;
- Zombie = zombie;
- }
- public void Move(List<Boid> boids)
- {
- if (!Zombie) Flock(boids);
- else Hunt(boids);
- CheckBounds();
- CheckSpeed();
- Position.X += dX;
- Position.Y += dY;
- }
- private void Flock(List<Boid> boids)
- {
- foreach (Boid boid in boids)
- {
- float distance = Distance(Position, boid.Position);
- if (boid != this && !boid.Zombie)
- {
- if (distance < space)
- {
- // Create space.
- dX += Position.X - boid.Position.X;
- dY += Position.Y - boid.Position.Y;
- }
- else if (distance < sight)
- {
- // Flock together.
- dX += (boid.Position.X - Position.X) * 0.05f;
- dY += (boid.Position.Y - Position.Y) * 0.05f;
- }
- if (distance < sight)
- {
- // Align movement.
- dX += boid.dX * 0.5f;
- dY += boid.dY * 0.5f;
- }
- }
- if (boid.Zombie && distance < sight)
- {
- // Avoid zombies.
- dX += Position.X - boid.Position.X;
- dY += Position.Y - boid.Position.Y;
- }
- }
- }
- private void Hunt(List<Boid> boids)
- {
- float range = float.MaxValue;
- Boid prey = null;
- foreach (Boid boid in boids)
- {
- if (!boid.Zombie)
- {
- float distance = Distance(Position, boid.Position);
- if (distance < sight && distance < range)
- {
- range = distance;
- prey = boid;
- }
- }
- }
- if (prey != null)
- {
- // Move towards closest prey.
- dX += prey.Position.X - Position.X;
- dY += prey.Position.Y - Position.Y;
- }
- }
- private static float Distance(PointF p1, PointF p2)
- {
- double val = Math.Pow(p1.X - p2.X, 2) + Math.Pow(p1.Y - p2.Y, 2);
- return (float)Math.Sqrt(val);
- }
- private void CheckBounds()
- {
- float val = boundary - border;
- if (Position.X < border) dX += border - Position.X;
- if (Position.Y < border) dY += border - Position.Y;
- if (Position.X > val) dX += val - Position.X;
- if (Position.Y > val) dY += val - Position.Y;
- }
- private void CheckSpeed()
- {
- float s;
- if (!Zombie) s = speed;
- else s = speed / 4f;
- float val = Distance(new PointF(0f, 0f), new PointF(dX, dY));
- if (val > s)
- {
- dX = dX * s / val;
- dY = dY * s / val;
- }
- }
- }

I hope you enjoy Boids and much as I do – I find them strangely addictive to watch.

### Self Organising Map C#

In this post, I shall be discussing Self Organising Maps (SOM), which are also known as Kohonen maps or topographical maps. Until now, all of my posts have focussed on supervised learning, i.e. we present a set of patterns to a neural network along with the desired outputs. The network then adjusts its weights in order to recreate the correct outputs. However, suppose we do not know in advance what the outputs should be? How can we get the network to do something useful? This is called unsupervised learning. Some reasons we may choose to do this are:

- Finding clusters
- Dimensionality reduction
- Finding hidden correlations
- Data compression
- Classification

A SOM is a two layer neural network that accepts N-dimensional input patterns and maps them to a lattice of output neurons, which represents feature space. The output map, which is typically two-dimensional, characterises the relative position of neurons with regards their neighbours, i.e. their topological properties rather than exact geometric locations. All input neurons are fully connected to all output neurons.

The training steps of a SOM are simple.

- Initialise the interconnecting weights with random values.
- Present an input pattern to the network.
- Choose the output neuron with the highest activation (the “winner”).
- Update the weights of neurons that are within the “neighbourhood” of the winner, using a relative learning factor.
- Reduce the learning factor monotonically.
- Reduce the size of the “neighbourhood” monotonically.
- Repeat from step two until only small updates are observed.

The spread of the neighbourhood function will initially include all neurons on the grid, gradually reducing to include only the winning neuron.

To provide an example of what to expect from a SOM, I have prepared a simple example that will attempt to group twenty-five foods into regions of similarity, based on three parameters, which are protein, carbohydrate and fat.

Therefore, the challenge for this SOM is to reduce data containing three dimensions down to two, whilst retaining meaning. It does this by automatically indentifying differentiating features that will have the greatest effect.

The input data is as follows:

Apples,0.4,11.8,0.1

Avocado,1.9,1.9,19.5

Bananas,1.2,23.2,0.3

Beef Steak,20.9,0.0,7.9

Big Mac,13.0,19.0,11.0

Brazil Nuts,15.5,2.9,68.3

Bread,10.5,37.0,3.2

Butter,1.0,0.0,81.0

Cheese,25.0,0.1,34.4

Cheesecake,6.4,28.2,22.7

Cookies,5.7,58.7,29.3

Cornflakes,7.0,84.0,0.9

Eggs,12.5,0.0,10.8

Fried Chicken,17.0,7.0,20.0

Fries,3.0,36.0,13.0

Hot Chocolate,3.8,19.4,10.2

Pepperoni,20.9,5.1,38.3

Pizza,12.5,30.0,11.0

Pork Pie,10.1,27.3,24.2

Potatoes,1.7,16.1,0.3

Rice,6.9,74.0,2.8

Roast Chicken,26.1,0.3,5.8

Sugar,0.0,95.1,0.0

Tuna Steak,25.6,0.0,0.5

Water,0.0,0.0,0.0

After running this data through the SOM, the foods were placed on a 10x10 grid representing their relative similarities. A graphical representation is shown below.

How has the feature map grouped items together, whilst crushing three dimensions into two? Well, a number of zones have formed. Water, which contains no protein, carbs or fat, has been pushed to the bottom right. Directly above in the top right hand corner, sugar, which is made almost entirely of carbs, has taken hold. In the top left corner, butter reigns supreme, being almost entirely fat. Finally, the bottom left is occupied by tuna, which has the highest protein content of the foods in my sample. The remaining foods live between these extremes, with a junk food zone occupying the centre ground.

Below is the C# code, which will allow you to recreate and modify this example. Try adding more input dimensions and see what results. It is not always obvious to see what is happening, especially with a high number of dimensions. However, eventually you will normally be able to spot the, sometimes unexpected, correlation.

- using System;
- using System.Collections.Generic;
- using System.IO;
- public class Map
- {
- private Neuron[,] outputs; // Collection of weights.
- private int iteration; // Current iteration.
- private int length; // Side length of output grid.
- private int dimensions; // Number of input dimensions.
- private Random rnd = new Random();
- private List<string> labels = new List<string>();
- private List<double[]> patterns = new List<double[]>();
- static void Main(string[] args)
- {
- new Map(3, 10, "Food.csv");
- Console.ReadLine();
- }
- public Map(int dimensions, int length, string file)
- {
- this.length = length;
- this.dimensions = dimensions;
- Initialise();
- LoadData(file);
- NormalisePatterns();
- Train(0.0000001);
- DumpCoordinates();
- }
- private void Initialise()
- {
- outputs = new Neuron[length, length];
- for (int i = 0; i < length; i++)
- {
- for (int j = 0; j < length; j++)
- {
- outputs[i, j] = new Neuron(i, j, length);
- outputs[i, j].Weights = new double[dimensions];
- for (int k = 0; k < dimensions; k++)
- {
- outputs[i, j].Weights[k] = rnd.NextDouble();
- }
- }
- }
- }
- private void LoadData(string file)
- {
- StreamReader reader = File.OpenText(file);
- reader.ReadLine(); // Ignore first line.
- while (!reader.EndOfStream)
- {
- string[] line = reader.ReadLine().Split(',');
- labels.Add(line[0]);
- double[] inputs = new double[dimensions];
- for (int i = 0; i < dimensions; i++)
- {
- inputs[i] = double.Parse(line[i + 1]);
- }
- patterns.Add(inputs);
- }
- reader.Close();
- }
- private void NormalisePatterns()
- {
- for (int j = 0; j < dimensions; j++)
- {
- double sum = 0;
- for (int i = 0; i < patterns.Count; i++)
- {
- sum += patterns[i][j];
- }
- double average = sum / patterns.Count;
- for (int i = 0; i < patterns.Count; i++)
- {
- patterns[i][j] = patterns[i][j] / average;
- }
- }
- }
- private void Train(double maxError)
- {
- double currentError = double.MaxValue;
- while (currentError > maxError)
- {
- currentError = 0;
- List<double[]> TrainingSet = new List<double[]>();
- foreach (double[] pattern in patterns)
- {
- TrainingSet.Add(pattern);
- }
- for (int i = 0; i < patterns.Count; i++)
- {
- double[] pattern = TrainingSet[rnd.Next(patterns.Count - i)];
- currentError += TrainPattern(pattern);
- TrainingSet.Remove(pattern);
- }
- Console.WriteLine(currentError.ToString("0.0000000"));
- }
- }
- private double TrainPattern(double[] pattern)
- {
- double error = 0;
- Neuron winner = Winner(pattern);
- for (int i = 0; i < length; i++)
- {
- for (int j = 0; j < length; j++)
- {
- error += outputs[i, j].UpdateWeights(pattern, winner, iteration);
- }
- }
- iteration++;
- return Math.Abs(error / (length * length));
- }
- private void DumpCoordinates()
- {
- for (int i = 0; i < patterns.Count; i++)
- {
- Neuron n = Winner(patterns[i]);
- Console.WriteLine("{0},{1},{2}", labels[i], n.X, n.Y);
- }
- }
- private Neuron Winner(double[] pattern)
- {
- Neuron winner = null;
- double min = double.MaxValue;
- for (int i = 0; i < length; i++)
- for (int j = 0; j < length; j++)
- {
- double d = Distance(pattern, outputs[i, j].Weights);
- if (d < min)
- {
- min = d;
- winner = outputs[i, j];
- }
- }
- return winner;
- }
- private double Distance(double[] vector1, double[] vector2)
- {
- double value = 0;
- for (int i = 0; i < vector1.Length; i++)
- {
- value += Math.Pow((vector1[i] - vector2[i]), 2);
- }
- return Math.Sqrt(value);
- }
- }
- public class Neuron
- {
- public double[] Weights;
- public int X;
- public int Y;
- private int length;
- private double nf;
- public Neuron(int x, int y, int length)
- {
- X = x;
- Y = y;
- this.length = length;
- nf = 1000 / Math.Log(length);
- }
- private double Gauss(Neuron win, int it)
- {
- double distance = Math.Sqrt(Math.Pow(win.X - X, 2) + Math.Pow(win.Y - Y, 2));
- return Math.Exp(-Math.Pow(distance, 2) / (Math.Pow(Strength(it), 2)));
- }
- private double LearningRate(int it)
- {
- return Math.Exp(-it / 1000) * 0.1;
- }
- private double Strength(int it)
- {
- return Math.Exp(-it / nf) * length;
- }
- public double UpdateWeights(double[] pattern, Neuron winner, int it)
- {
- double sum = 0;
- for (int i = 0; i < Weights.Length; i++)
- {
- double delta = LearningRate(it) * Gauss(winner, it) * (pattern[i] - Weights[i]);
- Weights[i] += delta;
- sum += delta;
- }
- return sum / Weights.Length;
- }
- }

As always, let me know what you think.

John

### Back Propagation Multi-Output Neural Network C#

In this post, I publish an updated version of my multi-layer Perceptron - new features and improvements include:

- A graphical representation of network activity
- The ability to handle multiple network outputs
- The ability to define any network architecture in a single line of code
- A cleaner separation of responsibility within the code

In order to put this new network through its paces, I downloaded the classic Iris Plants Database from the UCI Machine Learning Repository. The data set contains three classes of fifty instances each, where each class refers to a type of iris plant. One class is linearly separable from the other two; the latter are not linearly separable from each other. To use this data, save the web page as a text file with a csv file extension. Open with Excel and add three new columns, on the right, filling with *0,0,1* or *0,1,0* or *1,0,0* depending on the species of plant. Delete the species name column and you now have a file which can be fed into your network. The video below shows the graphical output and clearly displays how the network converges on a solution.

There is quite a lot of code so I will cover each class individually.

Unlike my previous back propagation project, this one is a Windows Forms Application, so in Visual Studio begin by creating a new project and delete *Form1.cs* and *Program.cs*, which were automatically created for you. Create a new class file for each of the code blocks below.

**Graph.cs**

This is the container for the project and provides a graphical display of how the network is proceeding with training. In order to use the graphing feature, the penultimate layer of your network must contain two dimensions, which is not as restrictive as is sounds. I have found that being able to visualise network activity helps enormously when tuning your network. Things to look out for are inactivity, meaning the network has become stuck in a local minimum, or erratic activity meaning your learning rate is too high. If at any time you want to restart training, simply hit the space key and the network will reset. I guarantee that once you have tried this, you will never go back to gazing at streams of numbers…

- using System;
- using System.Drawing;
- using System.Windows.Forms;
- public class Graph : Form
- {
- private int iteration;
- private Network network;
- private Brush[] brushes = { Brushes.Red, Brushes.Green, Brushes.Blue };
- [STAThread]
- static void Main()
- {
- Application.Run(new Graph());
- }
- public Graph()
- {
- int[] dims = { 4, 4, 2, 3 }; // Replace with your network dimensions.
- string file = "iris_data.csv"; // Replace with your input file location.
- network = new Network(dims, file);
- Initialise();
- }
- private void Initialise()
- {
- ClientSize = new Size(400, 400);
- SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque, true);
- FormBorderStyle = FormBorderStyle.FixedToolWindow;
- StartPosition = FormStartPosition.CenterScreen;
- KeyDown += new KeyEventHandler(Graph_KeyDown);
- }
- protected override void OnPaint(PaintEventArgs e)
- {
- double error = network.Train();
- UpdatePlotArea(e.Graphics, error);
- iteration++;
- Invalidate();
- }
- private void UpdatePlotArea(Graphics g, double error)
- {
- string banner = "Iteration={0} Error={1:0.00}";
- Text = string.Format(banner, iteration, error);
- g.FillRectangle(Brushes.White, 0, 0, 400, 400);
- foreach (float[] point in network.Points2D())
- {
- g.FillRectangle(brushes[(int)point[2]], point[0] * 395, point[1] * 395, 5, 5);
- }
- foreach (double[] line in network.HyperPlanes())
- {
- double a = -line[0] / line[1];
- double c = -line[2] / line[1];
- Point left = new Point(0, (int)(c * 400));
- Point right = new Point(400, (int)((a + c) * 400));
- g.DrawLine(new Pen(Color.Gray), left, right);
- }
- }
- private void Graph_KeyDown(object sender, KeyEventArgs e)
- {
- if (e.KeyCode == Keys.Space)
- {
- network.Initialise();
- iteration = 0;
- }
- }
- }

**Network.cs**

As the name suggests, this is where the logic of the network resides. The big difference here between this and my previous project is that it can handle multiple outputs. In addition, the new constructor provides the ability to define any network architecture using an integer array. Thus, { 4, 4, 2, 3 } represents a network with four inputs, a first hidden layer with four neurons, a second hidden layer with two neurons, and a final output layer with three neurons.

- using System;
- using System.Collections.Generic;
- using System.IO;
- public class Network : List<Layer>
- {
- private int[] dimensions;
- private List<Pattern> patterns;
- public Network(int[] dimensions, string file)
- {
- this.dimensions = dimensions;
- Initialise();
- LoadPatterns(file);
- }
- public void Initialise()
- {
- base.Clear();
- base.Add(new Layer(dimensions[0]));
- for (int i = 1; i < dimensions.Length; i++)
- {
- base.Add(new Layer(dimensions[i], base[i - 1], new Random()));
- }
- }
- private void LoadPatterns(string file)
- {
- patterns = new List<Pattern>();
- StreamReader reader = File.OpenText(file);
- while (!reader.EndOfStream)
- {
- string line = reader.ReadLine();
- patterns.Add(new Pattern(line, Inputs.Count, Outputs.Count));
- }
- reader.Close();
- }
- public double Train()
- {
- double error = 0;
- foreach (Pattern pattern in patterns)
- {
- Activate(pattern);
- for (int i = 0; i < Outputs.Count; i++)
- {
- double delta = pattern.Outputs[i] - Outputs[i].Output;
- Outputs[i].CollectError(delta);
- error += Math.Pow(delta, 2);
- }
- AdjustWeights();
- }
- return error;
- }
- private void Activate(Pattern pattern)
- {
- for (int i = 0; i < Inputs.Count; i++)
- {
- Inputs[i].Output = pattern.Inputs[i];
- }
- for (int i = 1; i < base.Count; i++)
- {
- foreach (Neuron neuron in base[i])
- {
- neuron.Activate();
- }
- }
- }
- private void AdjustWeights()
- {
- for (int i = base.Count - 1; i > 0; i--)
- {
- foreach (Neuron neuron in base[i])
- {
- neuron.AdjustWeights();
- }
- }
- }
- public List<double[]> HyperPlanes()
- {
- List<double[]> lines = new List<double[]>();
- foreach (Neuron n in Outputs)
- {
- lines.Add(n.HyperPlane);
- }
- return lines;
- }
- public List<float[]> Points2D()
- {
- int penultimate = base.Count - 2;
- if (base[penultimate].Count != 2)
- {
- throw new Exception("Penultimate layer must be 2D for graphing.");
- }
- List<float[]> points = new List<float[]>();
- for (int i = 0; i < patterns.Count; i++)
- {
- Activate(patterns[i]);
- float[] point = new float[3];
- point[0] = (float)base[penultimate][0].Output;
- point[1] = (float)base[penultimate][1].Output;
- if (Outputs.Count > 1)
- {
- point[2] = patterns[i].MaxOutput;
- }
- else
- {
- point[2] = (patterns[i].Outputs[0] >= 0.5) ? 1 : 0;
- }
- points.Add(point);
- }
- return points;
- }
- private Layer Inputs
- {
- get { return base[0]; }
- }
- private Layer Outputs
- {
- get { return base[base.Count - 1]; }
- }
- }

**Neuron.cs**

This class represents the neuron, and contains activation and training logic.

- using System;
- using System.Collections.Generic;
- public class Neuron
- {
- private double bias; // Bias value.
- private double error; // Sum of error.
- private double input; // Sum of inputs.
- private double gradient = 5; // Steepness of sigmoid curve.
- private double learnRate = 0.01; // Learning rate.
- private double output = double.MinValue; // Preset value of neuron.
- private List<Weight> weights; // Collection of weights to inputs.
- public Neuron() { }
- public Neuron(Layer inputs, Random rnd)
- {
- weights = new List<Weight>();
- foreach (Neuron input in inputs)
- {
- Weight w = new Weight();
- w.Input = input;
- w.Value = rnd.NextDouble() * 2 - 1;
- weights.Add(w);
- }
- }
- public void Activate()
- {
- error = 0;
- input = 0;
- foreach (Weight w in weights)
- {
- input += w.Value * w.Input.Output;
- }
- }
- public void CollectError(double delta)
- {
- if (weights != null)
- {
- error += delta;
- foreach (Weight w in weights)
- {
- w.Input.CollectError(error * w.Value);
- }
- }
- }
- public void AdjustWeights()
- {
- for (int i = 0; i < weights.Count; i++)
- {
- weights[i].Value += error * Derivative * learnRate * weights[i].Input.Output;
- }
- bias += error * Derivative * learnRate;
- }
- private double Derivative
- {
- get
- {
- double activation = Output;
- return activation * (1 - activation);
- }
- }
- public double Output
- {
- get
- {
- if (output != double.MinValue)
- {
- return output;
- }
- return 1 / (1 + Math.Exp(-gradient * (input + bias)));
- }
- set
- {
- output = value;
- }
- }
- public double[] HyperPlane
- {
- get
- {
- double[] line = new double[3];
- line[0] = weights[0].Value;
- line[1] = weights[1].Value;
- line[2] = bias;
- return line;
- }
- }
- }

**Layer.cs**

This class inherits from *List<Neuron>* and simply holds a collection of neurons representing a discrete layer within the network.

- using System;
- using System.Collections.Generic;
- public class Layer : List<Neuron>
- {
- public Layer(int size)
- {
- for (int i = 0; i < size; i++)
- base.Add(new Neuron());
- }
- public Layer(int size, Layer layer, Random rnd)
- {
- for (int i = 0; i < size; i++)
- base.Add(new Neuron(layer, rnd));
- }
- }

**Weight.cs**

This class holds a pointer to a contributing neuron and the associated weight value.

- public class Weight
- {
- public Neuron Input;
- public double Value;
- }

**Pattern.cs**

This class holds a single line of data from your input file in a form that can be consumed by the network.

- using System;
- public class Pattern
- {
- private double[] inputs;
- private double[] outputs;
- public Pattern(string value, int inputDims, int outputDims)
- {
- string[] line = value.Split(',');
- if (line.Length != inputDims + outputDims)
- throw new Exception("Input does not match network configuration");
- inputs = new double[inputDims];
- for (int i = 0; i < inputDims; i++)
- {
- inputs[i] = double.Parse(line[i]);
- }
- outputs = new double[outputDims];
- for (int i = 0; i < outputDims; i++)
- {
- outputs[i] = double.Parse(line[i + inputDims]);
- }
- }
- public int MaxOutput
- {
- get
- {
- int item = -1;
- double max = double.MinValue;
- for (int i = 0; i < Outputs.Length; i++)
- {
- if (Outputs[i] > max)
- {
- max = Outputs[i];
- item = i;
- }
- }
- return item;
- }
- }
- public double[] Inputs
- {
- get { return inputs; }
- }
- public double[] Outputs
- {
- get { return outputs; }
- }
- }

I hope you find this network useful. If you have any question or suggestions, I would be happy to hear from you.

### Train Neural Networks with Back Propagation C#

In my previous post, I showed how multi layer Perceptrons could be used to solve linearly non-separable problems. In that example, I calculated all the network weights by hand. In this post, I shall introduce the back propagation training algorithm, which will do all the hard work for us.

The back propagation algorithm has become the de facto training algorithm for artificial neural networks, and has been studied by the artificial intelligence community since the 1970s. It is used in commercial neural network software packages, such a MATLAB.

The principle of back propagation is actually quite easy to understand, even though the maths behind it can look rather daunting. The basic steps are:

- Initialise the network with small random weights.
- Present an input pattern to the input layer of the network.
- Feed the input pattern forward through the network to calculate its activation value.
- Take the difference between desired output and the activation value to calculate the network’s activation error.
- Adjust the weights feeding the output neuron to reduce its activation error for this input pattern.
- Propagate an error value back to each hidden neuron that is proportional to their contribution of the network’s activation error.
- Adjust the weights feeding each hidden neuron to reduce their contribution of error for this input pattern.
- Repeat steps 2 to 7 for each input pattern in the input collection.
- Repeat step 8 until the network is suitably trained.

It is important to note that each pattern is presented in turn, and the network adjusted slightly, before moving on to the next pattern. If we simply let the network perfectly correct the errors before moving onto the next pattern, it would never learn a generalised solution for the entire input collection.

The magic really happens in step 6, which determines how much error to feed back to each hidden neuron. Once the error value has been established, training can continue as described in my post about the single layer perceptron.

To illustrate how the error value is calculated, I will use this network diagram.

Then, if we use these variables:

*output_o* = Activation value of the output neuron

*error_o* = Error at the output neuron

*error_h* = Error at a hidden neuron

*weight_ho* = A weight connecting a hidden neuron to the output neuron

The error feed back to a hidden neuron is calculated:

*error_h = error_o * Derivative(output_o) * weight_ho*

For an explaination about how to calculate the derivative value, see my post on the sigmoid function.

Unlike the single layer Perceptron, training a multi layer Perceptron with back propagation does not guarantee a solution, even if one is available. This is because training can become stuck in a local error minimum. There are a number of strategies to overcome this, which I shall cover another time. For now, restarting training is normally sufficient for small networks.

I will continue to use the same classification problem from my last post.

Representing these input patterns. You should copy and paste these into a Patterns.csv file to use in the code sample below:

0.11, 0.11, 0

0.11, 0.82, 0

0.13, 0.17, 0

0.20, 0.81, 0

0.21, 0.57, 1

0.25, 0.52, 1

0.26, 0.48, 1

0.28, 0.17, 1

0.28, 0.45, 1

0.37, 0.28, 1

0.41, 0.92, 0

0.43, 0.04, 1

0.44, 0.55, 1

0.47, 0.84, 0

0.50, 0.36, 1

0.51, 0.96, 0

0.56, 0.62, 1

0.65, 0.01, 1

0.67, 0.50, 1

0.73, 0.05, 1

0.73, 0.90, 0

0.73, 0.99, 0

0.78, 0.01, 1

0.83, 0.62, 0

0.86, 0.42, 1

0.86, 0.91, 0

0.89, 0.12, 1

0.95, 0.15, 1

0.98, 0.73, 0

The code below is my implementation of back propagation in C#. In my opinion C# Generics are a beautiful thing, and you will see that I use them extensively. To run this code, create a new C# Console application and paste the code into the Program.cs file. Paste the input patterns into a file named Patterns.csv located in your project directory. Include Patterns.csv in your project, and make sure you set its “Copy to Output Directory” attribute to True.

- using System;
- using System.Collections.Generic;
- using System.IO;
- public class Network
- {
- private int _hiddenDims = 2; // Number of hidden neurons.
- private int _inputDims = 2; // Number of input neurons.
- private int _iteration; // Current training iteration.
- private int _restartAfter = 2000; // Restart training if iterations exceed this.
- private Layer _hidden; // Collection of hidden neurons.
- private Layer _inputs; // Collection of input neurons.
- private List<Pattern> _patterns; // Collection of training patterns.
- private Neuron _output; // Output neuron.
- private Random _rnd = new Random(); // Global random number generator.
- [STAThread]
- static void Main()
- {
- new Network();
- }
- public Network()
- {
- LoadPatterns();
- Initialise();
- Train();
- Test();
- }
- private void Train()
- {
- double error;
- do
- {
- error = 0;
- foreach (Pattern pattern in _patterns)
- {
- double delta = pattern.Output - Activate(pattern);
- AdjustWeights(delta);
- error += Math.Pow(delta, 2);
- }
- Console.WriteLine("Iteration {0}tError {1:0.000}", _iteration, error);
- _iteration++;
- if (_iteration > _restartAfter) Initialise();
- } while (error > 0.1);
- }
- private void Test()
- {
- Console.WriteLine("nBegin network testingnPress Ctrl C to exitn");
- while (1 == 1)
- {
- try
- {
- Console.Write("Input x, y: ");
- string values = Console.ReadLine() + ",0";
- Console.WriteLine("{0:0}n", Activate(new Pattern(values, _inputDims)));
- }
- catch (Exception e)
- {
- Console.WriteLine(e.Message);
- }
- }
- }
- private double Activate(Pattern pattern)
- {
- for (int i = 0; i < pattern.Inputs.Length; i++)
- {
- _inputs[i].Output = pattern.Inputs[i];
- }
- foreach (Neuron neuron in _hidden)
- {
- neuron.Activate();
- }
- _output.Activate();
- return _output.Output;
- }
- private void AdjustWeights(double delta)
- {
- _output.AdjustWeights(delta);
- foreach (Neuron neuron in _hidden)
- {
- neuron.AdjustWeights(_output.ErrorFeedback(neuron));
- }
- }
- private void Initialise()
- {
- _inputs = new Layer(_inputDims);
- _hidden = new Layer(_hiddenDims, _inputs, _rnd);
- _output = new Neuron(_hidden, _rnd);
- _iteration = 0;
- Console.WriteLine("Network Initialised");
- }
- private void LoadPatterns()
- {
- _patterns = new List<Pattern>();
- StreamReader file = File.OpenText("Patterns.csv");
- while (!file.EndOfStream)
- {
- string line = file.ReadLine();
- _patterns.Add(new Pattern(line, _inputDims));
- }
- file.Close();
- }
- }
- public class Layer : List<Neuron>
- {
- public Layer(int size)
- {
- for (int i = 0; i < size; i++)
- base.Add(new Neuron());
- }
- public Layer(int size, Layer layer, Random rnd)
- {
- for (int i = 0; i < size; i++)
- base.Add(new Neuron(layer, rnd));
- }
- }
- public class Neuron
- {
- private double _bias; // Bias value.
- private double _error; // Sum of error.
- private double _input; // Sum of inputs.
- private double _lambda = 6; // Steepness of sigmoid curve.
- private double _learnRate = 0.5; // Learning rate.
- private double _output = double.MinValue; // Preset value of neuron.
- private List<Weight> _weights; // Collection of weights to inputs.
- public Neuron() { }
- public Neuron(Layer inputs, Random rnd)
- {
- _weights = new List<Weight>();
- foreach (Neuron input in inputs)
- {
- Weight w = new Weight();
- w.Input = input;
- w.Value = rnd.NextDouble() * 2 - 1;
- _weights.Add(w);
- }
- }
- public void Activate()
- {
- _input = 0;
- foreach (Weight w in _weights)
- {
- _input += w.Value * w.Input.Output;
- }
- }
- public double ErrorFeedback(Neuron input)
- {
- Weight w = _weights.Find(delegate(Weight t) { return t.Input == input; });
- return _error * Derivative * w.Value;
- }
- public void AdjustWeights(double value)
- {
- _error = value;
- for (int i = 0; i < _weights.Count; i++)
- {
- _weights[i].Value += _error * Derivative * _learnRate * _weights[i].Input.Output;
- }
- _bias += _error * Derivative * _learnRate;
- }
- private double Derivative
- {
- get
- {
- double activation = Output;
- return activation * (1 - activation);
- }
- }
- public double Output
- {
- get
- {
- if (_output != double.MinValue)
- {
- return _output;
- }
- return 1 / (1 + Math.Exp(-_lambda * (_input + _bias)));
- }
- set
- {
- _output = value;
- }
- }
- }
- public class Pattern
- {
- private double[] _inputs;
- private double _output;
- public Pattern(string value, int inputSize)
- {
- string[] line = value.Split(',');
- if (line.Length - 1 != inputSize)
- throw new Exception("Input does not match network configuration");
- _inputs = new double[inputSize];
- for (int i = 0; i < inputSize; i++)
- {
- _inputs[i] = double.Parse(line[i]);
- }
- _output = double.Parse(line[inputSize]);
- }
- public double[] Inputs
- {
- get { return _inputs; }
- }
- public double Output
- {
- get { return _output; }
- }
- }
- public class Weight
- {
- public Neuron Input;
- public double Value;
- }

When the application runs, it will use the back propagation algorithm to train the network, restarting if it gets trapped in a local error minimum. Once fully trained, you will be able to test the network against untrained points on the graph and observe that it generalises correctly.

It is simple to modify the code to accept more input dimensions and use more hidden neurons, by changing the variables *_inputDims* and *_hiddenDims*. If you try this, make sure to add extra columns to the Patterns.csv file. By doing this, this network can be used to solve very complex problems.

In future posts, I will be using networks like this to solve real world problems - I would welcome suggestions.

John

### Hidden Neurons and Feature Space

In this post, I continue on the journey to solve linearly non-separable problems using the Multi Layer Perceptron. I will be using the same problem that I introduced last week.

The network I will be using to solve this problem is shown below. If you read my previous post, you will notice that I have introduced a bias to the network. Without a bias, any hyperplane must always pass through the origin, i.e. (0, 0), which is an unnecessary restriction.

The role of the two hidden neurons is divide input space into partitions. In order to achieve this, I have chosen two arbitrary hyperplanes and drawn them on the graph below.

The values in the equations map directly to the weights in the network. However, first the equations must be rearranged with all terms on the same side of the equals sign, i.e. 0 = y + 0.36x - 0.85, etc. Therefore, the weights in the network are as follows:

yh1 = 1

bh1 = -0.85xh2 = 1.92

yh2 = 1

bh2 = -0.70

Using the sigmoid function introduced in my last post, this creates a feature space that looks like this, with h1 along the horizontal axis and h2 along the vertical axis.

As you can see, feature space is a distorted view of input space. Each of the points representing a class clearly fall within a distinct quadrant of the graph, which is evidence that the weights have done their job.

However, this feature space is still linearly non-separable, so the output neuron will still fail in its task of correctly classifying the points. To correct this, we need to modify the sigmoid function, and introduce another variable known as lambda (λ).

- public double Function(double x)
- {
- return 1 / (1 + Math.Exp(-lambda * x));
- }

Lambda has the effect of steepening the gradient of the sigmoid function, which in turn further distorts input space. By using a lambda value of six, feature space now looks like this.

As you can see, this now results in a linearly separable pattern of points, which the output neuron can correctly classify. Again, the values in the equation map directly to the weights in the network. Therefore, the weights in the final layer of the network are as follows:

h2o = 1

bo = 0.21

Therefore, we now have a network that can correctly classify the points of a linearly non-separable problem.

However, so far, we have done all the work ourselves. How do we get the network to establish correctly the required values of the weights automatically? In order to do that, we need a learning algorithm. In my next post, I will introduce the Back Propagation algorithm and provide a working example written in C#.

In the meantime, if you have any questions on this post, drop me a comment.

John

### The Sigmoid Function C#

In my last post, I discussed the Single Layer Perceptron and its limitations regarding solving linearly non-separable problems. If we are to solve this type of problem, then we need a more sophisticated network, and that means adding layers. However, if we do that, how do we train the network?

Until now, we have used the error observed at the output neuron to adjust the weights between it and the input layer. But, what do we do if we add another layer in between, a hidden layer? Well, we still need to feed this error back through the network in order to adjust the weights, and this is a problem.

Currently, a neuron is either “on” or “off”, which is defined by the threshold activation function we are using.

- public int Function(double x)
- {
- return (x >= 0) ? 1 : -1;
- }

When graphed, it looks like this, with the blue line representing the function and the red line its derivative, which at zero is infinity (not very useful).

Any adjustment we make to the weights feeding the hidden layer is going to be rather course, so we need to smooth this out. We can do that by replacing our simple threshold function with something better. How about this? This is known as a sigmoid function.

- public double Sigmoid(double x)
- {
- return 2 / (1 + Math.Exp(-2 * x)) - 1;
- }

And its derivative.

f'(x) = 1 - f(x)^{2}

- public double Derivative(double x)
- {
- double s = Sigmoid(x);
- return 1 - (Math.Pow(s, 2));
- }

When graphed, it looks like this.

Now, this looks much more useful. There is a smooth and continuous transition between -1 and 1, and the derivative goes nowhere near infinity. Whilst this function is very popular with many neural net developers, I would like to make one further refinement. I like my neurons to be working in the range of 0 to 1, and to do that I need to modify the function slightly.

- public double Sigmoid(double x)
- {
- return 1 / (1 + Math.Exp(-x));
- }

And its derivative.

f'(x) = f(x)(1 - f(x))

- public double Derivative(double x)
- {
- double s = Sigmoid(x);
- return s * (1 - s);
- }

When graphed, it looks like this.

Now, that is perfect, and it has the added benefit of being computationally less demanding, which will be important for larger networks.

In my next post, I will show you how to use the sigmoid activation function to build a Multi Layer Perceptron, trained with the Back Propagation Algorithm.

I welcome comments on this post, and suggestions for future posts.

John

### The Single Layer Perceptron C#

This is the first in a series of posts in which I will write about the evolution of neural networks. I will start with the most simple network of all, the Single Layer Perceptron, and work through different architectures and learning methods which will eventually lead to networks that can predict stock market price movements, perform face recognition, handle natural language processing and much more.

I will provide full code samples, written in C#, which can be compiled and run by downloading Visual Studio.

The Perceptron is the grand daddy of all neural networks. It was invented in 1957 at the Cornell Aeronautical Laboratory by Frank Rosenblatt. The Perceptron is the simplest type of feed forward neural network, known as a linear classifier. This means that the type of problems the network can solve must be linearly separable. In the graphs shown below it is easy to visualise what this means in two dimensions.

This is linearly separable. |
This is linearly non-separable. |

The green line represents the separation between the two classes of data the network is attempting to classify. In three dimensions this would be represented by a plane, and in four dimensions or more by a hyperplane. There are other types of network that can solve linearly non-separable problems, which I will cover in later posts.

To begin to solve this problem we need a network as represented below.

As you can see, each input node is connected directly to the output node. By adjusting the value of the connecting weights, the network is able to learn.

In the demonstration below each of the points plotted in the first graph above will be used as training data. The training data will be repeatedly applied to the input nodes of the network and the weights adjusted until the network is performs as desired.

Once the network has been trained the application will step through the range of input data to prove that the network has learnt correctly and is able to perform good generalisation. The following code shows how this is done.

- using System;
- namespace Perceptron
- {
- public class Perceptron
- {
- [STAThread]
- static void Main()
- {
- // Load sample input patterns.
- double[,] inputs = new double[,] {
- { 0.72, 0.82 }, { 0.91, -0.69 }, { 0.46, 0.80 },
- { 0.03, 0.93 }, { 0.12, 0.25 }, { 0.96, 0.47 },
- { 0.79, -0.75 }, { 0.46, 0.98 }, { 0.66, 0.24 },
- { 0.72, -0.15 }, { 0.35, 0.01 }, { -0.16, 0.84 },
- { -0.04, 0.68 }, { -0.11, 0.10 }, { 0.31, -0.96 },
- { 0.00, -0.26 }, { -0.43, -0.65 }, { 0.57, -0.97 },
- { -0.47, -0.03 }, { -0.72, -0.64 }, { -0.57, 0.15 },
- { -0.25, -0.43 }, { 0.47, -0.88 }, { -0.12, -0.90 },
- { -0.58, 0.62 }, { -0.48, 0.05 }, { -0.79, -0.92 },
- { -0.42, -0.09 }, { -0.76, 0.65 }, { -0.77, -0.76 } };
- // Load sample output patterns.
- int[] outputs = new int[] {
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
- int patternCount = inputs.GetUpperBound(0) + 1;
- // Randomise weights.
- Random r = new Random();
- double[] weights = { r.NextDouble(), r.NextDouble() };
- // Set learning rate.
- double learningRate = 0.1;
- int iteration = 0;
- double globalError;
- do
- {
- globalError = 0;
- for (int p = 0; p < patternCount; p++)
- {
- // Calculate output.
- int output = Output(weights, inputs[p, 0], inputs[p, 1]);
- // Calculate error.
- double localError = outputs[p] - output;
- if (localError != 0)
- {
- // Update weights.
- for (int i = 0; i < 2; i++)
- {
- weights[i] += learningRate * localError * inputs[p, i];
- }
- }
- // Convert error to absolute value.
- globalError += Math.Abs(localError);
- }
- Console.WriteLine("Iteration {0}tError {1}", iteration, globalError);
- iteration++;
- } while (globalError != 0);
- // Display network generalisation.
- Console.WriteLine();
- Console.WriteLine("X, Y, Output");
- for (double x = -1; x <= 1; x += .5)
- {
- for (double y = -1; y <= 1; y += .5)
- {
- // Calculate output.
- int output = Output(weights, x, y);
- Console.WriteLine("{0}, {1}, {2}", x, y, (output == 1) ? "Blue" : "Red");
- }
- }
- Console.ReadKey();
- }
- private static int Output(double[] weights, double x, double y)
- {
- double sum = x * weights[0] + y * weights[1];
- return (sum >= 0) ? 1 : -1;
- }
- }
- }

The output from the network after training looks like this, which proves generalisation has been correctly achieved. Each pair of x and y coordinates when presented to the network returns the classification expected, i.e. blue or red.

-1.0, -1.0, Blue

-1.0, -0.5, Blue

-1.0, 0.0, Blue

-1.0, 0.5, Blue

-1.0, 1.0, Blue

-0.5, -1.0, Blue

-0.5, -0.5, Blue

-0.5, 0.0, Blue

-0.5, 0.5, Blue

-0.5, 1.0, Red

0.0, -1.0, Blue

0.0, -0.5, Blue

0.0, 0.0, Blue

0.0, 0.5, Red

0.0, 1.0, Red

0.5, -1.0, Blue

0.5, -0.5, Red

0.5, 0.0, Red

0.5, 0.5, Red

0.5, 1.0, Red

1.0, -1.0, Red

1.0, -0.5, Red

1.0, 0.0, Red

1.0, 0.5, Red

1.0, 1.0, Red

Whilst this may seem like a trivial problem to solve in two dimensions, the Perceptron can perform very powerful analysis in higher dimensions. The same general principals shown here will apply.

In my next post, I will start to write about the multi-layer perceptron, which can be used to solve linearly non-separable problems, like the one presented in the second graph above.

I welcome feedback on this post, and would be interested in receiving suggestions for future posts.