反向传播算法代码

    1. class Network(object):
    2. ...
    3. def backprop(self, x, y):
    4. """Return a tuple "(nabla_b, nabla_w)" representing the
    5. gradient for the cost function C_x. "nabla_b" and
    6. "nabla_w" are layer-by-layer lists of numpy arrays, similar
    7. to "self.biases" and "self.weights"."""
    8. nabla_b = [np.zeros(b.shape) for b in self.biases]
    9. nabla_w = [np.zeros(w.shape) for w in self.weights]
    10. # feedforward
    11. activations = [x] # list to store all the activations, layer by layer
    12. zs = [] # list to store all the z vectors, layer by layer
    13. for b, w in zip(self.biases, self.weights):
    14. z = np.dot(w, activation)+b
    15. zs.append(z)
    16. activations.append(activation)
    17. # backward pass
    18. delta = self.cost_derivative(activations[-1], y) * \
    19. sigmoid_prime(zs[-1])
    20. nabla_b[-1] = delta
    21. nabla_w[-1] = np.dot(delta, activations[-2].transpose())
    22. # Note that the variable l in the loop below is used a little
    23. # differently to the notation in Chapter 2 of the book. Here,
    24. # l = 1 means the last layer of neurons, l = 2 is the
    25. # second-last layer, and so on. It's a renumbering of the
    26. # scheme in the book, used here to take advantage of the fact
    27. # that Python can use negative indices in lists.
    28. for l in xrange(2, self.num_layers):
    29. z = zs[-l]
    30. delta = np.dot(self.weights[-l+1].transpose(), delta) * sp
    31. nabla_b[-l] = delta
    32. return (nabla_b, nabla_w)
    33. ...
    34. def cost_derivative(self, output_activations, y):
    35. """Return the vector of partial derivatives \partial C_x /
    36. \partial a for the output activations."""
    37. return (output_activations-y)
    38. def sigmoid(z):
    39. """The sigmoid function."""
    40. return 1.0/(1.0+np.exp(-z))
    41. def sigmoid_prime(z):
    42. """Derivative of the sigmoid function."""
    43. return sigmoid(z)*(1-sigmoid(z))
    • 在一个批次(mini-batch)上应用完全基于矩阵的反向传播方法
      在我们的随机梯度下降算法的实现中,我们需要依次遍历一个批次(mini-batch)中的训练样例。我们也可以修改反向传播算法,使得它可以同时为一个批次中的所有训练样例计算梯度。我们在输入时传入一个矩阵(而不是一个向量),这个矩阵的列代表了这一个批次中的向量。前向传播时,每一个节点都将输入乘以权重矩阵、加上偏置矩阵并应用sigmoid函数来得到输出,反向传播时也用类似的方式计算。明确地写出这种反向传播方法,并修改,令其使用这种完全基于矩阵的方法进行计算。这种方式的优势在于它可以更好地利用现代线性函数库,并且比循环的方式运行得更快。(例如,在我的笔记本电脑上求解与上一章所讨论的问题相类似的MNIST分类问题时,最高可以达到两倍的速度。)在实践中,所有正规的反向传播算法库都使用了这种完全基于矩阵的方法或其变种。