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]

[]

pytorch实现简单的线性回归模型_第1张图片

 

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]

  • pytorch实现简单的线性回归模型_第2张图片

 

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

  • pytorch实现简单的线性回归模型_第3张图片

 

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

  • pytorch实现简单的线性回归模型_第4张图片

 

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

  • pytorch实现简单的线性回归模型_第5张图片

 

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

pytorch实现简单的线性回归模型_第6张图片

 

你可能感兴趣的:(笔记,pytorch,线性回归,深度学习)