仅用Python中的两个隐藏神经元无法解决XOR问题

时间:2019-05-25 20:23:45

标签: python numpy neural-network

我有一个小型的3层神经网络,其中包含两个输入神经元,两个隐藏神经元和一个输出神经元。我试图坚持仅使用2个隐藏神经元的以下格式。

enter image description here

我试图展示如何将其用作XOR逻辑门,但是只有两个隐藏的神经元,经过1,000,000次迭代后,我得到以下不良输出!

Input: 0 0   Output:  [0.01039096]
Input: 1 0   Output:  [0.93708829]
Input: 0 1   Output:  [0.93599738]
Input: 1 1   Output:  [0.51917667]

如果我使用三个隐藏的神经元,那么经过100,000次迭代,我的输出就会更好:

Input: 0 0   Output:  [0.01831612]
Input: 1 0   Output:  [0.98558057]
Input: 0 1   Output:  [0.98567602]
Input: 1 1   Output:  [0.02007876]

我在隐藏层中有3个神经元,但在隐藏层中没有2个神经元,得到了不错的输出。为什么?

根据下面的评论,此repo包含使用两个隐藏神经元解决XOR问题的高代码。

我不知道自己在做什么错。任何建议表示赞赏! 附上我的代码:

import numpy as np
import matplotlib
from matplotlib import pyplot as plt


# Sigmoid function
def sigmoid(x, deriv=False):
    if deriv:
        return x * (1 - x)
    return 1 / (1 + np.exp(-x))


alpha = [0.7]

# Input dataset
X = np.array([[0, 0],
              [0, 1],
              [1, 0],
              [1, 1]])

# Output dataset
y = np.array([[0, 1, 1, 0]]).T

# seed random numbers to make calculation deterministic
np.random.seed(1)

# initialise weights randomly with mean 0
syn0 = 2 * np.random.random((2, 3)) - 1  # 1st layer of weights synapse 0 connecting L0 to L1
syn1 = 2 * np.random.random((3, 1)) - 1  # 2nd layer of weights synapse 0 connecting L1 to L2

# Randomize inputs for stochastic gradient descent
data = np.hstack((X, y))    # append Input and output dataset
np.random.shuffle(data)     # shuffle
x, y = np.array_split(data, 2, 1)    # Split along vertical(1) axis

for iter in range(100000):
    for i in range(4):
        # forward prop
        layer0 = x[i]  # Input layer
        layer1 = sigmoid(np.dot(layer0, syn0))  # Prediction step for layer 1
        layer2 = sigmoid(np.dot(layer1, syn1))  # Prediction step for layer 2

        layer2_error = y[i] - layer2  # Compare how well layer2's guess was with input

        layer2_delta = layer2_error * sigmoid(layer2, deriv=True)  # Error weighted derivative step

        if iter % 10000 == 0:
            print("Error: ", str(np.mean(np.abs(layer2_error))))
            plt.plot(iter, layer2_error, 'ro')


        # Uses "confidence weighted error" from l2 to establish an error for l1
        layer1_error = layer2_delta.dot(syn1.T)

        layer1_delta = layer1_error * sigmoid(layer1, deriv=True)  # Error weighted derivative step

        # Since SGD we need to dot product two 1D arrays. This is how.
        syn1 += (alpha * np.dot(layer1[:, None], layer2_delta[None, :]))  # Update weights
        syn0 += (alpha * np.dot(layer0[:, None], layer1_delta[None, :]))

    # Training was done above, below we re run to test algorithm

    layer0 = X  # Input layer
    layer1 = sigmoid(np.dot(layer0, syn0))  # Prediction step for layer 1
    layer2 = sigmoid(np.dot(layer1, syn1))  # Prediction step for layer 2


plt.show()
print("output after training: \n")
print("Input: 0 0 \t Output: ", layer2[0])
print("Input: 1 0 \t Output: ", layer2[1])
print("Input: 0 1 \t Output: ", layer2[2])
print("Input: 1 1 \t Output: ", layer2[3])

2 个答案:

答案 0 :(得分:3)

这是由于您没有为神经元考虑任何bias的事实。 您仅使用权重来尝试拟合XOR模型。

在隐藏层中有2个神经元的情况下,网络无法适应,因为它无法补偿偏差。

在隐藏层中使用3个神经元时,多余的神经元会抵消由于缺乏偏见而引起的效果。

这是XOR门的网络示例。您会注意到theta(偏差)已添加到隐藏层。这为网络提供了一个额外的参数来调整。

enter image description here

Additional resources

答案 1 :(得分:2)

这是一个不可解的方程组,这就是为什么NN也不能解它的原因。 尽管可能过于简单,但是如果我们说传递函数是线性的,则表达式变为类似

z = (w1*x+w2*y)*w3 + (w4*x+w5*y)*w6

那么有4种情况:

xy=00, z=0 = 0
xy=10, z=1 = w1*w3+w4*w6
xy=01, z=1 = w2*w3+w5*w6
xy=11, z=0 = (w1+w2)*w3 + (w4+w5)*w6

问题是

0 = (w1+w2)*w3 + (w4+w5)*w6 = w1*w3+w2*w3 + w4*w6+w5*w6            <-- xy=11 line
                            = w1*w3+w4*w6 + w2*w3+w5*w6 = 1+1 = 2  <-- xy=10 and xy=01 lines

表面上6个自由度在这里还不够,这就是为什么您需要添加一些额外内容的原因。