题目

题目题目2
题目三

过程推导——了解BP原理

BP神经网络(Back propagation neural network)全称为多层前馈神经网络,其用于解决非线性问题。整个神经网络的步骤为:输入层接收外界的输入,隐藏层和输出层的神经元对输入的特征或信号通过权重矩阵进行加工,最终输出结果。过程中最重要的是获得加工所要的权重,本质上说神经网络的学习过程就是在学习神经元与神经元之间连接的权重。

这里我引用西瓜书的一些知识
1
2
3
4
这里引用飞桨的视频截图(这个过程更加直白一点)
引用
6

我再补充一些:

补充
∂ E k ∂ w = y ^ j k ( 1 − y ^ j k ) ( y j k − y ^ j k ) {∂E_k \over∂w}= \hat y^k_j(1-\hat y^k_j)(y_j^k-\hat y^k_j) wEk=y^jk(1y^jk)(yjky^jk) Δ θ j = − η g j \Delta \theta_j = -\eta g_j Δθj=ηgj ∂ E k ∂ V i h = b h ( 1 − b h ) ∑ j = 1 l W h j g j {∂E_k \over ∂V_ih}=b_h(1-b_h)\sum^l_{j=1}W_{hj}g_j VihEk=bh(1bh)j=1lWhjgj e h = − ∂ E k ∂ b h ∂ b h ∂ α h e_h=-{∂E_k \over ∂b_h}{∂b_h \over ∂\alpha_h} eh=bhEkαhbh Δ V i h = η e h x i \Delta V_{ih}=\eta e_hx_i ΔVih=ηehxi ∂ E k ∂ r h = ∑ j = 1 l y ^ j k ( 1 − y ^ j k ) ( y j k − x ^ k ) W h j b h ( 1 − b h ) {∂E_k \over ∂r_h}=\sum^l_{j=1}\hat y^k_j(1-\hat y^k_j)(y_j^k-\hat x^k)W_{hj}b_h(1-b_h) rhEk=j=1ly^jk(1y^jk)(yjkx^k)Whjbh(1bh) Δ r h = − η e h \Delta r_h=-\eta e_h Δrh=ηeh

数值计算

将题目中给出的数值代入推导出的公式中
(这里就以 w 1 w_1 w1为例)
∂ E k ∂ w 1 = y ^ 1 k ( 1 − y ^ 1 k ) ( y 1 k − y ^ 1 k ) ∗ b ( 为 0 ) = y ^ 1 k ( 1 − y ^ 1 k ) ( y 1 k − y ^ 1 k ) ∗ f ( w 1 x 1 + w 2 x 2 ) + b = − 0.0084 故: Δ W 1 = W 1 − ∂ E k ∂ w 1 = 0.2 − ( − 0.0084 ) = 0.2084 \begin{aligned} {∂E_k \over∂w_1}&= \hat y^k_1(1-\hat y^k_1)(y_1^k-\hat y^k_1)*b(为0)\\ &=\hat y^k_1(1-\hat y^k_1)(y_1^k-\hat y^k_1)*f(w_1x_1+w_2x_2)+b\\ &=-0.0084\\ 故:&\Delta W_1=W_1-{∂E_k \over∂w_1}=0.2-(-0.0084)=0.2084 \end{aligned} w1Ek故:=y^1k(1y^1k)(y1ky^1k)b(0)=y^1k(1y^1k)(y1ky^1k)f(w1x1+w2x2)+b=0.0084ΔW1=W1w1Ek=0.2(0.0084)=0.2084

代码实现

使用numpy实现

import numpy as np
 
w1, w2, w3, w4, w5, w6, w7, w8 = 0.2, -0.4, 0.5, 0.6, 0.1, -0.5, -0.3, 0.8
x1, x2 = 0.5, 0.3
y1, y2 = 0.23, -0.07
print("输入值 x0, x1:")
print(x1, x2)
print("输出值 y0, y1:")
print(y1, y2)
 
 
def sigmoid(z):
    a = 1 / (1 + np.exp(-z))
    return a
 
 
def forward_propagate(x1, x2, y1, y2, w1, w2, w3, w4, w5, w6, w7, w8):
    in_h1 = w1 * x1 + w3 * x2
    out_h1 = sigmoid(in_h1)
    in_h2 = w2 * x1 + w4 * x2
    out_h2 = sigmoid(in_h2)
 
    in_o1 = w5 * out_h1 + w7 * out_h2
    out_o1 = sigmoid(in_o1)
    in_o2 = w6 * out_h1 + w8 * out_h2
    out_o2 = sigmoid(in_o2)
 
    print("正向计算:预测值o1 ,o2为")
    print(round(out_o1, 5), round(out_o2, 5))
 
    error = (1 / 2) * (out_o1 - y1) ** 2 + (1 / 2) * (out_o2 - y2) ** 2
 
    print("损失函数(均方误差):",round(error, 5))
 
    return out_o1, out_o2, out_h1, out_h2
 
 
