与神经网络的XOR(Matlab)

时间:2015-05-11 09:06:43

标签: matlab neural-network xor

所以,我希望这是我正在做的一件非常愚蠢的事情,并且有一个简单的答案。我正在尝试训练一个2x3x1神经网络来解决XOR问题。它没有用,所以我决定深入了解发生了什么。最后,我决定自己分配权重。这是我提出的权重向量:

theta1 = [11 0 -5; 0 12 -7;18 17 -20];
theta2 = [14 13 -28 -6];

(用Matlab表示法)。我故意试图让两个权重不相同(除了零)

而且,我的代码在matlab中非常简单

function layer2 = xornn(iters)
    if nargin < 1
        iters = 50
    end
    function s = sigmoid(X)
        s = 1.0 ./ (1.0 + exp(-X));
    end
    T = [0 1 1 0];
    X = [0 0 1 1; 0 1 0 1; 1 1 1 1];
    theta1 = [11 0 -5; 0 12 -7;18 17 -20];
    theta2 = [14 13 -28 -6];
    for i = [1:iters]
        layer1 = [sigmoid(theta1 * X); 1 1 1 1];
        layer2 = sigmoid(theta2 * layer1)
        delta2 = T - layer2;
        delta1 = layer1 .* (1-layer1) .* (theta2' * delta2);
        % remove the bias from delta 1. There's no real point in a delta on the bias.
        delta1 = delta1(1:3,:);
        theta2d = delta2 * layer1';
        theta1d = delta1 * X';
        theta1 = theta1 - 0.1 * theta1d;
        theta2 = theta2 - 0.1 * theta2d;
    end
end

我相信这是对的。我用有限差分法测试了各种参数(thetas),看它们是否正确,它们似乎是。

但是,当我运行它时,它最终只归结为全部归零。如果我做xornn(1)(1次迭代)我得到

0.0027    0.9966    0.9904    0.0008

但是,如果我做xornn(35)

0.0026    0.9949    0.9572    0.0007

(它开始向错误的方向下降)当我到达xornn(45)时,我得到了

0.0018    0.0975    0.0000    0.0003

如果我运行10,000次迭代,它只返回所有0。

发生了什么事?我必须添加正规化吗?我原以为这么简单的网络不需要它。但是,无论如何,为什么它会摆脱我用手喂它的明显好的解决方案呢?

谢谢!

1 个答案:

答案 0 :(得分:0)

AAARRGGHHH!解决方案只是改变问题

theta1 = theta1 - 0.1 * theta1d;
theta2 = theta2 - 0.1 * theta2d;

theta1 = theta1 + 0.1 * theta1d;
theta2 = theta2 + 0.1 * theta2d;

叹息

现在,我需要弄清楚当我认为我在计算的是什么时,我是如何以某种方式计算负面衍生物的......没关系。无论如何,我会在这里张贴,以防它帮助其他人。

因此,z =是sigmoid的输入之和,y是sigmoid的输出。

C = -(T * Log[y] + (1-T) * Log[(1-y))

dC/dy = -((T/y) - (1-T)/(1-y))
      = -((T(1-y)-y(1-T))/(y(1-y)))
      = -((T-Ty-y+Ty)/(y(1-y)))
      = -((T-y)/(y(1-y)))
      = ((y-T)/(y(1-y))) # This is the source of all my woes.
dy/dz = y(1-y)
dC/dz = ((y-T)/(y(1-y))) * y(1-y)
      = (y-T)

所以,问题在于,我不小心在计算T-y,因为我忘记了成本函数前面的负号。然后,我减去了我认为的渐变,但实际上是负梯度。而且,那里。这就是问题所在。

一旦我这样做了:

function layer2 = xornn(iters)
    if nargin < 1
        iters = 50
    end
    function s = sigmoid(X)
        s = 1.0 ./ (1.0 + exp(-X));
    end
    T = [0 1 1 0];
    X = [0 0 1 1; 0 1 0 1; 1 1 1 1];
    theta1 = [11 0 -5; 0 12 -7;18 17 -20];
    theta2 = [14 13 -28 -6];
    for i = [1:iters]
        layer1 = [sigmoid(theta1 * X); 1 1 1 1];
        layer2 = sigmoid(theta2 * layer1)
        delta2 = T - layer2;
        delta1 = layer1 .* (1-layer1) .* (theta2' * delta2);
        % remove the bias from delta 1. There's no real point in a delta on the bias.
        delta1 = delta1(1:3,:);
        theta2d = delta2 * layer1';
        theta1d = delta1 * X';
        theta1 = theta1 + 0.1 * theta1d;
        theta2 = theta2 + 0.1 * theta2d;
    end
end

xornn(50)返回0.0028 0.9972 0.9948 0.0009和 xornn(10000)返回0.0016 0.9989 0.9993 0.0005

唷!也许这会帮助其他人调试他们的版本..

相关问题