Pytorch学习之旅(2)——线性回归实战

一、线性回归模型

       回归分析中,只包括一个自变量和一个因变量,且二者的关系可用一条直线近似表示,这种回归分析称为一元线性回归分析,即 y = w * x + b .

二、模型分析

1、确定模型

M o d e l : y = w ∗ x + b Model: y = w * x + b Modely=wx+b

2、选择损失函数

采用最小平方法求解一元线性模型最优参数 w、b。
M S E : 1 m ∑ i = 1 m ( y p e r d − y ) 2 MSE: \frac{1}{m}\sum_{i=1}^{m}(y_{perd}-y)^2 MSEm1i=1m(yperdy)2

3、求解梯度并更新参数

w = w − L R ∗ w . g r a d w = w - LR * w.grad w=wLRw.grad b = b − L R ∗ b . g r a d b = b - LR*b.grad b=bLRb.grad

三、实战

1、设置训练数据及学习率

lr = 0.01 # 学习率

# 创建训练数据
x = torch.rand(20, 1) * 10		# 设置参数 X,x.shape=torch.Size([20, 1])
y = 2 * x + ( 5 + torch.rand(20, 1))	# 设置参数 Y, y.shape=torch.Size([20, 1])

w = torch.randn((1), requires_grad=True)  # 设置参数 w,w.shape=torch.Size([1])
b = torch.zeros((0), requires_grad=True)  # 设置参数 b,b.shape=torch.Size([1])

2、前向传播

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

3、计算MSE loss

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

4、反向传播

# 反向传播
loss.backward()

5、更新参数

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

6、清零张量的梯度

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

7、绘图

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, 20)
plt.ylim(8, 28)
plt.title('Iterator:{}\nw:{}\nb:{}'.format(iteration, w.data.numpy(), b.data.numpy()))
plt.pause(0.5)

8、代码汇总

import torch
import matplotlib.pyplot as plt

lr = 0.01 # 学习率

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

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
    loss = (0.5 * (y - y_pred) ** 2).mean()

    # 反向传播
    loss.backward()

    # 更新参数
    w.data.sub_(lr * w.grad)
    b.data.sub_(lr * b.grad)
    
    # 清零张量的梯度
    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, 20)
        plt.ylim(8, 28)
        plt.title('Iterator:{}\nw:{}\nb:{}'.format(iteration, w.data.numpy(), b.data.numpy()))
        plt.pause(0.5)

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

9、结果展示

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

10、分析

1、改变学习率 lr,可以改变梯度下降速率,加快拟合速度。
2、当数据过于分散时,计算的熵值可能达不到预定值以下,所以要根据实际情况调整预定值。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值