# 手撸反向传播算法+代码实现

·  阅读 3684

## 关于代价函数的两个假设

1. 代价函数可以被写成在每一个训练样本 上的代价函数 的均值

2. 代价函数可以写成神经网络输出的函数。

## 反向传播算法

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 range(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_prime(z):
"""Derivative of the sigmoid function."""
return sigmoid(z)*(1-sigmoid(z))

（BP1） 得到证明。

（BP2） 得到证明。

（BP3） 得到证明。

（BP4） 得到证明。

## 参考文献

[1] Michael Nielsen. CHAPTER 2 How the backpropagation algorithm works[DB/OL]. neuralnetworksanddeeplearning.com/chap2.html, 2018-06-21.

[2] Zhu Xiaohu. Zhang Freeman.Another Chinese Translation of Neural Networks and Deep Learning[DB/OL]. github.com/zhanggyb/nn…, 2018-06-21.

[3] oio328Loio. 神经网络学习（三）反向（BP）传播算法（1）[DB/OL]. blog.csdn.net/hoho1151191…, 2018-06-25.