[英]Simple Perceptron In Javascript for XOR gate
I tried to use a single perceptron to predict the XOR gate. 我试图使用单个感知器来预测XOR门。 However, the results seem to be completely random and I cannot find the error.
但是,结果似乎是完全随机的,我找不到错误。
What am I doing wrong here ? 我在这里做错了什么? - Is my training method wrong?
-我的训练方法错误吗? - or is there any error in the perceptron model ?
-或感知器模型有任何错误? - or a single perceptron cannot be used for this problem ?
-或单个感知器不能用于此问题?
class Perceptron {
constructor(input_nodes, learning_rate) {
this.nodes = input_nodes;
this.bias = Math.random() * 2 - 1;
this.learning_rate = learning_rate;
this.weights = [];
for (let i = 0; i < input_nodes; i++) {
this.weights.push(Math.random() * 2 - 1)
}
}
train (inputs, desired_output) {
// Guess the result
let guess = this.predict(inputs);
let error = desired_output - guess;
// Adjust weights and bias
for (let i = 0; i < this.weights.length; i++) {
this.weights[i] += this.learning_rate * error * inputs[i];
}
this.bias += error * this.learning_rate;
}
predict (input_array) {
if ( input_array.length != this.nodes) throw new Error({message: 'Invalid Input!'})
let sum = this.bias;
for (let i = 0; i < input_array.length; i++) {
sum += this.weights[i] * input_array[i];
}
return this.activate(sum);
}
activate (num) {
return num < 0 ? 0 : 1;
}
}
module.exports = Perceptron;
if ( require.main === module ) {
let p = new Perceptron(2, 0.003);
for ( let i = 0; i < 1000; i++ ) {
p.train([0, 0], 0);
p.train([0, 1], 1);
p.train([1, 0], 1);
p.train([1, 1], 0);
}
console.log( p.predict([0, 1]) )
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.