pytorch学习:一元线性回归代码

本文通过使用PyTorch库实现线性回归模型,详细介绍了如何准备数据、定义模型结构、设置损失函数与优化器,并通过迭代训练提高模型准确性。最终展示了训练结果及预测曲线。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# -*- coding: utf-8 -*-
"""
Created on Tue Aug  7 11:15:54 2018

@author: www
"""
import numpy as np
import torch
from torch import nn
from torch import optim
from torch.autograd import Variable
import matplotlib.pyplot as plt


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([ [3.3], [4.4], [55],[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)

x_train = torch.from_numpy(x_train)
y_train = torch.from_numpy(y_train)

class LinearRegression(nn.Module):
     def __init__(self):
          super(LinearRegression, self).__init__()
          self.linear = nn.Linear(1, 1)     #input and output is 1 dimension
          
     def forward(self, x):
          out = self.linear(x)
          return out
if torch.cuda.is_available():
     model = LinearRegression().cuda()
else:
     model = LinearRegression()
     
criterion = nn.MSELoss()
optimizer = optim.SGD(model.parameters(), lr = 1e-3)

num_epochs = 1000
for epoch in range(num_epochs):
     if torch.cuda.is_available():
          inputs = Variable(x_train).cuda()
          target = Variable(y_train).cuda()
     else:
          inputs = Variable(x_train)
          target = Variable(y_train)
          
     #forwards
     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(x_train))
predict = predict.data.numpy()
plt.plot(x_train.numpy(), y_train.numpy(), 'ro', label = 'Original data')
plt.plot(x_train.numpy(), predict, label='Fitting Line')
plt.show()
     









 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值