具有神经网络(MATLAB)的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。

发生了什么事?我必须添加正规化吗?我本来会认为这样一个简单的网络不需要它。但是,无论如何,为什么它脱离了我手工喂的明显的好解决方案?

谢谢!

aaarrgghhh!解决方案只是更改

的问题
theta1 = theta1 - 0.1 * theta1d;
theta2 = theta2 - 0.1 * theta2d;

to

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

叹气

现在,我需要弄清楚当我认为自己正在计算的是...没关系时,我如何以某种方式计算负衍生物。无论如何,我会在这里发布,以防万一它可以帮助别人。

so,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

ph!也许这将帮助其他人调试他们的版本。

最新更新