Created
September 25, 2017 01:12
-
-
Save diestrin/5db801ae65361e26f8b76ac4b1741720 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Neuron { | |
constructor() { | |
this.theta0 = 0; | |
this.theta1 = 0; | |
} | |
/** | |
* @param {number} value | |
*/ | |
predict(value) { | |
return this.theta0 + this.theta1 * value; | |
} | |
test(data) { | |
data.forEach(([x, y]) => | |
console.log( | |
'Predicting', x, | |
'expecting', y, | |
'got', Math.round(this.predict(x)))); | |
} | |
/** | |
* @param {any[]} arr | |
* @param {function} fn | |
*/ | |
sum(arr, fn) { | |
return arr.reduce((result, item) => result + fn(item), 0); | |
} | |
/** | |
* @param {number[][]} data | |
* @param {number} rate | |
* @param {number} useX | |
*/ | |
learn(data, rate, useX = false) { | |
const meanError = this.sum(data, ([x, y]) => { | |
const result = this.predict(x); | |
const error = (result - y) * (useX ? x : 1); | |
return error; | |
}) / data.length; | |
return rate * meanError; | |
} | |
/** | |
* @param {number[][]} data | |
* @param {number} learnRate | |
* @param {number} cycles | |
*/ | |
train(data, learnRate, cycles) { | |
while(cycles--) { | |
const [t0, t1] = [ | |
this.theta0 - this.learn(data, learnRate), | |
this.theta1 - this.learn(data, learnRate, true) | |
]; | |
this.theta0 = t0; | |
this.theta1 = t1; | |
} | |
} | |
} | |
const trainData = [ | |
[75, 2000], | |
[100, 5000], | |
[125, 7500], | |
[150, 8000] | |
]; | |
const testData = [ | |
[110, 5500], | |
[160, 8300], | |
[200, 10000] | |
]; | |
const neuron = new Neuron(); | |
neuron.train(trainData, 0.00001, 80); | |
neuron.test(testData); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment