pytorch实现简单的线性回归模型

import numpy as np
import random
import matplotlib.pyplot as plt
x = np.arange(20)
y = np.array([5*x[i]+random.randint(1,20) for i in range(len(x))])
print("产生的X:",x)
print("产生的y:",y)
plt.plot(x,y,"r.")

产生的X: [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19] 产生的y: [ 17 16 25 26 36 30 34 45 47 59 53 58 71 81 73 91 98 99 95 111]

[<matplotlib.lines.Line2D at 0x17484978fd0>]

 

import torch
x_train = torch.from_numpy(x).float()
y_train = torch.from_numpy(y).float()
print(x_train)
print(y_train)
class LinearRegression(torch.nn.Module):
    def __init__(self):
        super(LinearRegression,self).__init__()
        #线性回归,输入和输出都是一维的
        self.linear=torch.nn.Linear(1,1)
    def forward(self,x):
        return self.linear(x)

tensor([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15., 16., 17., 18., 19.]) tensor([ 17., 16., 25., 26., 36., 30., 34., 45., 47., 59., 53., 58., 71., 81., 73., 91., 98., 99., 95., 111.])

#新建模型、误差函数、优化器
model = LinearRegression()
criterion = torch.nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(),0.001)
#开始训练
num_epochs = 10
for i in range(num_epochs):
    input_data = x_train.unsqueeze(1) #增加一维
    target = y_train.unsqueeze(1)
    out = model(input_data)
    loss = criterion(out,target)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    print("Epoch:[{}/{}],loss:[{:.4f}]".format(i+1,num_epochs,loss.item()))
    if((i+1)%2==0):
        predict = model(input_data)
        plt.plot(x_train.data.numpy(),predict.squeeze(1).data.numpy(),"r")
        loss = criterion(predict,target)
        plt.title("Loss:{:.4f}".format(loss.item()))
        plt.xlabel("X")
        plt.ylabel("Y")
        plt.scatter(x_train,y_train)
        plt.show()

Epoch:[1/10],loss:[5012.6416] Epoch:[2/10],loss:[2854.1079]

 

Epoch:[3/10],loss:[1634.9456] Epoch:[4/10],loss:[946.3441]

 

Epoch:[5/10],loss:[557.4068] Epoch:[6/10],loss:[337.7210]

 

Epoch:[7/10],loss:[213.6298] Epoch:[8/10],loss:[143.5305]

 

Epoch:[9/10],loss:[103.9265] Epoch:[10/10],loss:[81.5461]

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值