【问题标题】:Why is a simple 2-layer Neural Network unable to learn 0,0 sequence?为什么简单的 2 层神经网络无法学习 0,0 序列?
【发布时间】:2016-11-09 23:02:39
【问题描述】:

在查看一个微型 2 层神经网络的 example 时,我注意到了我无法解释的结果。

假设我们有以下带有相应标签的数据集:

[0,1] -> [0]
[0,1] -> [0]
[1,0] -> [1]
[1,0] -> [1]

让我们创建一个微型 2 层神经网络,它将学习预测两个数字序列的结果,其中每个数字可以是 0 或 1。我们将根据上述数据集训练这个神经网络。

    import numpy as np

    # compute sigmoid nonlinearity
    def sigmoid(x):
        output = 1 / (1 + np.exp(-x))
        return output

    # convert output of sigmoid function to its derivative
    def sigmoid_to_deriv(output):
        return output * (1 - output)

    def predict(inp, weigths):
        print inp, sigmoid(np.dot(inp, weigths))

    # input dataset
    X = np.array([ [0,1],
                   [0,1],
                   [1,0],
                   [1,0]])
    # output dataset
    Y = np.array([[0,0,1,1]]).T

    np.random.seed(1)

    # init weights randomly with mean 0
    weights0 = 2 * np.random.random((2,1)) - 1

    for i in xrange(10000):
        # forward propagation
        layer0 = X
        layer1 = sigmoid(np.dot(layer0, weights0))
        # compute the error
        layer1_error = layer1 - Y

        # gradient descent
        # calculate the slope at current x position
        layer1_delta = layer1_error * sigmoid_to_deriv(layer1)
        weights0_deriv = np.dot(layer0.T, layer1_delta)
        # change x by the negative of the slope (x = x - slope)
        weights0 -= weights0_deriv

    print 'INPUT   PREDICTION'
    predict([0,1], weights0)
    predict([1,0], weights0)
    # test prediction of the unknown data
    predict([1,1], weights0)
    predict([0,0], weights0)

在我们训练完这个 NN 之后,我们对其进行测试。

INPUT   PREDICTION
[0, 1] [ 0.00881315]
[1, 0] [ 0.99990851]
[1, 1] [ 0.5]
[0, 0] [ 0.5]

好的,0,11,0 是我们所期望的。 0,01,1 的预测也是可以解释的,我们的 NN 只是没有这些案例的训练数据,所以让我们将其添加到我们的训练数据集中:

[0,1] -> [0]
[0,1] -> [0]
[1,0] -> [1]
[1,0] -> [1]
[0,0] -> [0]
[1,1] -> [1]

重新训练网络并再次测试!

INPUT   PREDICTION
[0, 1] [ 0.00881315]
[1, 0] [ 0.99990851]
[1, 1] [ 0.9898148]
[0, 0] [ 0.5]
  • 等等,为什么 [0,0] 仍然是 0.5

这意味着 NN仍然不确定 0,0,与在我们训练它之前不确定 1,1 时相同。

【问题讨论】:

  • 我认为这个模型是正确的。网络能够成功区分数据。您现在只需添加一个阈值即可对数据进行分类。
  • 除非我遗漏了一些明显的东西,否则你没有偏见单位。预感,但我觉得在这个例子中,在没有偏置单元的情况下输入 [0,0] 会导致问题。由于它是一个小型网络,您可以通过在每个训练示例的末尾附加 1 并查看是否可以解决问题来解决此问题。

标签: python machine-learning neural-network


【解决方案1】:

分类也是对的。您需要了解网络能够分离测试集。

现在您需要使用步进函数来对01 之间的数据进行分类。

在您的情况下,0.5 似乎是一个不错的threshold

编辑:

您需要在代码中添加偏差。

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

# init weights randomly with mean 0
weights0 = 2 * np.random.random((3,1)) - 1

【讨论】:

  • 是的,添加一个偏差,如果您想解释原因,请考虑在没有偏差单元的神经网络中输入 [0,0] 会发生什么。由于神经网络在每一层之间执行乘法运算,因此权重没有影响,因为任何次数的 0 仍然是 0。因此,在最后一层,每个节点的激活为 0,并且当零被传递给 sigmoid函数,它输出 .5,这是你的网络输出的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-25
  • 2021-07-02
  • 2020-01-16
  • 2014-05-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多