【CSDN软件工程师能力认证学习精选】Python实现简单的神经网络( 三 )


接下来我们要想办法获得y p r e d {y_{pred}}ypred?和w1的关系,我们已经知道神经元h1、h2和o1的数学运算规则:
y p r e d = o 1 = f ( w 5 h 1 + w 6 h 2 + b 3 ) {y_{pred}=o_1=f(++b_3)}ypred?=o1?=f(w5?h1?+w6?h2?+b3?)
实际上只有神经元h1中包含权重w1,所以我们再次运用链式求导法则:
? y p r e d ? w 1 = ? y p r e d ? h 1 ? ? h 1 ? w 1 {\frac{\ y_{pred}}{\ w_1}=\frac{\ y_{pred}}{\ h_1}*\frac{\ h_1}{\ w_1}}?w1??ypred??=?h1??ypred????w1??h1??
? y p r e d ? h 1 = w 5 ? f ′ ( w 5 h 1 + w 6 h 2 + h 3 ) {\frac{\ y_{pred}}{\ h_1}=w_5*f'(++h_3)}?h1??ypred??=w5??f′(w5?h1?+w6?h2?+h3?)
然后求? h 1 ? w 1 {\frac{\ h_1}{\ w_1}}?w1??h1??:
h 1 = f ( w 1 x 1 + w 2 x 2 + b 1 ) {h_1=f(++b_1)}h1?=f(w1?x1?+w2?x2?+b1?)
? h 1 ? w 1 = x 1 ? f ′ ( w 1 x 1 + w 2 x 2 + h 1 ) {\frac{\ h_1}{\ w_1}=x_1*f'(++h_1)}?w1??h1??=x1??f′(w1?x1?+w2?x2?+h1?)
上面的计算中遇到了2次激活函数s i g m o i d {}的导数f ′ ( x ) {f'(x)}f′(x),s i g m o i d {}函数的导数很容易求得:f ( x ) = 1 1 + e ? x {f(x)=\frac{1}{1+e^{-x}}}f(x)=1+e?x1?
f ′ ( x ) = e x ( 1 + e ? x ) 2 = f ( x ) ? ( 1 ? f ( x ) ) {f'(x)=\frac{e^x}{(1+e^{-x})^2}=f(x)*(1-f(x))}f′(x)=(1+e?x)2ex?=f(x)?(1?f(x))
总的链式求导公式:
? L ? w 1 = ? L ? y p r e d ? ? y p r e d ? h 1 ? ? h 1 ? w 1 {\frac{\ L}{\ w_1}=\frac{\ L}{\ y_{pred}}*\frac{\ y_{pred}}{\ h_1}*\frac{\ h_1}{\ w_1}}?w1??L?=?ypred??L???h1??ypred????w1??h1??
这种向后计算偏导数的系统称为反向传播() 。
上面的数学符号太多,下面我们带入实际数值来计算一下 。h 1 、 h 2 和 o 1 {h_1、h_2和o_1}h1?、h2?和o1?
h 1 = f ( x 1 w 1 + x 2 w 2 + b 1 ) = 0.0474 {h_1=f(++b_1)=0.0474}h1?=f(x1?w1?+x2?w2?+b1?)=0.0474
h 2 = f ( x 3 w 3 + x 4 w 4 + b 2 ) = 0.0474 {h_2=f(++b_2)=0.0474}h2?=f(x3?w3?+x4?w4?+b2?)=0.0474
o 1 = f ( h 1 w 5 + h 2 w 6 + b 3 ) = f ( 0.0474 + 0.0474 + 0 ) = 0.524 {o_1=f(++b_3)=f(0.0474+0.0474+0)=0.524}o1?=f(h1?w5?+h2?w6?+b3?)=f(0.0474+0.0474+0)=0.524
神经网络的输出y=0.524,没有显示出强烈的是男(1)是女(0)的证据 。现在的预测效果还很不好 。
? L ? w 1 = ? L ? y p r e d ? ? y p r e d ? h 1 ? ? h 1 ? w 1 {\frac{\ L}{\ w_1}=\frac{\ L}{\ y_{pred}}*\frac{\ y_{pred}}{\ h_1}*\frac{\ h_1}{\ w_1}}?w1??L?=?ypred??L???h1??ypred????w1??h1??
所以? L ? w 1 = ? 0.952 ? 0.249 ? ? 0.0904 = 0.0214 {\frac{\ L}{\ w_1}=-0.952*0.249*-0.0904 = 0.0214}?w1??L?=?0.952?0.249??0.0904=0.0214
这个结果告诉我们:如果增大w1,损失函数L会有一个非常小的增长 。
随机梯度下降
下面将使用一种称为随机梯度下降(SGD)的优化算法,来训练网络 。
经过前面的运算,我们已经有了训练神经网络所有数据 。但是该如何操作?SGD定义了改变权重和偏置的方法:
w 1 ← w 1 ? η? L ? w 1 {w_1\ w_1-\eta \ \frac{\ L}{\ w_1}}w1?←w1??η?w1??L?
η {\eta}η是一个常数,称为学习率( rate),它决定了我们训练网络速率的快慢 。将w 1 {w_1}w1?减去η ? L ? w 1 {\eta \frac{\ L}{\ w_1}}η?w1??L?,就等到了新的权重w 1 {w_1}w1? 。
如果我们用这种方法去逐步改变网络的权重w {w}w和偏置b {b}b,损失函数会缓慢地降低,从而改进我们的神经网络 。
训练流程如下:
从数据集中选择一个样本;计算损失函数对所有权重和偏置的偏导数;使用更新公式更新每个权重和偏置;回到第1步 。
代码实现这个过程:
def sigmoid(x):# Sigmoid activation function: f(x) = 1 / (1 + e^(-x))return 1 / (1 + np.exp(-x))def deriv_sigmoid(x):# Derivative of sigmoid: f'(x) = f(x) * (1 - f(x))fx = sigmoid(x)return fx * (1 - fx)def mse_loss(y_true, y_pred):# y_true and y_pred are numpy arrays of the same lengthreturn ((y_true - y_pred) ** 2).mean()class OurNeuralNetwork():"""A neural network with:- 2 inputs- a hidden layer with 2 neurons (h1, h2)- an output layer with 1 neuron (o1)*** DISCLAIMER ***The code below is intend to be simple and educational, NOT optimal.Real neural net code looks nothing like this. Do NOT use this code.Instead, read/run it to understand how this specific network works."""def __init__(self):# weightsself.w1 = np.random.normal()self.w2 = np.random.normal()self.w3 = np.random.normal()self.w4 = np.random.normal()self.w5 = np.random.normal()self.w6 = np.random.normal()# biasesself.b1 = np.random.normal()self.b2 = np.random.normal()self.b3 = np.random.normal()def feedforward(self, x):# x is a numpy array with 2 elements, for example [input1, input2]h1 = sigmoid(self.w1 * x[0] + self.w2 * x[1] + self.b1)h2 = sigmoid(self.w3 * x[0] + self.w4 * x[1] + self.b2)o1 = sigmoid(self.w5 * h1 + self.w6 * h2 + self.b3)return o1def train(self, data, all_y_trues):"""- data is a (n x 2) numpy array, n = # samples in the dataset.- all_y_trues is a numpy array with n elements.Elements in all_y_trues correspond to those in data."""learn_rate = 0.1epochs = 1000 # number of times to loop through the entire datasetfor epoch in range(epochs):for x, y_true in zip(data, all_y_trues):# - - - Do a feedforward (we'll need these values later)sum_h1 = self.w1 * x[0] + self.w2 * x[1] + self.b1h1 = sigmoid(sum_h1)sum_h2 = self.w3 * x[0] + self.w4 * x[1] + self.b2h2 = sigmoid(sum_h2)sum_o1 = self.w5 * x[0] + self.w6 * x[1] + self.b3o1 = sigmoid(sum_o1)y_pred = o1# - - - Calculate partial derivatives.# - - - Naming: d_L_d_w1 represents "partial L / partial w1"d_L_d_ypred = -2 * (y_true - y_pred)# Neuron o1d_ypred_d_w5 = h1 * deriv_sigmoid(sum_o1)d_ypred_d_w6 = h2 * deriv_sigmoid(sum_o1)d_ypred_d_b3 = deriv_sigmoid(sum_o1)d_ypred_d_h1 = self.w5 * deriv_sigmoid(sum_o1)d_ypred_d_h2 = self.w6 * deriv_sigmoid(sum_o1)# Neuron h1d_h1_d_w1 = x[0] * deriv_sigmoid(sum_h1)d_h1_d_w2 = x[1] * deriv_sigmoid(sum_h1)d_h1_d_b1 = deriv_sigmoid(sum_h1)# Neuron h2d_h2_d_w3 = x[0] * deriv_sigmoid(sum_h2)d_h2_d_w4 = x[0] * deriv_sigmoid(sum_h2)d_h2_d_b2 = deriv_sigmoid(sum_h2)# - - - update weights and biases# Neuron o1self.w5 -= learn_rate * d_L_d_ypred * d_ypred_d_w5self.w6 -= learn_rate * d_L_d_ypred * d_ypred_d_w6self.b3 -= learn_rate * d_L_d_ypred * d_ypred_d_b3# Neuron h1self.w1 -= learn_rate * d_L_d_ypred * d_ypred_d_h1 * d_h1_d_w1self.w2 -= learn_rate * d_L_d_ypred * d_ypred_d_h1 * d_h1_d_w2self.b1 -= learn_rate * d_L_d_ypred * d_ypred_d_h1 * d_h1_d_b1# Neuron h2self.w3 -= learn_rate * d_L_d_ypred * d_ypred_d_h2 * d_h2_d_w3self.w4 -= learn_rate * d_L_d_ypred * d_ypred_d_h2 * d_h2_d_w4self.b2 -= learn_rate * d_L_d_ypred * d_ypred_d_h2 * d_h2_d_b2# - - - Calculate total loss at the end of each epochif epoch % 10 == 0:y_preds = np.apply_along_axis(self.feedforward, 1, data)loss = mse_loss(all_y_trues, y_preds)print("Epoch %d loss: %.3f", (epoch, loss))# Define datasetdata = http://www.kingceram.com/post/np.array([[-2, -1], # Alice[25, 6],# Bob[17, 4],# Charlie[-15, -6] # diana])all_y_trues = np.array([1, # Alice0, # Bob0, # Charlie1 # diana])# Train our neural network!network = OurNeuralNetwork()network.train(data, all_y_trues)