人工智能-作业3:例题程序复现 PyTorch版

目录

1.使用pytorch复现课上例题

2.对比【作业3】和【作业2】的程序,观察两种方法结果是否相同?如果不同,哪个正确?

3.【作业2】程序更新

4.对比【作业2】与【作业3】的反向传播的实现方法。总结并陈述

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

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

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

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

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

10.权值w1-w8初始值换为随机数,对比【作业2】指定权值结果,观察、总结并陈述

11.总结反向传播原理和编码实现

12.参考代码

13.参考链接


题目要求同作业2:

(2条消息) 【2021-2022 春学期】人工智能-作业2:例题程序复现_HBU_David的博客-CSDN博客

1.使用pytorch复现课上例题

运行结果(5轮):

=====输入值: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
=====第1轮=====
正向计算:o1 ,o2
tensor([0.4685]) tensor([0.5072])
损失函数(均方误差): 0.19503259658813477
    grad W:  -0.01 0.01 -0.01 0.01 0.03 0.08 0.03 0.07
=====第2轮=====
正向计算:o1 ,o2
tensor([0.4604]) tensor([0.4864])
损失函数(均方误差): 0.1813509315252304
    grad W:  -0.01 0.01 -0.01 0.01 0.03 0.08 0.03 0.07
=====第3轮=====
正向计算:o1 ,o2
tensor([0.4526]) tensor([0.4664])
损失函数(均方误差): 0.16865134239196777
    grad W:  -0.01 0.01 -0.01 0.0 0.03 0.08 0.03 0.07
=====第4轮=====
正向计算:o1 ,o2
tensor([0.4451]) tensor([0.4473])
损失函数(均方误差): 0.15690487623214722
    grad W:  -0.01 0.01 -0.01 0.0 0.03 0.07 0.03 0.06
=====第5轮=====
正向计算:o1 ,o2
tensor([0.4378]) tensor([0.4290])
损失函数(均方误差): 0.14607082307338715
    grad W:  -0.01 0.0 -0.01 0.0 0.03 0.07 0.02 0.06
更新后的权值
tensor([0.2684]) tensor([-0.4489]) tensor([0.5411]) tensor([0.5706]) tensor([-0.0912]) tensor([-0.9621]) tensor([-0.4657]) tensor([0.3994])

Process finished with exit code 0

2.对比【作业3】和【作业2】的程序,观察两种方法结果是否相同?如果不同,哪个正确?

两种方法的结果不同,作业3的正确

3.【作业2】程序更新

import numpy as np
import matplotlib.pyplot as plt


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)

    error = (1 / 2) * (out_o1 - y1) ** 2 + (1 / 2) * (out_o2 - y2) ** 2

    return out_o1, out_o2, out_h1, out_h2, error


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_w5 + d_w6) * out_h1 * (1 - out_h1) * x1
    d_w3 = (d_w5 + d_w6) * out_h1 * (1 - out_h1) * x2
    d_w2 = (d_w7 + d_w8) * out_h2 * (1 - out_h2) * x1
    d_w4 = (d_w7 + d_w8) * out_h2 * (1 - out_h2) * x2

    return d_w1, d_w2, d_w3, d_w4, d_w5, d_w6, d_w7, d_w8


def update_w(step,w1, w2, w3, w4, w5, w6, w7, w8):    #梯度下降,更新权值
    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__":
    w1, w2, w3, w4, w5, w6, w7, w8 = 0.2, -0.4, 0.5, 0.6, 0.1, -0.5, -0.3, 0.8 # 可以给随机值,为配合PPT,给的指定值
    x1, x2 = 0.5, 0.3   # 输入值
    y1, y2 = 0.23, -0.07 # 正数可以准确收敛;负数不行。why? 因为用sigmoid输出,y1, y2 在 (0,1)范围内。
    N = 10             # 迭代次数
    step = 10           # 步长

    print("输入值:x1, x2;",x1, x2, "输出值:y1, y2:", y1, y2)
    eli = []
    lli = []
    for i in range(N):
        print("=====第" + str(i) + "轮=====")
        # 正向传播
        out_o1, out_o2, out_h1, out_h2, error = forward_propagate(x1, x2, y1, y2, w1, w2, w3, w4, w5, w6, w7, w8)
        print("正向传播:", round(out_o1, 5), round(out_o2, 5))
        print("损失函数:", round(error, 2))
        # 反向传播
        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(step,w1, w2, w3, w4, w5, w6, w7, w8)
        eli.append(i)
        lli.append(error)


    plt.plot(eli, lli)
    plt.ylabel('Loss')
    plt.xlabel('w')
    plt.show()

4.对比【作业2】与【作业3】的反向传播的实现方法。总结并陈述

