Theano学习与门
Theano learning AND gate
我写了一个简单的神经网络来学习与门。我试图理解为什么我的成本永远不会降低并且预测变量始终为 0.5:
import numpy as np
import theano
import theano.tensor as T
inputs = [[0,0], [1,1], [0,1], [1,0]]
outputs = [[0], [1], [0], [0]]
x = theano.shared(value=np.asarray(inputs), name='x')
y = theano.shared(value=np.asarray(outputs), name='y')
alpha = 0.1
w_array = np.asarray(np.random.uniform(low=-1, high=1, size=(2, 1)), dtype=theano.config.floatX)
w = theano.shared(value=w_array, name='w', borrow=True)
output = T.nnet.sigmoid(T.dot(x, w))
cost = T.sum((y - output) ** 2)
updates = [(w, w - alpha * T.grad(cost, w))]
train = theano.function(inputs=[], outputs=[], updates=updates)
test = theano.function(inputs=[], outputs=[output])
calc_cost = theano.function(inputs=[], outputs=[cost])
for i in range(60000):
if (i+1) % 10000 == 0:
print(i+1)
print(calc_cost())
train()
print(test())
输出始终相同:
10000
[array(1.0)]
20000
[array(1.0)]
30000
[array(1.0)]
40000
[array(1.0)]
50000
[array(1.0)]
60000
[array(1.0)]
[array([[ 0.5],
[ 0.5],
[ 0.5],
[ 0.5]])]
无论输入如何,它似乎总是预测 0.5,因为成本在学习过程中没有偏离 1
如果我将输出切换到 [[0], [1], [1], [1]]
以学习或门,我会得到正确的预测,并正确地降低成本
您的模型符合
<w, x>
因此它无法建立任何不穿过原点的分离。这样的等式只能表示通过点 (0,0) 的直线,显然分隔与门((1, 1) 与其他任何东西)的直线不穿过原点。您必须添加 bias 项,因此您的模型是
<w, x> + b
我写了一个简单的神经网络来学习与门。我试图理解为什么我的成本永远不会降低并且预测变量始终为 0.5:
import numpy as np
import theano
import theano.tensor as T
inputs = [[0,0], [1,1], [0,1], [1,0]]
outputs = [[0], [1], [0], [0]]
x = theano.shared(value=np.asarray(inputs), name='x')
y = theano.shared(value=np.asarray(outputs), name='y')
alpha = 0.1
w_array = np.asarray(np.random.uniform(low=-1, high=1, size=(2, 1)), dtype=theano.config.floatX)
w = theano.shared(value=w_array, name='w', borrow=True)
output = T.nnet.sigmoid(T.dot(x, w))
cost = T.sum((y - output) ** 2)
updates = [(w, w - alpha * T.grad(cost, w))]
train = theano.function(inputs=[], outputs=[], updates=updates)
test = theano.function(inputs=[], outputs=[output])
calc_cost = theano.function(inputs=[], outputs=[cost])
for i in range(60000):
if (i+1) % 10000 == 0:
print(i+1)
print(calc_cost())
train()
print(test())
输出始终相同:
10000
[array(1.0)]
20000
[array(1.0)]
30000
[array(1.0)]
40000
[array(1.0)]
50000
[array(1.0)]
60000
[array(1.0)]
[array([[ 0.5],
[ 0.5],
[ 0.5],
[ 0.5]])]
无论输入如何,它似乎总是预测 0.5,因为成本在学习过程中没有偏离 1
如果我将输出切换到 [[0], [1], [1], [1]]
以学习或门,我会得到正确的预测,并正确地降低成本
您的模型符合
<w, x>
因此它无法建立任何不穿过原点的分离。这样的等式只能表示通过点 (0,0) 的直线,显然分隔与门((1, 1) 与其他任何东西)的直线不穿过原点。您必须添加 bias 项,因此您的模型是
<w, x> + b