I put your code in a snippet, so you can run it here.
function f(x) {
//number is in negative it returns -1
if (x < 0) {
return -1
//number is in positive it returns 1
} else {
return 1
}
}
class Perceptron {
constructor() {
//two weights
this.weights = new Array(2)
//intitializing two random weights
for (let i = 0; i < this.weights.length; i++) {
this.weights[i] = Math.random() * 2 - 1
}
}
//prediction
guess(input) {
let sum = 0;
for (let i = 0; i < input.length; i++) {
sum += this.weights[i] * input[i] //sum of all product of inputs and weights
}
return f(sum) //returns -1 or 1
}
//training data
train(inputs, target) {
this.lr = 0.1 //learning rate
const guess = this.guess(inputs) //answer comes either 1 or -1
const err = target - guess //calc error
for (let i = 0; i < this.weights.length; i++) {
this.weights[i] += err * inputs[i] * this.lr // re adjust the weights
}
}
}
const brain = new Perceptron;
let data = [{
inputx: 1,
inputy: 1,
target: 1
},
{
inputx: 0,
inputy: 1,
target: -1
},
{
inputx: 1,
inputy: 0,
target: -1
},
{
inputx: 0,
inputy: 0,
target: -1
}
]
for (let i = 0; i < data.length; i++) {
let inputs = [data[i].inputx, data[i].inputy]
brain.train(inputs, data[i].target)
let guess = brain.guess([1, 0])
console.log(guess)
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…