Skip to content

Instantly share code, notes, and snippets.

@deanmarano
Last active August 29, 2015 14:07
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 deanmarano/f2d053a9356ce80098a4 to your computer and use it in GitHub Desktop.
Save deanmarano/f2d053a9356ce80098a4 to your computer and use it in GitHub Desktop.
Machine Learning 4.2
"// noprotect";
var a = function() {
'use strict';
var examples = [
{inputs: {a: -1, b: -1}, output: -1},
{inputs: {a: -1, b: 1}, output: -1},
{inputs: {a: 1, b: -1}, output: 1},
{inputs: {a: 1, b: 1}, output: -1},
];
function train(examples) {
var positive = 0,
negative = 0,
update = 0,
n = 0.05,
w0 = Math.random() * 2 - 1,
w1 = Math.random() * 2 - 1,
w2 = Math.random() * 2 - 1;
for(var a = 0; a < 10000; a++) {
var example = examples[Math.floor(Math.random() * examples.length)];
var temp = (w0 + w1 * example.inputs.a + w2 * example.inputs.b);
var o = temp > 0 ? 1 : -1;
if(o == 1) { positive += 1; } else { negative += 1; }
var deltaw0 = n * (example.output - o) * w0;
var deltaw1 = n * (example.output - o) * w1;
var deltaw2 = n * (example.output - o) * w2;
w0 += deltaw0;
w1 += deltaw1;
w2 += deltaw2;
}
console.log('positive: ' + positive);
console.log('negative: ' + negative);
return {w0: w0, w1: w1, w2: w2};
}
var test = function(examples, weights) {
var results = examples.map(function(example) {
var temp = weights.w0 + weights.w1 * example.inputs.a + weights.w2 * example.inputs.b;
var o = temp > 0 ? 1 : -1;
console.log('example: ' + JSON.stringify(example) + ' result: ' + o);
return example.output == o;
});
var result = results.reduce(function(i, sum) { return i & sum; });
console.log('test result was: ' + result);
return result;
};
var t = false,
loopCounter = 0,
goodWeights = [];
while(!t) {
loopCounter += 1;
var weights = train(examples);
console.log('weights: ' + JSON.stringify(weights));
var testResult = test(examples, weights);
if(testResult) {
goodWeights.push(weights);
}
console.log('results of test ' + loopCounter + ': ' + testResult);
if(loopCounter > 500) {
t = true;
}
}
console.log('succeeded ' + goodWeights.length + ' times');
console.log(JSON.stringify(goodWeights));
}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment