我试图(完全)掌握神经网络背后的想法,所以我从创建自己的简单感知器算法开始。
这是我的代码(在 JavaScript 中):
var lr = 0.1;//learning rate
//Initiate the weights randomly
function initWeights(weights, trainingSets){
for(var i=0; i<trainingSets[0].in.length; i++){
weights[i] = Math.random()*2 - 1;
}
weights.push(Math.random()*2 - 1); //b
}
//Return the raw activation value for a giving trainingSet
function getSum(weights, trainingSet){
var sum = 0;
for(var i=0; i < trainingSet.in.length; i++){
sum += weights[i]*trainingSet.in[i];
}
sum += 1 * weights[weights.length-1];
return sum;
}
//Activation function
function activate(value){
return (value >= 0)? 1 : 0;
}
function train(weights, trainingSets){
var error = 0;
for(var i=0; i<trainingSets.length; i++){
var currentSet = trainingSets[i];
var activationValue = getSum(weights, currentSet);
var error = currentSet.out - activate(activationValue);
error += error;
for(var j=0; j<weights.length-1; j++){
var deltaW = error * lr * currentSet.in[j];
weights[j] += deltaW;
}
weights[weights.length-1] += error * lr * 1;
}
return error/(weights.length);
}
var inp = [
{in:[1,1], out:1},
{in:[0,0], out:0},
{in:[0,1], out:0},
];
var w = [];
initWeights(w, inp);
//for(var j = 0; j < inp.length; j++){
var error = 1;
while(error >= 0.01){
error = train(w, inp);
}
//}
console.log("===")
var tester = {in:[1,0], out: NaN};
console.log(getSum(w, tester)) //should be negative
console.log("y=("+w[1]+"*x+"+w[2]+")/"+w[1])
结果不一致,(我正在使用 AND 算法来学习)。
情节应如下所示:
但通常如下所示:
我确定我在这里遗漏了一些小东西,
在此先感谢。