栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

动手学深度学 pytorch pdf_pytorch线性回归代码?

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

动手学深度学 pytorch pdf_pytorch线性回归代码?

0. 往期内容

[一]深度学习Pytorch-张量定义与张量创建

[二]深度学习Pytorch-张量的操作:拼接、切分、索引和变换

[三]深度学习Pytorch-张量数学运算

[四]深度学习Pytorch-线性回归

深度学习Pytorch-线性回归

0. 往期内容1. 线性回归概念2. 线性回归求解步骤3. 线性回归实战

1. 线性回归概念

2. 线性回归求解步骤

LR是步长,也叫学习率;
grad是梯度;

3. 线性回归实战
import torch
import matplotlib.pyplot as plt
torch.manual_seed(10)

lr = 0.05  # 学习率    20191015修改

# 创建训练数据
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,b,自动梯度求导需要设置requires_grad为True
w = torch.randn((1), requires_grad=True) #初始化w为数值为正态分布,大小为1的张量
b = torch.zeros((1), requires_grad=True) #初始化b为数值为0,大小为1的张量

for iteration in range(1000):

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

    # 计算 MSE loss
    #0.5是为了求导过程中消掉系数2设置的,影响不大
    loss = (0.5 * (y - y_pred) ** 2).mean() 

    # 反向传播,使用自动求导系统反向传播即可得到梯度
    loss.backward()

    # 更新参数w,b
    b.data.sub_(lr * b.grad) #b=b-lr*b.grad
    w.data.sub_(lr * w.grad) #w=w-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, 28)
        plt.title("Iteration: {}nw: {} b: {}".format(iteration, w.data.numpy(), b.data.numpy()))
        plt.pause(0.5)

        #loss小于1时停止迭代更新
        if loss.data.numpy() < 1:
            break
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/783302.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号