python - 为什么一个简单的 2 层神经网络无法学习 0,0 序列?

标签 python machine-learning neural-network

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

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

[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)

训练完这个神经网络后,我们对其进行测试。

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

好的,0,11,0 是我们所期望的。 0,01,1 的预测也是可以解释的,我们的神经网络只是没有这些情况的训练数据,所以让我们将它添加到我们的训练数据集中:

[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

这意味着神经网络仍然不确定0,0,在我们训练它之前它不确定1,1

最佳答案

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

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

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

编辑:

您需要将偏差添加到代码中。

# 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

关于python - 为什么一个简单的 2 层神经网络无法学习 0,0 序列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38248657/

相关文章:

machine-learning - 如何制作非静态的Caffe网络架构?

python - 如何使用 cv2 矩形 (YOLOv5) 从 "results.xyxy[0]"绘制边界框?

machine-learning - 自动编码器可以用于重建非二进制向量吗?

python - 从 CNN 层转到线性层时层尺寸不匹配

python - 使用连续数字将列表向左和向右扩展至总长度的 50%

python - 在 Pygame 中后台 blit 代码中创建的 TypeError

python 嵌套 dict 到 csv 有很多列

python - 在固定时间内接受多个输入

python - 如何在 NiftyNet 中实现迁移学习?

javascript - NOT 函数的 bool 感知器