def back_propagate(out_o1, out_o2, out_h1, out_h2):
    # 反向传播
    d_o1 = out_o1 - y1
    d_o2 = out_o2 - y2
 
    d_w5 = d_o1 * out_o1 * (1 - out_o1) * out_h1
    d_w7 = d_o1 * out_o1 * (1 - out_o1) * out_h2
    d_w6 = d_o2 * out_o2 * (1 - out_o2) * out_h1
    d_w8 = d_o2 * out_o2 * (1 - out_o2) * out_h2
 
    d_w1 = (d_o1 * out_h1 * (1 - out_h1) * w5 + d_o2 * out_o2 * (1 - out_o2) * w6) * out_h1 * (1 - out_h1) * x1
    d_w3 = (d_o1 * out_h1 * (1 - out_h1) * w5 + d_o2 * out_o2 * (1 - out_o2) * w6) * out_h1 * (1 - out_h1) * x2
    d_w2 = (d_o1 * out_h1 * (1 - out_h1) * w7 + d_o2 * out_o2 * (1 - out_o2) * w8) * out_h2 * (1 - out_h2) * x1
    d_w4 = (d_o1 * out_h1 * (1 - out_h1) * w7 + d_o2 * out_o2 * (1 - out_o2) * w8) * out_h2 * (1 - out_h2) * x2
 
    print("反向传播:误差传给每个权值", round(d_w1, 5), round(d_w2, 5), round(d_w3, 5), round(d_w4, 5), round(d_w5, 5), round(d_w6, 5),
          round(d_w7, 5), round(d_w8, 5))
 
    return d_w1, d_w2, d_w3, d_w4, d_w5, d_w6, d_w7, d_w8
 
 
def update_w(w1, w2, w3, w4, w5, w6, w7, w8):
    # 步长
    step = 1
    w1 = w1 - step * d_w1
    w2 = w2 - step * d_w2
    w3 = w3 - step * d_w3
    w4 = w4 - step * d_w4
    w5 = w5 - step * d_w5
    w6 = w6 - step * d_w6
    w7 = w7 - step * d_w7
    w8 = w8 - step * d_w8
    return w1, w2, w3, w4, w5, w6, w7, w8
 
 
