一维线性回归

# -*- coding: utf-8 -*-
'''
Created on 2018年9月29日

@author: plus
'''

import torch
import numpy as np
from torch.autograd import Variable
import matplotlib.pyplot as plt

torch.manual_seed(2017)
 
# 读入数据 x 和 y
x_train = np.array([[3.3], [4.4], [5.5], [6.71], [6.93], [4.168],
                    [9.779], [6.182], [7.59], [2.167], [7.042],
                    [10.791], [5.313], [7.997], [3.1]], dtype=np.float32)
 
y_train = np.array([[1.7], [2.76], [2.09], [3.19], [1.694], [1.573],
                    [3.366], [2.596], [2.53], [1.221], [2.827],
                    [3.465], [1.65], [2.904], [1.3]], dtype=np.float32)
 
 
class LinearRegression(torch.nn.Module):
    def __init__(self):
        super(LinearRegression, self).__init__()
        self.linear = torch.nn.Linear(1, 1)
        
    def forward(self, x):
        out = self.linear(x)
        return out
    
    
if torch.cuda.is_available():
    model = LinearRegression().cuda()
else:
    model = LinearRegression()
    
    
    
    
criterion = torch.nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=1e-3)
 
 
num_epochs = 1000
for epoch in range(num_epochs):
    if torch.cuda.is_available():
        inputs = Variable(torch.from_numpy(x_train)).cuda()
        target = Variable(torch.from_numpy(y_train)).cuda()
    else:
        inputs = Variable(torch.from_numpy(x_train))
        target = Variable(torch.from_numpy(y_train))
        
        
    #forward
    out = model(inputs)
    loss = criterion(out, target)
    #backward
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    
    
    if(epoch+1) % 20 == 0:
        print('Epoch[{}/{}], loss: {:.6f}'
              .format(epoch+1, num_epochs, loss.data[0]))
        
 
 
model.eval()
predict = model(Variable(torch.from_numpy(x_train)).cuda())
predict = predict.cpu()
predict = predict.data.numpy()
plt.plot(x_train, y_train, 'ro', label='Original data')
plt.plot(x_train, predict, label='Fitting Line')
plt.show()
 
 
#https://github.com/L1aoXingyu/code-of-learn-deep-learning-with-pytorch
 
 
 

猜你喜欢

转载自blog.csdn.net/zzb5233/article/details/82899613