作业2用的链式求导法则,作业3是计算图自动求导,效率比链式求导高很多

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

Sigmoid函数的数学形式是:

       f(x)=\frac{1}{1+e^{-x}}

Sigmoid函数的导数是其本身的函数,即f′(x)=f(x)[1−f(x)],因此Sigmoid函数在反向传播的求导中起到了重要作用

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

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

    return out_o1, out_o2

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

Relu函数的数学形式是:

f(x)=\begin{cases} x & \text{ } x>0 \\ 0 & \text{ } x<=0 \end{cases}

Relu函数其实就是分段的线性函数,作用是把所有的负值都变为0,而正值保持不变

def Relu(z):
    if z<=0:
        b = 0
    return b


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

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

    return out_o1, out_o2

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

MSELoss均方误差,是预测值与真实值之差的平方和的平均值

    loss = torch.nn.MSELoss()

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

信息熵在这里就是一个常量。由于KL散度的值表示真实概率分布与预测概率分布之间的差异,值越小表示预测的结果越好,所以需要最小化KL散度,而交叉熵等于KL散度加上一个常量(信息熵),且公式相比KL散度更加容易计算,所以在机器学习中常常使用交叉熵损失函数来计算loss

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

步长step=1,训练5次

=====第5轮=====
正向计算:o1 ,o2
tensor([0.4378]) tensor([0.4290])
损失函数(均方误差): 0.14607082307338715
    grad W:  -0.01 0.0 -0.01 0.0 0.03 0.07 0.02 0.06
更新后的权值
tensor([0.2684]) tensor([-0.4489]) tensor([0.5411]) tensor([0.5706]) tensor([-0.0912]) tensor([-0.9621]) tensor([-0.4657]) tensor([0.3994])

步长step=1,训练10次

=====第10轮=====
正向计算:o1 ,o2
tensor([0.4047]) tensor([0.3507])
损失函数(均方误差): 0.10375461727380753
    grad W:  -0.02 -0.0 -0.01 -0.0 0.02 0.06 0.02 0.05
更新后的权值
tensor([0.3425]) tensor([-0.4540]) tensor([0.5855]) tensor([0.5676]) tensor([-0.2230]) tensor([-1.2686]) tensor([-0.5765]) tensor([0.1418])

Process finished with exit code 0

步长step=2,训练5次

 =====第5轮=====
正向计算:o1 ,o2
tensor([0.4038]) tensor([0.3481])
损失函数(均方误差): 0.10249901562929153
    grad W:  -0.02 -0.0 -0.01 -0.0 0.02 0.06 0.02 0.05
更新后的权值
tensor([0.3543]) tensor([-0.4590]) tensor([0.5926]) tensor([0.5646]) tensor([-0.2515]) tensor([-1.3345]) tensor([-0.6009]) tensor([0.0852])

Process finished with exit code 

 步长step=2,训练10次

=====第10轮=====
正向计算:o1 ,o2
tensor([0.3519]) tensor([0.2453])
损失函数(均方误差): 0.057134903967380524
    grad W:  -0.01 -0.0 -0.01 -0.0 0.02 0.04 0.01 0.03
更新后的权值
tensor([0.4959]) tensor([-0.4270]) tensor([0.6775]) tensor([0.5838]) tensor([-0.4483]) tensor([-1.7590]) tensor([-0.7615]) tensor([-0.2611])

Process finished with exit code 0

        步长越大、训练次数越多,均方误差越小 

10.权值w1-w8初始值换为随机数,对比【作业2】指定权值结果,观察、总结并陈述

        权重换为随机数后,均方误差会变小

11.总结反向传播原理和编码实现

        前向传播通过训练数据和权重参数计算输出结果;反向传播通过导数链式法则计算损失函数对各参数的梯度,并根据梯度进行参数的更新

        反向传播其实是为了解决链式求导中的偏导数计算量大的问题,利用反向传播算法可以快速计算任意一个偏导数。反向传播算法的思想和前向传播是相同的,只是一个反向的过程

12.参考代码

# https://blog.csdn.net/qq_41033011/article/details/109325070
# https://github.com/Darwlr/Deep_learning/blob/master/06%20Pytorch%E5%AE%9E%E7%8E%B0%E5%8F%8D%E5%90%91%E4%BC%A0%E6%92%AD.ipynb
# torch.nn.Sigmoid(h_in)
 
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)

13.参考链接

(2条消息) 【2021-2022 春学期】人工智能-作业3:例题程序复现 PyTorch版_HBU_David的博客-CSDN博客

【人工智能导论:模型与算法】MOOC 8.3 误差后向传播(BP) 例题 编程验证 Pytorch版本 - HBU_DAVID - 博客园 (cnblogs.com)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值