反向传播算法代码

在理论上理解了反向传播算法后,就可以理解上一章中用来实现反向传播算法的代码了。回忆一下第一章Network类中的update_mini_batchbackprop方法的代码。这些代码可以看做是上面算法描述的直接翻译。具体来说,update_mini_batch方法通过计算梯度来为当前的小批次(mini_batch)更新Network的权重和偏置。

  1. class Network(object):
  2. ...
  3. def update_mini_batch(self, mini_batch, eta):
  4. """Update the network's weights and biases by applying
  5. gradient descent using backpropagation to a single mini batch.
  6. The "mini_batch" is a list of tuples "(x, y)", and "eta"
  7. is the learning rate."""
  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. for x, y in mini_batch:
  11. delta_nabla_b, delta_nabla_w = self.backprop(x, y)
  12. nabla_b = [nb+dnb for nb, dnb in zip(nabla_b, delta_nabla_b)]
  13. nabla_w = [nw+dnw for nw, dnw in zip(nabla_w, delta_nabla_w)]
  14. self.weights = [w-(eta/len(mini_batch))*nw
  15. for w, nw in zip(self.weights, nabla_w)]
  16. self.biases = [b-(eta/len(mini_batch))*nb
  17. for b, nb in zip(self.biases, nabla_b)]

大部分工作是由deltanabla_b, delta_nabla_w = self.backprop(x, y)这行代码完成的。它使用了backprop方法来计算偏导backprop方法基本上是按照上一节中描述的内容来实现的,但有一点不同:我们使用了一个稍微不同的方法来索引layer。这个改动利用了Python中列表负索引特性的优势来从后向前索引一个列表。例如,l[-3]代表列表l的倒数第三项。backprop方法的代码如下所示,同时还有一些帮助方法用来计算函数、的导数,以及代价函数的导数。你应该能够理解下面的代码了。但如果遇到了困难的话,可以参考第一章中对这段代码的描述。

  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. activation = x
  12. activations = [x] # list to store all the activations, layer by layer
  13. zs = [] # list to store all the z vectors, layer by layer
  14. for b, w in zip(self.biases, self.weights):
  15. z = np.dot(w, activation)+b
  16. zs.append(z)
  17. activation = sigmoid(z)
  18. activations.append(activation)
  19. # backward pass
  20. delta = self.cost_derivative(activations[-1], y) * \
  21. sigmoid_prime(zs[-1])
  22. nabla_b[-1] = delta
  23. nabla_w[-1] = np.dot(delta, activations[-2].transpose())
  24. # Note that the variable l in the loop below is used a little
  25. # differently to the notation in Chapter 2 of the book. Here,
  26. # l = 1 means the last layer of neurons, l = 2 is the
  27. # second-last layer, and so on. It's a renumbering of the
  28. # scheme in the book, used here to take advantage of the fact
  29. # that Python can use negative indices in lists.
  30. for l in xrange(2, self.num_layers):
  31. z = zs[-l]
  32. sp = sigmoid_prime(z)
  33. delta = np.dot(self.weights[-l+1].transpose(), delta) * sp
  34. nabla_b[-l] = delta
  35. nabla_w[-l] = np.dot(delta, activations[-l-1].transpose())
  36. return (nabla_b, nabla_w)
  37. ...
  38. def cost_derivative(self, output_activations, y):
  39. """Return the vector of partial derivatives \partial C_x /
  40. \partial a for the output activations."""
  41. return (output_activations-y)
  42. def sigmoid(z):
  43. """The sigmoid function."""
  44. return 1.0/(1.0+np.exp(-z))
  45. def sigmoid_prime(z):
  46. """Derivative of the sigmoid function."""
  47. return sigmoid(z)*(1-sigmoid(z))

问题

  • 在一个批次(mini-batch)上应用完全基于矩阵的反向传播方法
    在我们的随机梯度下降算法的实现中,我们需要依次遍历一个批次(mini-batch)中的训练样例。我们也可以修改反向传播算法,使得它可以同时为一个批次中的所有训练样例计算梯度。我们在输入时传入一个矩阵(而不是一个向量),这个矩阵的列代表了这一个批次中的向量。前向传播时,每一个节点都将输入乘以权重矩阵、加上偏置矩阵并应用sigmoid函数来得到输出,反向传播时也用类似的方式计算。明确地写出这种反向传播方法,并修改network.py,令其使用这种完全基于矩阵的方法进行计算。这种方式的优势在于它可以更好地利用现代线性函数库,并且比循环的方式运行得更快。(例如,在我的笔记本电脑上求解与上一章所讨论的问题相类似的MNIST分类问题时,最高可以达到两倍的速度。)在实践中,所有正规的反向传播算法库都使用了这种完全基于矩阵的方法或其变种。

原文: https://hit-scir.gitbooks.io/neural-networks-and-deep-learning-zh_cn/content/chap2/c2s7.html