Skip to content

Instantly share code, notes, and snippets.

@danglingfarpointer
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danglingfarpointer/2fa56b9359ec2e260f6b to your computer and use it in GitHub Desktop.
Save danglingfarpointer/2fa56b9359ec2e260f6b to your computer and use it in GitHub Desktop.
Simple 2D perceptron
/*
Simple 2D perceptron
Copyright (c) 2014 danglingfarpointer
This program is distributed under the MIT License:
http://opensource.org/licenses/mit-license.php
*/
var signs = [
1, 1, 1, 1, -1, -1, -1, -1,
];
var samples = [
// [c, x, y]; c is always set to 1
[1, -2, 1],
[1, -1, 4],
[1, 1, 3],
[1, 3, 3],
[1, -3, -1],
[1, 0, -1],
[1, 2, 1],
[1, 3, 2],
];
var n = samples.length; // the number of samples
var d = samples[0].length; // dimension
// console.log(signs);
// console.log(samples);
// initialize
var ws = [];
for (var i = 0; i < d; ++i)
ws[i] = Math.random();
var stop;
do {
stop = true;
console.log((- ws[1] / ws[2]) + " * x + " + (- ws[0] / ws[2]));
for (var i = 0; i < n; ++i) {
var ans = 0;
for (var j = 0; j < d; ++j)
ans += samples[i][j] * ws[j];
if (0 < signs[i] && ans <= 0) {
stop = false;
for (var j = 0; j < d; ++j)
ws[j] += samples[i][j];
} else if (signs[i] <= 0 && 0 < ans) {
stop = false;
for (var j = 0; j < d; ++j)
ws[j] -= samples[i][j];
}
}
} while(!stop);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment