### 后向传播算法

1. 输入$x$：为输入层设置对应的激活$a^{1}$。

2. 向前反馈：对于每一层$l = 2, 3, \ldots, L$计算$z^{l} = w^l a^{l-1}+b^l$和$a^{l} = \sigma(z^{l})$。

3. 输出层误差$\delta^L$：计算向量$\delta^{L} = \nabla_a C \odot \sigma'(z^L)$。

4. 后向传播误差：对每一层$l = L-1, L-2, \ldots, 2$计算$\delta^{l} = ((w^{l+1})^T \delta^{l+1}) \odot \sigma'(z^{l})$。

5. 输出：代价函数的梯度为$\frac{\partial C}{\partial w^l_{jk}} = a^{l-1}_k \delta^l_j$和$\frac{\partial C}{\partial b^l_j} = \delta^l_j$。

#### 练习

• 具有一个神经元的后向传播 假设我们更改前向网络中的一个神经元以便这个神经元的输出是$f(\sum_j w_j x_j + b)$，其中$f$是某个非sigmoid的函数。那么我们应该如何更改这个后向传播算法？

• 线形神经元后向传播 假设我们将非线性的$\sigma$函数用$\sigma(z) = z$来替换，重写该后向传播算法。

1. 输入训练样本集合

2. 对于每一个训练样本$x$： 设置对应的输入激活$a^{x,1}$，执行以下步骤：

• 向前：对于每一层$l = 2, 3, \ldots, L$计算$z^{x,l} = w^l a^{x,l-1}+b^l$和$a^{x,l} = \sigma(z^{x,l})$。

• 输出层误差$\delta^{x,L}$：计算向量$\delta^{x,L} = \nabla_a C_x \odot \sigma'(z^{x,L})$。

• 后向传播误差：对于每一层$l = L-1, L-2, \ldots, 2$计算$\delta^{x,l} = ((w^{l+1})^T \delta^{x,l+1}) \odot \sigma'(z^{x,l})$。

3. 梯度下降：对于每一层$l = L, L-1, \ldots, 2$，按照规则$w^l \rightarrow w^l-\frac{\eta}{m} \sum_x \delta^{x,l} (a^{x,l-1})^T$更新权重，按照规则$b^l \rightarrow b^l-\frac{\eta}{m} \sum_x \delta^{x,l}$更新偏差。

### 后向传播的实施代码

class Network(object):
...
def update_mini_batch(self, mini_batch, eta):
"""Update the network's weights and biases by applying
gradient descent using backpropagation to a single mini batch.
The "mini_batch" is a list of tuples "(x, y)", and "eta"
is the learning rate."""
nabla_b = [np.zeros(b.shape) for b in self.biases]
nabla_w = [np.zeros(w.shape) for w in self.weights]
for x, y in mini_batch:
delta_nabla_b, delta_nabla_w = self.backprop(x, y)
nabla_b = [nb+dnb for nb, dnb in zip(nabla_b, delta_nabla_b)]
nabla_w = [nw+dnw for nw, dnw in zip(nabla_w, delta_nabla_w)]
self.weights = [w-(eta/len(mini_batch))*nw
for w, nw in zip(self.weights, nabla_w)]
self.biases = [b-(eta/len(mini_batch))*nb
for b, nb in zip(self.biases, nabla_b)]


class Network(object):
...
def backprop(self, x, y):
"""Return a tuple "(nabla_b, nabla_w)" representing the
gradient for the cost function C_x.  "nabla_b" and
"nabla_w" are layer-by-layer lists of numpy arrays, similar
to "self.biases" and "self.weights"."""
nabla_b = [np.zeros(b.shape) for b in self.biases]
nabla_w = [np.zeros(w.shape) for w in self.weights]
# feedforward
activation = x
activations = [x] # list to store all the activations, layer by layer
zs = [] # list to store all the z vectors, layer by layer
for b, w in zip(self.biases, self.weights):
z = np.dot(w, activation)+b
zs.append(z)
activation = sigmoid(z)
activations.append(activation)
# backward pass
delta = self.cost_derivative(activations[-1], y) * \
sigmoid_prime(zs[-1])
nabla_b[-1] = delta
nabla_w[-1] = np.dot(delta, activations[-2].transpose())
# Note that the variable l in the loop below is used a little
# differently to the notation in Chapter 2 of the book.  Here,
# l = 1 means the last layer of neurons, l = 2 is the
# second-last layer, and so on.  It's a renumbering of the
# scheme in the book, used here to take advantage of the fact
# that Python can use negative indices in lists.
for l in xrange(2, self.num_layers):
z = zs[-l]
sp = sigmoid_prime(z)
delta = np.dot(self.weights[-l+1].transpose(), delta) * sp
nabla_b[-l] = delta
nabla_w[-l] = np.dot(delta, activations[-l-1].transpose())
return (nabla_b, nabla_w)

...

def cost_derivative(self, output_activations, y):
"""Return the vector of partial derivatives \partial C_x /
\partial a for the output activations."""
return (output_activations-y)

def sigmoid(z):
"""The sigmoid function."""
return 1.0/(1.0+np.exp(-z))

def sigmoid_prime(z):
"""Derivative of the sigmoid function."""
return sigmoid(z)*(1-sigmoid(z))


#### 问题

• 对小批量样本完全基于矩阵的后向传播途径 我们实施随机梯度下降采用小批量样本不断循环的方式。可以更改后向传播算法，使得同时对小批量样本中的每一个样本计算梯度。思路就是我们可以替换单一输入向量$x$，而采用矩阵$X = [x_1 x_2 \ldots x_m]$，它的列就是小批量数量的维度。我们向前将其乘以权重矩阵，再加上偏差矩阵，最后实施sigmoid函数。我们也后向采用相似的方式。显示的写出这样的后向传播算法伪代码。更改network.py以便它使用完全基于矩阵的方式。这种方式的优势是它利用了当今线性代数库的优势。结果是这样能够比起小批量样本内不断循环方式运行更快。（比如在我的笔记本中，运行MNIST分类的速度将比上一节中的循环方式缩短二分之一。）实际上，所有后向传播库都使用完全矩阵方式或者它的某种变形。