0

这段 JavaScript 代码代表了神经网络中简单感知器的概念。下面的代码预测除XOR 表之外的所有真值表都很好。请在浏览器的控制台窗口中运行此代码并找出问题所在。

由于这是一个简单的单个神经元,因此我没有对隐藏层给予太多重视。我正在训练这个高达 10,000 次迭代以获得更好的结果。

//AND GATE
var X1 = [0,1,1,0];
var X2 = [0,1,0,1];
var OUT = [0,1,0,0];

/*

//AND GATE
var X1 = [0,1,1,0];
var X2 = [0,1,0,1];
var OUT = [0,1,0,0];

//OR GATE
var X1 = [0,1,1,0];
var X2 = [0,1,0,1];
var OUT = [0,1,1,1];

//NAND GATE
var X1 = [0,1,1,0];
var X2 = [0,1,0,1];
var OUT = [1,0,1,1];

//NOR GATE
var X1 = [0,1,1,0];
var X2 = [0,1,0,1];
var OUT = [1,0,0,0];

//XOR GATE
var X1 = [0,1,1,0];
var X2 = [0,1,0,1];
var OUT = [0,0,1,1];

*/

var LR = 0.01; //Learning rate to speedup learning process.
var BIAS = 1; // Avoid sum become zero.
var TRAIN = 10000; //Epochs we need to run for accurate result
var WEIGHTS = [Math.random(),Math.random(),Math.random()]; //3 Random weights 2 for input & 1 for bias 

//console.log("Initial Weights : "+WEIGHTS);

function neuron(x1,x2,out){

var sum = 0;
var error = 0;

//Sum of weighted x1,x2 and bias
sum = x1*WEIGHTS[0] + x2*WEIGHTS[1] + BIAS*WEIGHTS[2];

//Heaviside step function as activation function
if(sum>1){
    sum = 1;
}else{
    sum = 0;
}

//Calculate the error
error = out - sum;

//Adjust weights
WEIGHTS[0] = WEIGHTS[0] + error * x1 * LR;  
WEIGHTS[1] = WEIGHTS[1] + error * x2 * LR;
WEIGHTS[2] = WEIGHTS[2] + error * BIAS * LR;

//console.log("Weights adjust : "+WEIGHTS);

}

function Train(){
//Epoch iteration eg- 10000 is good
for(var k=1;k<=TRAIN;k++){
//Train Four sets of truth table
for(var i=0;i<X1.length;i++){
neuron(X1[i],X2[i],OUT[i]);
}
}
}

function Predict(x1,x2){
var predict = 0;
predict = x1*WEIGHTS[0] + x2*WEIGHTS[1] + BIAS*WEIGHTS[2];

if(predict>1){
    predict = 1;
}else{
    predict = 0;
}
//Predict for given input
console.log("The prediction for "+(x1+","+x2)+" is "+predict);

}

//First train the perceptron 
Train();
//Predict for given input
Predict(1,1);
Predict(0,0);
Predict(1,0);
Predict(0,1);

异或门的输出是

The prediction for 1,1 is 1
The prediction for 0,0 is 1
The prediction for 1,0 is 1
The prediction for 0,1 is 1
4

1 回答 1

0

一些消息来源指出,用单个感知器无法解决 XOR 门。

其他来源让您知道您需要更高阶的感知器来使用单个感知器解决 XOR。

我引用第二个链接:

每个研究过神经网络的人都可能已经读过,单个感知器无法表示布尔 XOR 函数。人工智能的主要教科书《人工智能:一种现代方法》一书说:“[XOR] 不是线性可分的,因此感知器无法学习它”(第 730 页)。

我希望这能为您指明正确的方向。这种问题在这里并不新鲜

于 2020-04-20T15:51:02.063 回答