【发布时间】: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,1 和 1,0 是我们所期望的。 0,0 和 1,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