if __name__ == "__main__":
 
    print("更新前的权值:",round(w1, 2), round(w2, 2), round(w3, 2), round(w4, 2), round(w5, 2), round(w6, 2), round(w7, 2),
          round(w8, 2))
 
    for i in range(1):
        print("第" + str(i+1) + "轮:")
        out_o1, out_o2, out_h1, out_h2 = forward_propagate(x1, x2, y1, y2, w1, w2, w3, w4, w5, w6, w7, w8)
        d_w1, d_w2, d_w3, d_w4, d_w5, d_w6, d_w7, d_w8 = back_propagate(out_o1, out_o2, out_h1, out_h2)
        w1, w2, w3, w4, w5, w6, w7, w8 = update_w(w1, w2, w3, w4, w5, w6, w7, w8)
 
    print("更新后的权值w:", round(w1, 2), round(w2, 2), round(w3, 2), round(w4, 2), round(w5, 2), round(w6, 2), round(w7, 2),

运行结果:

输入值 x0, x1:
0.5 0.3
输出值 y0, y1:
0.23 -0.07
更新前的权值: 0.2 -0.4 0.5 0.6 0.1 -0.5 -0.3 0.8
第1轮:
正向计算:预测值o1 ,o2为
0.47695 0.5287
损失函数(均方误差): 0.20971
反向传播:误差传给每个权值 -0.00843 0.01264 -0.00506 0.00758 0.03463 0.08387 0.03049 0.07384
更新后的权值w: 0.21 -0.41 0.51 0.59 0.07 -0.58 -0.33 0.73

使用pytorch实现

import torch
 
x1, x2 = torch.Tensor([0.5]), torch.Tensor([0.3])
y1, y2 = torch.Tensor([0.23]), torch.Tensor([-0.07])
print("=====输入值:x1, x2;真实输出值:y1, y2=====")
print(x1, x2, y1, y2)
w1, w2, w3, w4, w5, w6, w7, w8 = torch.Tensor([0.2]), torch.Tensor([-0.4]), torch.Tensor([0.5]), torch.Tensor(
    [0.6]), torch.Tensor([0.1]), torch.Tensor([-0.5]), torch.Tensor([-0.3]), torch.Tensor([0.8])  # 权重初始值
w1.requires_grad = True
w2.requires_grad = True
w3.requires_grad = True
w4.requires_grad = True
w5.requires_grad = True
w6.requires_grad = True
w7.requires_grad = True
w8.requires_grad = True
 
 
def sigmoid(z):
    a = 1 / (1 + torch.exp(-z))
    return a
 
 
def forward_propagate(x1, x2):
    in_h1 = w1 * x1 + w3 * x2
    out_h1 = sigmoid(in_h1)  # out_h1 = torch.sigmoid(in_h1)
    in_h2 = w2 * x1 + w4 * x2
    out_h2 = sigmoid(in_h2)  # out_h2 = torch.sigmoid(in_h2)
 
    in_o1 = w5 * out_h1 + w7 * out_h2
    out_o1 = sigmoid(in_o1)  # out_o1 = torch.sigmoid(in_o1)
    in_o2 = w6 * out_h1 + w8 * out_h2
    out_o2 = sigmoid(in_o2)  # out_o2 = torch.sigmoid(in_o2)
 
    print("正向计算:o1 ,o2")
    print(out_o1.data, out_o2.data)
 
    return out_o1, out_o2
 
 
def loss_fuction(x1, x2, y1, y2):  # 损失函数
    y1_pred, y2_pred = forward_propagate(x1, x2)  # 前向传播
    loss = (1 / 2) * (y1_pred - y1) ** 2 + (1 / 2) * (y2_pred - y2) ** 2  # 考虑 : t.nn.MSELoss()
    print("损失函数(均方误差):", loss.item())
    return loss
 
 
def update_w(w1, w2, w3, w4, w5, w6, w7, w8):
    # 步长
    step = 1
    w1.data = w1.data - step * w1.grad.data
    w2.data = w2.data - step * w2.grad.data
    w3.data = w3.data - step * w3.grad.data
    w4.data = w4.data - step * w4.grad.data
    w5.data = w5.data - step * w5.grad.data
    w6.data = w6.data - step * w6.grad.data
    w7.data = w7.data - step * w7.grad.data
    w8.data = w8.data - step * w8.grad.data
    w1.grad.data.zero_()  # 注意:将w中所有梯度清零
    w2.grad.data.zero_()
    w3.grad.data.zero_()
    w4.grad.data.zero_()
    w5.grad.data.zero_()
    w6.grad.data.zero_()
    w7.grad.data.zero_()
    w8.grad.data.zero_()
    return w1, w2, w3, w4, w5, w6, w7, w8
 
 
if __name__ == "__main__":
 
    print("=====更新前的权值=====")
    print(w1.data, w2.data, w3.data, w4.data, w5.data, w6.data, w7.data, w8.data)
 
    for i in range(1):
        print("=====第" + str(i) + "轮=====")
        L = loss_fuction(x1, x2, y1, y2)  # 前向传播,求 Loss,构建计算图
        L.backward()  # 自动求梯度,不需要人工编程实现。反向传播,求出计算图中所有梯度存入w中
        print("\tgrad W: ", round(w1.grad.item(), 2), round(w2.grad.item(), 2), round(w3.grad.item(), 2),
              round(w4.grad.item(), 2), round(w5.grad.item(), 2), round(w6.grad.item(), 2), round(w7.grad.item(), 2),
              round(w8.grad.item(), 2))
        w1, w2, w3, w4, w5, w6, w7, w8 = update_w(w1, w2, w3, w4, w5, w6, w7, w8)
 
    print("更新后的权值")
    print(w1.data, w2.data, w3.data, w4.data, w5.data, w6.data, w7.data, w8.data)

运行结果:

=====输入值:x1, x2;真实输出值:y1, y2=====
tensor([0.5000]) tensor([0.3000]) tensor([0.2300]) tensor([-0.0700])
=====更新前的权值=====
tensor([0.2000]) tensor([-0.4000]) tensor([0.5000]) tensor([0.6000]) tensor([0.1000]) tensor([-0.5000]) tensor([-0.3000]) tensor([0.8000])
=====第0轮=====
正向计算:o1 ,o2
tensor([0.4769]) tensor([0.5287])
损失函数(均方误差): 0.2097097933292389
        grad W:  -0.01 0.01 -0.01 0.01 0.03 0.08 0.03 0.07
更新后的权值
tensor([0.2084]) tensor([-0.4126]) tensor([0.5051]) tensor([0.5924]) tensor([0.0654]) tensor([-0.5839]) tensor([-0.3305]) tensor([0.7262])

1、对比【numpy】和【pytorch】程序,总结并陈述。

通过改变训练轮数,发现无论训练多少轮,还是当梯度都为0时(即找到最优解),结果都十分相近,因此可认为两种方法的求解效果基本相同。

例如:

训练轮数等于2时【numpy】程序结果:

更新后的权值w: 0.22 -0.42 0.51 0.59 0.03 -0.67 -0.36 0.66

训练轮数等于2时【pytorch】程序结果:

损失函数(均方误差): 0.19503259658813477
        grad W:  -0.01 0.01 -0.01 0.01 0.03 0.08 0.03 0.07
更新后的权值
tensor([0.2183]) tensor([-0.4232]) tensor([0.5110]) tensor([0.5861]) tensor([0.0319]) tensor([-0.6652]) tensor([-0.3598]) tensor([0.6550])

2、激活函数Sigmoid用PyTorch自带函数torch.sigmoid(),观察、总结并陈述。

使用Sigmoid函数和使用Pytorch自带函数torch.sigmoid()没较为明显的差距。
训练50轮:

正向计算:o1 ,o2
tensor([0.2758]) tensor([0.1304])
损失函数(均方误差): 0.02112446539103985
        grad W:  -0.01 -0.0 -0.0 -0.0 0.01 0.01 0.0 0.01
更新后的权值
tensor([0.7606]) tensor([-0.3133]) tensor([0.8363]) tensor([0.6520]) tensor([-0.7251]) tensor([-2.3611]) tensor([-0.9798]) tensor([-0.7355])

训练100轮:

=====第99轮=====
正向计算:o1 ,o2
tensor([0.2378]) tensor([0.0736])
损失函数(均方误差): 0.010342842899262905
        grad W:  -0.0 -0.0 -0.0 -0.0 0.0 0.01 0.0 0.01
更新后的权值
tensor([0.9865]) tensor([-0.2037]) tensor([0.9719]) tensor([0.7178]) tensor([-0.8628]) tensor([-2.8459]) tensor([-1.0866]) tensor([-1.1112])

3、激活函数Sigmoid改变为Relu,观察、总结并陈述。

Relu函数图像:
图像
训练2轮Relu函数:

=====输入值:x1, x2;真实输出值:y1, y2=====
tensor([0.5000]) tensor([0.3000]) tensor([0.2300]) tensor([-0.0700])
=====更新前的权值=====
tensor([0.2000]) tensor([-0.4000]) tensor([0.5000]) tensor([0.6000]) tensor([0.1000]) tensor([-0.5000]) tensor([-0.3000]) tensor([0.8000])
=====第0轮=====
正向计算:o1 ,o2
tensor([0.0250]) tensor([0.])
损失函数(均方误差): 0.023462500423192978
        grad W:  -0.01 0.0 -0.01 0.0 -0.05 0.0 -0.0 0.0
=====第1轮=====
正向计算:o1 ,o2
tensor([0.0389]) tensor([0.])
损失函数(均方误差): 0.020715968683362007
        grad W:  -0.01 0.0 -0.01 0.0 -0.05 0.0 0.0 0.0
更新后的权值
tensor([0.2247]) tensor([-0.4000]) tensor([0.5148]) tensor([0.6000]) tensor([0.2004]) tensor([-0.5000]) tensor([-0.3000]) tensor([0.8000])

训练50轮Relu函数:

=====第49轮=====
正向计算:o1 ,o2
tensor([0.2300]) tensor([0.])
损失函数(均方误差): 0.0024500000290572643
        grad W:  -0.0 0.0 -0.0 0.0 -0.0 0.0 0.0 0.0
更新后的权值
tensor([0.4287]) tensor([-0.4000]) tensor([0.6372]) tensor([0.6000]) tensor([0.5672]) tensor([-0.5000]) tensor([-0.3000]) tensor([0.8000])

训练100轮Relu函数:

=====第99轮=====
正向计算:o1 ,o2
tensor([0.2300]) tensor([0.])
损失函数(均方误差): 0.0024500000290572643
        grad W:  -0.0 0.0 -0.0 0.0 -0.0 0.0 0.0 0.0
更新后的权值
tensor([0.4287]) tensor([-0.4000]) tensor([0.6372]) tensor([0.6000]) tensor([0.5672]) tensor([-0.5000]) tensor([-0.3000]) tensor([0.8000])
  1. 相比来说,激活函数为Sigmoid函数收敛的较快,而relu函数收敛的较慢。
  2. 采用sigmoid等函数,算激活函数时(指数运算),计算量大,反向传播求误差梯度时,求导涉及除法,计算量相对大,而采用Relu激活函数,整个过程的计算量节省很多

4、损失函数MSE用PyTorch自带函数 t.nn.MSELoss()替代,观察、总结并陈述。

损失函数更改后:

def loss_fuction(x1, x2, y1, y2):  # 损失函数
    y1_pred, y2_pred = forward_propagate(x1, x2)  # 前向传播
    # loss = (1 / 2) * (y1_pred - y1) ** 2 + (1 / 2) * (y2_pred - y2) ** 2  # 考虑 : t.nn.MSELoss()
    loss = torch.nn.MSELoss()
    loss1 = loss(y1_pred,y1)
    loss2 = loss(y2_pred,y2)
    loss = loss1 + loss2
    print("损失函数(均方误差):", loss.item())
    return loss

运行结果:
训练轮数为2:

=====第1轮=====
正向计算:o1 ,o2
tensor([0.0534]) tensor([0.])
损失函数(均方误差): 0.03607065975666046
        grad W:  -0.04 0.0 -0.02 0.0 -0.09 0.0 0.0 0.0
更新后的权值
tensor([0.2563]) tensor([-0.4000]) tensor([0.5338]) tensor([0.6000]) tensor([0.2957]) tensor([-0.5000]) tensor([-0.3000]) tensor([0.8000])

训练轮数为50:

=====第49轮=====
正向计算:o1 ,o2
tensor([0.2300]) tensor([0.])
损失函数(均方误差): 0.004900000058114529
        grad W:  -0.0 0.0 -0.0 0.0 -0.0 0.0 0.0 0.0
更新后的权值
tensor([0.4236]) tensor([-0.4000]) tensor([0.6342]) tensor([0.6000]) tensor([0.5720]) tensor([-0.5000]) tensor([-0.3000]) tensor([0.8000])

训练轮数为100:

=====第99轮=====
正向计算:o1 ,o2
tensor([0.2300]) tensor([0.])
损失函数(均方误差): 0.004900000058114529
        grad W:  -0.0 0.0 -0.0 0.0 -0.0 0.0 0.0 0.0
更新后的权值
tensor([0.4236]) tensor([-0.4000]) tensor([0.6342]) tensor([0.6000]) tensor([0.5720]) tensor([-0.5000]) tensor([-0.3000]) tensor([0.8000])

通过运行结果观察发现自带函数和编写的函数运行结果相同

5、损失函数MSE改变为交叉熵,观察、总结并陈述。

更改后:

def loss_fuction(x1, x2, y1, y2):
    y1_pred, y2_pred = forward_propagate(x1, x2)
    loss_func = torch.nn.CrossEntropyLoss() # 创建交叉熵损失函数
    y_pred = torch.stack([y1_pred, y2_pred], dim=1)
    y = torch.stack([y1, y2], dim=1)
    loss = loss_func(y_pred, y) # 计算
    print("损失函数(交叉熵损失):", loss.item())
    return loss

运行结果:
训练轮数为2:

=====第1轮=====
正向计算:o1 ,o2
tensor([0.0350]) tensor([0.])
损失函数(交叉熵损失): 0.10567688941955566
        grad W:  -0.01 0.0 -0.01 0.0 -0.04 0.0 0.0 0.0
更新后的权值
tensor([0.2176]) tensor([-0.4000]) tensor([0.5106]) tensor([0.6000]) tensor([0.1752]) tensor([-0.5000]) tensor([-0.3000]) tensor([0.8000])

训练轮数为50:

=====第49轮=====
正向计算:o1 ,o2
tensor([13.3109]) tensor([0.])
损失函数(交叉熵损失): -0.9317622780799866
        grad W:  -0.17 0.0 -0.1 0.0 -0.2 0.0 0.0 0.0
更新后的权值
tensor([4.1027]) tensor([-0.4000]) tensor([2.8416]) tensor([0.6000]) tensor([4.9657]) tensor([-0.5000]) tensor([-0.3000]) tensor([0.8000])

训练轮数为100:

=====第99轮=====
正向计算:o1 ,o2
tensor([727.1639]) tensor([0.])
损失函数(交叉熵损失): -50.9014778137207
        grad W:  -1.24 0.0 -0.74 0.0 -1.44 0.0 0.0 0.0
更新后的权值
tensor([31.3506]) tensor([-0.4000]) tensor([19.1903]) tensor([0.6000]) tensor([36.7545]) tensor([-0.5000]) tensor([-0.3000]) tensor([0.8000])

改为交叉熵之后损失函数出现负数,在这之前,我们已经了解到交叉熵损失函数更实用于分类,而不是预测。

6、改变步长,训练次数,观察、总结并陈述。

步长为0.5
训练轮数为2:

=====第1轮=====
正向计算:o1 ,o2
tensor([0.4685]) tensor([0.5072])
损失函数(均方误差): 0.39006519317626953
        grad W:  -0.02 0.02 -0.01 0.01 0.07 0.16 0.06 0.14
更新后的权值
tensor([0.2183]) tensor([-0.4232]) tensor([0.5110]) tensor([0.5861]) tensor([0.0319]) tensor([-0.6652]) tensor([-0.3598]) tensor([0.6550])

训练轮数为50:

=====第49轮=====
正向计算:o1 ,o2
tensor([0.2758]) tensor([0.1304])
损失函数(均方误差): 0.0422489307820797
        grad W:  -0.01 -0.01 -0.01 -0.0 0.01 0.03 0.01 0.02
更新后的权值
tensor([0.7606]) tensor([-0.3133]) tensor([0.8363]) tensor([0.6520]) tensor([-0.7251]) tensor([-2.3611]) tensor([-0.9798]) tensor([-0.7355])

训练轮数为100:

=====第99轮=====
正向计算:o1 ,o2
tensor([0.2378]) tensor([0.0736])
损失函数(均方误差): 0.02068568579852581
        grad W:  -0.01 -0.0 -0.0 -0.0 0.0 0.01 0.0 0.01
更新后的权值
tensor([0.9865]) tensor([-0.2037]) tensor([0.9719]) tensor([0.7178]) tensor([-0.8628]) tensor([-2.8459]) tensor([-1.0866]) tensor([-1.1112])

步长为3
训练轮数为2:

=====第1轮=====
正向计算:o1 ,o2
tensor([0.4269]) tensor([0.4012])
损失函数(均方误差): 0.26084014773368835
        grad W:  -0.03 0.0 -0.02 0.0 0.05 0.13 0.05 0.11
更新后的权值
tensor([0.3378]) tensor([-0.4885]) tensor([0.5827]) tensor([0.5469]) tensor([-0.2728]) tensor([-1.3908]) tensor([-0.6224]) tensor([0.0294])

训练轮数为50:

=====第49轮=====
正向计算:o1 ,o2
tensor([0.2283]) tensor([0.0290])
损失函数(均方误差): 0.009809560142457485
        grad W:  -0.0 -0.0 -0.0 -0.0 -0.0 0.0 -0.0 0.0
更新后的权值
tensor([1.2860]) tensor([-0.0748]) tensor([1.1516]) tensor([0.7951]) tensor([-0.8526]) tensor([-3.5755]) tensor([-1.0837]) tensor([-1.6757])

训练轮数为100:

=====第99轮=====
正向计算:o1 ,o2
tensor([0.2293]) tensor([0.0157])
损失函数(均方误差): 0.007349265739321709
        grad W:  -0.0 -0.0 -0.0 -0.0 -0.0 0.0 -0.0 0.0
更新后的权值
tensor([1.4843]) tensor([0.0442]) tensor([1.2706]) tensor([0.8665]) tensor([-0.8113]) tensor([-3.9912]) tensor([-1.0526]) tensor([-1.9894])
  1. 可见,步长越大,均方误差下降越快,收敛就越快;
  2. 训练轮数达到一定次数时,准确率或者误差会不变,这时停止训练,可以提升系统的性能
  3. 合适的训练次数和学习率会提升模型的稳健性。

7、权值w1-w8初始值换为随机数,对比“指定权值”的结果,观察、总结并陈述。

代码:

import torch
torch.manual_seed(20)

x1, x2 = torch.Tensor([0.5]), torch.Tensor([0.3])
y1, y2 = torch.Tensor([0.23]), torch.Tensor([-0.07])
print("=====输入值:x1, x2;真实输出值:y1, y2=====")
print(x1, x2, y1, y2)

w1, w2, w3, w4, w5, w6, w7, w8 =torch.rand(1), torch.rand(1), torch.rand(1), torch.rand(1), torch.rand(1),torch.rand(1), torch.rand(1), torch.rand(1)
w1.requires_grad = True
w2.requires_grad = True
w3.requires_grad = True
w4.requires_grad = True
w5.requires_grad = True
w6.requires_grad = True
w7.requires_grad = True
w8.requires_grad = True


def sigmoid(z):
    a = 1 / (1 + torch.exp(-z))
    return a


def forward_propagate(x1, x2):
    in_h1 = w1 * x1 + w3 * x2
    out_h1 = torch.relu(in_h1)  # out_h1 = torch.sigmoid(in_h1)
    in_h2 = w2 * x1 + w4 * x2
    out_h2 = torch.relu(in_h2)  # out_h2 = torch.sigmoid(in_h2)
    in_o1 = w5 * out_h1 + w7 * out_h2
    out_o1 = torch.relu(in_o1)  # out_o1 = torch.sigmoid(in_o1)
    in_o2 = w6 * out_h1 + w8 * out_h2
    out_o2 = torch.relu(in_o2)  # out_o2 = torch.sigmoid(in_o2)

    print("正向计算:o1 ,o2")
    print(out_o1.data, out_o2.data)

    return out_o1, out_o2


def loss_fuction(x1, x2, y1, y2):  # 损失函数
    y1_pred, y2_pred = forward_propagate(x1, x2)  # 前向传播
    loss = torch.nn.CrossEntropyLoss()  # 考虑 : t.nn.MSELoss()
    y_pred = torch.stack([y1_pred, y2_pred], dim=1)
    y = torch.stack([y1, y2], dim=1)
    loss = loss(y_pred,y)
    print("损失函数(CrossEntropyLoss):", loss.item())
    return loss


def update_w(w1, w2, w3, w4, w5, w6, w7, w8):
    # 步长
    step = 2
    w1.data = w1.data - step * w1.grad.data
    w2.data = w2.data - step * w2.grad.data
    w3.data = w3.data - step * w3.grad.data
    w4.data = w4.data - step * w4.grad.data
    w5.data = w5.data - step * w5.grad.data
    w6.data = w6.data - step * w6.grad.data
    w7.data = w7.data - step * w7.grad.data
    w8.data = w8.data - step * w8.grad.data
    w1.grad.data.zero_()  # 注意:将w中所有梯度清零
    w2.grad.data.zero_()
    w3.grad.data.zero_()
    w4.grad.data.zero_()
    w5.grad.data.zero_()
    w6.grad.data.zero_()
    w7.grad.data.zero_()
    w8.grad.data.zero_()
    return w1, w2, w3, w4, w5, w6, w7, w8


if __name__ == "__main__":

    print("=====更新前的权值=====")
    print(w1.data, w2.data, w3.data, w4.data, w5.data, w6.data, w7.data, w8.data)

    for i in range(2):
        print("=====第" + str(i) + "轮=====")
        L = loss_fuction(x1, x2, y1, y2)  # 前向传播,求 Loss,构建计算图
        L.backward()  # 自动求梯度,不需要人工编程实现。反向传播,求出计算图中所有梯度存入w中
        print("\tgrad W: ", round(w1.grad.item(), 2), round(w2.grad.item(), 2), round(w3.grad.item(), 2),
              round(w4.grad.item(), 2), round(w5.grad.item(), 2), round(w6.grad.item(), 2), round(w7.grad.item(), 2),
              round(w8.grad.item(), 2))
        w1, w2, w3, w4, w5, w6, w7, w8 = update_w(w1, w2, w3, w4, w5, w6, w7, w8)

    print("更新后的权值")
    print(w1.data, w2.data, w3.data, w4.data, w5.data, w6.data, w7.data, w8.data)

运行结果:
训练轮数为2时:

=====输入值:x1, x2;真实输出值:y1, y2=====
tensor([0.5000]) tensor([0.3000]) tensor([0.2300]) tensor([-0.0700])
=====更新前的权值=====
tensor([0.5615]) tensor([0.1774]) tensor([0.8147]) tensor([0.3295]) tensor([0.2319]) tensor([0.7832]) tensor([0.8544]) tensor([0.1012])
=====第0轮=====
正向计算:o1 ,o2
tensor([0.2820]) tensor([0.4303])
损失函数(CrossEntropyLoss): 0.1335778832435608
        grad W:  0.04 -0.06 0.03 -0.04 -0.08 0.08 -0.03 0.03
=====第1轮=====
正向计算:o1 ,o2
tensor([0.4288]) tensor([0.3005])
损失函数(CrossEntropyLoss): 0.09199006855487823
        grad W:  0.02 -0.06 0.01 -0.04 -0.07 0.07 -0.04 0.04
更新后的权值
tensor([0.4431]) tensor([0.4209]) tensor([0.7437]) tensor([0.4757]) tensor([0.5309]) tensor([0.4842]) tensor([0.9904]) tensor([-0.0348])

训练轮数为50时:

=====第49轮=====
正向计算:o1 ,o2
tensor([1648.7810]) tensor([0.])
损失函数(CrossEntropyLoss): -115.4146728515625
        grad W:  -1.1 -1.5 -0.66 -0.9 -1.29 0.0 -1.75 0.0
更新后的权值
tensor([29.0125]) tensor([39.6298]) tensor([17.8853]) tensor([24.0010]) tensor([34.0791]) tensor([0.2528]) tensor([46.3349]) tensor([-0.2410])

训练轮数为100时:

=====第99轮=====
正向计算:o1 ,o2
tensor([4218611.]) tensor([0.])
损失函数(CrossEntropyLoss): -295302.78125
        grad W:  -55.78 -75.84 -33.47 -45.5 -65.05 0.0 -88.44 0.0
更新后的权值
tensor([1477.9680]) tensor([2009.5591]) tensor([887.2587]) tensor([1205.9587]) tensor([1723.8379]) tensor([0.2528]) tensor([2343.6436]) tensor([-0.2410])

由图可见,当w1-w8初始值换为随机数后,均方误差的下降速度与指定权值时相比有所降低,收敛速度小于指定权值。

8、权值w1-w8初始值换为0,观察、总结并陈述。

代码:

w1, w2, w3, w4, w5, w6, w7, w8 = torch.Tensor([0]), torch.Tensor([0]), torch.Tensor([0]), torch.Tensor(
    [0]), torch.Tensor([0]), torch.Tensor([0]), torch.Tensor([0]), torch.Tensor([0])

运行结果:

=====第99轮=====
正向计算:o1 ,o2
tensor([0.]) tensor([0.])
损失函数(CrossEntropyLoss): 0.1109035536646843
        grad W:  0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
更新后的权值
tensor([0.]) tensor([0.]) tensor([0.]) tensor([0.]) tensor([0.]) tensor([0.]) tensor([0.]) tensor([0.])

我们发现,这里没有改变,出现了梯度消失的情况。
原因:

  1. 从深层网络角度来讲,不同的层学习的速度差异很大,表现为网络中靠近输出的层学习的情况很好,靠近输入的层学习的很慢,有时甚至训练了很久,前几层的权值和刚开始随机初始化的值差不多。因此,梯度消失、爆炸,其根本原因在于反向传播训练法则,属于先天不足,另外多说一句,Hinton提出capsule的原因就是为了彻底抛弃反向传播
  2. 计算权值更新信息的时候需要计算前层偏导信息,因此如果激活函数选择不合适,比如使用sigmoid,梯度消失就会很明显了。下图是sigmoid的导数的图像,其梯度不会超过0.25,如果使用sigmoid作为损失函数,经过链式求导之后,很容易发生梯度消失.

解决方法:

使用不同的激活函数,relu、leakrelu、elu等激活函数(其一)
Relu:思想也很简单,如果激活函数的导数为1,那么就不存在梯度消失爆炸的问题了,每层的网络都可以得到相同的更新速度。
relu的主要贡献在于:

  • 解决了梯度消失、爆炸的问题
  • 计算方便,计算速度快
  • 加速了网络的训练

relu的缺点:

  • 由于负数部分恒为0,会导致一些神经元无法激活(可通过设置小学习率部分解决)
  • 输出不是以0为中心的
  1. x>0 的时候,relu是y=x, 求导就是1,套到前面的论述的话:100个1 相乘还是为1, 大不了不变呗,但不会梯度消失
  2. x<0 的时候,relu=0,常数求导为0,这个意思就是:大不了那个神经元不更新,起到网络稀疏的效果…

心得体会

  1. 通过这次实验,我对于前馈神经网路有了更深的理解,其实只要一点点的推算,就可以记住啦~
  2. 学习有很多方法,我们可以一点一点的运算,可以画图,也可以看书,也可以查视频,但是最终的结果,都是服务我们,我们要找到最快的最方便的最适合我们的方法才能提高效率!!!
  3. 对于西瓜书不理解的地方,已经完全搞定了,这是一个很大的收获!

参考

BP神经网络原理(详细推导)
NNDL 作业3:分别使用numpy和pytorch实现FNN例题
【2021-2022 春学期】人工智能-作业2:例题程序复现
【2021-2022 春学期】人工智能-作业3:例题程序复现 PyTorch版
人工智能导论:模型与算法】误差后向传播(BP) 例题 编程验证 numpy版本
人工智能导论:模型与算法】误差后向传播(BP) 例题 编程验证 Pytorch版本


求赞

创作不易,如果对你有帮助,求求你给我个赞!!!
点赞 + 收藏 + 关注!!!
如有错误与建议,望告知!!!(将于下篇文章更正)
请多多关注我!!!谢谢!!!

更多推荐