我正在尝试AND
使用 python 中的 Theano 库通过神经网络实现操作。这是我的代码:
import theano
import theano.tensor as T
import numpy as np
import matplotlib.pyplot as plt
#Define variables:
x = T.matrix('x')
w1 = theano.shared(np.random.uniform(0,1,(3,3)))
w2 = theano.shared(np.random.uniform(0,1,(1,3)))
learning_rate = 0.01
#Define mathematical expression:c for forward pass
z1 = T.dot(x,w1)
a1 = 1/(1+T.exp(-z1))
z2 = T.dot(a1,w2.T)
a2 = 1/(1 + T.exp(-z2))
#Let’s determine the cost as follows:
a_hat = T.vector('a_hat') #Actual output
cost = -(a_hat*T.log(a2) + (1-a_hat)*T.log(1-a2)).sum()
dw2,dw1 = T.grad(cost,[w2,w1])
train = theano.function(
inputs = [x,a_hat],
outputs = [a2,cost],
updates = [
[w1, w1-learning_rate*dw1],
[w2, w2-learning_rate*dw2]
]
)
#Define inputs and weights
inputs = np.array([
[0, 0],
[0, 1],
[1, 0],
[1, 1]
])
inputs = np.append( np.ones((inputs.shape[0],1)), inputs, axis=1)
outputs = np.array([0,0,0,1]).T
#Iterate through all inputs and find outputs:
cost = []
for iteration in range(30000):
pred, cost_iter = train(inputs, outputs)
cost.append(cost_iter)
我无法追溯错误ValueError: Dimension mismatch; shapes are (*, *), (*, 4), (4, 1), (*, *), (*, 4), (4, 1) Apply node that caused the error:
。即使我改变了权重向量的维度w1
和w2
,误差仍然是一样的。我是 Theano 的新手,对调试它不太了解。有人可以帮我吗?谢谢。