使用pytorch做一元线性回归以及预测

import matplotlib.pyplot as plt # 导入画图的程序包
import torch
import numpy as np
x = torch.linspace(0,100,100).type(torch.FloatTensor)
rand = torch.randn(100)* 10
y = x + rand
#划分训练集与测试集。90个训练 10个测试。
x_train = x[ : -10]
x_test = x[-10 : ]
y_train = y[ : -10]
y_test = y[-10 : ]

# plt.figure(figsize=(10,8)) #设定绘制窗口大小10*8
# plt.xlabel('X') #添加X轴标注
# plt.ylabel('Y') #添加Y轴的标注
# plt.plot(x_train.numpy(),y_trian.numpy(),'o')
# plt.show() #画出图形

#定义两个自动微分变量a和b
a = torch.rand(1, requires_grad=True)
b = torch.rand(1, requires_grad=True)
#设置学习率
learning_rate = 0.0001
"""对a,b进行迭代计算。"""
for i in range(1000):
#计算当前a,b条件下的模型预测值
    predictons = a.expand_as(x_train) * x_train + b.expand_as(x_train)
    #将所有训练数据带入模型ax+b,计算每个预测值。这里的x_train和predictions都是(90,1)的张量
    loss = torch.mean((predictons - y_train) ** 2)
    print('loss:', loss)
    loss.backward()

    a.data = a.data - learning_rate * a.grad
    b.data = b.data - learning_rate * b.grad
    a.grad.data.zero_()  # 清空a的梯度数值
    b.grad.data.zero_()

x_data = x_train.data.numpy() # 获得x包裹的数据
x_pred = x_test.data.numpy() # 获得包裹的测试数据的自变量
plt.figure(figsize = (10, 7)) # 设定绘图窗口大小
plt.plot(x_data, y_train.data.numpy(), 'o') # 绘制训练数据
plt.plot(x_pred, y_test.data.numpy(), 's') # 绘制测试数据
x_data = np.r_[x_data, x_test.data.numpy()]
xplot = plt.plot(x_data, a.data.numpy() * x_data + b.data.numpy())  # 绘制拟合数据
yplot = plt.plot(x_pred, a.data.numpy() * x_pred + b.data.numpy(), 'o') # 绘制预测数据
plt.xlabel('X') # 更改横坐标轴标注
plt.ylabel('Y') # 更改纵坐标轴标注
str1 = str(a.data.numpy()[0]) + 'x +' + str(b.data.numpy()[0]) # 图例信息
plt.legend([xplot, yplot],['Data', str1]) # 绘制图例
plt.show()

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

lihongli000

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

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

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

打赏作者

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

抵扣说明:

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

余额充值