我试图在python中使用numpy实现反向传播算法。我一直在使用本站实现矩阵形式的反向传播.在XOR上测试此代码时,即使在多次运行数千次迭代之后,我的网络也不会收敛。我认为有某种逻辑上的错误。如果有人愿意看一看,我将非常感激。完全可运行的代码可以在github中找到
import numpy as np
def backpropagate(network, tests, iterations=50):
#convert tests into numpy matrices
tests = [(np.matrix(inputs, dtype=np.float64).reshape(len(inputs), 1),
np.matrix(expected, dtype=np.float64).reshape(len(expected), 1))
for inputs, expected in tests]
for _ in range(iterations):
#accumulate the weight and bias deltas
weight_delta = [np.zeros(matrix.shape) for matrix in network.weights]
bias_delta = [np.zeros(matrix.shape) for matrix in network.bias]
#iterate over the tests
for potentials, expected in tests:
#input the potentials into the network
#calling the network with trace == True returns a list of matrices,
#representing the potentials of each layer
trace = network(potentials, trace=True)
errors = [expected - trace[-1]]
#iterate over the layers backwards
for weight_matrix, layer in reversed(list(zip(network.weights, trace))):
#compute the error vector for a layer
errors.append(np.multiply(weight_matrix.transpose()*errors[-1],
network.sigmoid.derivative(layer)))
#remove the input layer
errors.pop()
errors.reverse()
#compute the deltas for bias and weight
for index, error in enumerate(errors):
bias_delta[index] += error
weight_delta[index] += error * trace[index].transpose()
#apply the deltas
for index, delta in enumerate(weight_delta):
network.weights[index] += delta
for index, delta in enumerate(bias_delta):
network.bias[index] += delta此外,下面是计算输出的代码和我的sigmoid函数。bug不太可能出现在这里;我能够训练一个网络来模拟XOR,使用模拟退火。
# the call function of the neural network
def __call__(self, potentials, trace=True):
#ensure the input is properly formated
potentials = np.matrix(potentials, dtype=np.float64).reshape(len(potentials), 1)
#accumulate the trace
trace = [potentials]
#iterate over the weights
for index, weight_matrix in enumerate(self.weights):
potentials = weight_matrix * potentials + self.bias[index]
potentials = self.sigmoid(potentials)
trace.append(potentials)
return trace
#The sigmoid function that is stored in the network
def sigmoid(x):
return np.tanh(x)
sigmoid.derivative = lambda x : (1-np.square(x))发布于 2013-11-15 10:00:50
问题是缺少的步长参数。梯度应该是额外的缩放,而不是一次在权值空间中完成整个步骤。所以,它应该是:network.weights[index] += delta和network.bias[index] += delta,而不是:
def backpropagate(network, tests, stepSize = 0.01, iterations=50):
#...
network.weights[index] += stepSize * delta
#...
network.bias[index] += stepSize * deltahttps://stackoverflow.com/questions/19991431
复制相似问题