第二次作业

本文通过调整线性回归模型的停止条件和斜率,训练了一个线性回归模型,并探讨了计算图的两个主要概念:结点表示数据,边表示运算。此外,还对比了动态图和静态图的区别,前者在pytorch中实现,更灵活易调节;后者在TensorFlow中使用,高效但不灵活。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

"""
    作者:Aidan
    时间:18/01/2020
    功能:线性回归
"""

import torch
import matplotlib.pyplot as plt


def main():

    torch.manual_seed(10)

    # 学习率
    lr = 0.05

    # 创建训练数据
    x = torch.rand(20, 1) * 10
    y = 5*x + (5 + torch.randn(20, 1)) # y值随机加入扰动

    #构建线性回归模型
    w = torch.randn((1), requires_grad=True)
    b = torch.zeros((1), requires_grad=True)

    for iteration in range(1000):

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

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

        # 反向传播
        loss.backward()

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

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

        # 绘图
        if iteration % 20 == 0:
            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, 45)
            plt.title('Iteratiion:{}\nw:{} b:{}'.format(iteration, w.data.numpy(), b.data.numpy()))
            plt.pause(0.5)

            if loss.data.numpy() < 0.8:
                break


if __name__ == '__main__':
    main()

在这里插入图片描述

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

  • 结点:表示数据,如向量,矩阵,张量。
  • 边:表示运算,如加减乘除卷积等。

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

两者的搭建方式不同

  • 动态图

    • 运算与搭建同时进行,典型代表是pytorch
    • 特点:灵活、易调节
  • 静态图

    • 先搭建图,后运算,典型代表TensorFlow
    • 特点:高效、不灵活
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Aidanmomo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值