Skip to content

Instantly share code, notes, and snippets.

@grimmdev
Last active March 2, 2018 04:48
Show Gist options
  • Save grimmdev/5394afd4779a490c3f003e45808622b1 to your computer and use it in GitHub Desktop.
Save grimmdev/5394afd4779a490c3f003e45808622b1 to your computer and use it in GitHub Desktop.
Perceptron for C# and Unity, based on PerceptronJS and the Perceptron Model.
using UnityEngine;
public class Perceptron {
private float accuracy = 0;
private int samples = 0;
private int[][] xtrain;
private int[] ytrain;
private int epochs;
private float learnrate;
private float bias = 0;
private float[] weights;
public Perceptron(int[][] x, int[] y, int e = 1000, float l = 0.1f) {
this.accuracy = 0;
this.samples = 0;
xtrain = x;
ytrain = y;
this.epochs = e;
this.learnrate = l;
this.bias = 0;
this.weights = new float[x[0].Length];
for (var n = 0; n < x[0].Length; n++) {
this.weights [n] = this.random();
}
}
private float current_accuracy()
{
return this.accuracy / this.samples;
}
private float random()
{
return Random.value * 2 - 1;
}
private int activation(float n)
{
return n < 0 ? 0 : 1;
}
private int predict(int[] input)
{
var total = this.bias;
for (int w = 0; w < weights.Length; w++) {
total += input [w] * weights [w];
}
return this.activation (total);
}
public void fit()
{
for (int a = 0; a < this.epochs; a++) {
for (int b = 0; b < this.xtrain.Length; b++) {
var prediction = this.predict (this.xtrain [b]);
Debug.Log ("Expected: " + this.ytrain [b] + " Model Output: " + prediction);
if (this.ytrain [b] == prediction) {
this.accuracy += 1;
} else {
this.accuracy -= 1;
}
this.samples++;
var loss = this.ytrain[b] - prediction;
for (int w = 0; w < this.weights.Length; w++) {
this.weights [w] += loss * this.xtrain [b] [w] * this.learnrate;
}
this.bias += loss * this.learnrate;
}
Debug.Log ("Accuracy: " + this.current_accuracy ());
}
}
}
using UnityEngine;
public class TestPerceptron : MonoBehaviour {
private void Awake()
{
int[][] x = new int[3][];
// 111
x[0] = new int[3];
x [0] [0] = 1;
x [0] [1] = 1;
x [0] [2] = 1;
// 000
x[1] = new int[3];
x [1] [0] = 0;
x [1] [1] = 0;
x [1] [2] = 0;
// 101
x[2] = new int[3];
x [2] [0] = 1;
x [2] [1] = 0;
x [2] [2] = 1;
int[] y = { 1, 0, 1 };
var p = new Perceptron (x, y, 10, 0.1f);
p.fit ();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment