【深度之眼PyTorch框架班第五期】作业打卡02:张量操作与线性回归;计算图与动态图机制

任务名称

张量操作与线性回归;计算图与动态图机制

任务简介

学习张量的基本操作与线性回归模型的实现;学习计算图概念,理解动态图和静态图的差异

详细说明

本节将介绍张量的基本操作,如张量拼接切分、索引和变换,同时学习张量的数学运算,并基于所学习的知识,实现线性回归模型的训练,以加深知识点的认识。

本节第二部分介绍pytorch最大的特性——动态图机制,动态图机制是pytorch与tensorflow最大的区别,该部分首先介绍计算图的概念,并通过演示动态图与静态图的搭建过程来理解动态图与静态图的差异。

作业

1.调整线性回归模型停止条件以及y = 2*x + (5 + torch.randn(20, 1))中的斜率,训练一个线性回归模型;

安装matplotlib包

命令行里先激活相应环境,再安装matplotlib工具包

activate pytorch_cpu
pip install matplotlib


安装成功

调整停止条件

模型:

代码:

import torch
import matplotlib.pyplot as plt

torch.manual_seed(10)  # 为CPU设置种子用于生成随机数,使得每次的随机数结果是确定的

lr = 0.05  # 学习率

# 创建训练数据
x = torch.rand(20, 1) * 10  # x data (tensor), shape=(20, 1)
y = 2*x + (5 + torch.randn(20, 1))  # y data (tensor), shape=(20, 1)

# 构建线性回归参数
w = torch.randn(1, requires_grad=True)  # w 随机初始化(需要对w和b进行自动求导,所以requires_grad=True)
b = torch.zeros(1, requires_grad=True)  # b 初始化为0

for iteration in range(1000):

    # 前向传播
    wx = torch.mul(w, x)  # wx = w * x
    y_pred = torch.add(wx, b)  # y_pred = w * x + b

    # 计算 MSE loss
    loss = (0.5 * (y - y_pred) ** 2).mean()

    # 反向传播
    loss.backward()  # 自动求导计算梯度

    # 更新参数
    b.data.sub_(lr * b.grad)
    w.data.sub_(lr * w.grad)

    # 清零张量的梯度
    w.grad.zero_() 
    b.grad.zero_()

    # 绘图
    if iteration % 20 == 0:  # 每隔20次画一次图

        plt.scatter(x.data.numpy(), y.data.numpy())
        plt.plot(x.data.numpy(), y_pred.data.numpy(), 'r-', lw=5)
        plt.text(2, 20, 'Loss=%.4f' % loss.data.numpy(), fontdict={'size': 20, 'color':  'red'})
        plt.xlim(1.5, 10)
        plt.ylim(8, 28)
        plt.title("Iteration: {}\nw: {} b: {}".format(iteration, w.data.numpy(), b.data.numpy()))
        plt.pause(0.5)

    if loss.data.numpy() < 1:  # 停止条件:loss < 1
        plt.scatter(x.data.numpy(), y.data.numpy())
        plt.plot(x.data.numpy(), y_pred.data.numpy(), 'r-', lw=5)
        plt.text(2, 20, 'Loss=%.4f' % loss.data.numpy(), fontdict={'size': 20, 'color': 'red'})
        plt.xlim(1.5, 10)
        plt.ylim(8, 28)
        plt.title("Iteration: {}\nw: {} b: {}".format(iteration, w.data.numpy(), b.data.numpy()))
        plt.pause(0.5)
        break

  • loss<1:迭代了78次
    在这里插入图片描述

  • loss<0.1:迭代了580次,w和b很接近2和5了

疑问:但是loss没有降到0.1以下,也没到1000次的循环上限,为什么停了呢?

  • loss<10:迭代了0次

调整斜率

  • 斜率为1:迭代了84次
  • 斜率为3:迭代了72次
    在这里插入图片描述
  • 斜率为5:迭代了59次

2.计算图的两个主要概念是什么?

计算图是表示运算的有向无环图,其中两个主要概念是 表示运算的边edge表示数据的节点node

3.动态图与静态图的区别是什么?

动态图是运算与搭建图同时进行,灵活,易调节
静态图是搭建图,运算,高效,不灵活

补充

随机数种子设置参见torch中manual_seed的作用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值