pytorch 线性回归代码

该博客介绍了如何使用PyTorch实现线性回归模型。首先定义超参数,包括输入和输出大小、训练轮数及学习率。接着,创建线性回归模型类,并实例化。然后,设置损失函数为均方误差损失,优化器为随机梯度下降。通过迭代训练模型,并最终绘制了训练数据点和预测结果的图形。

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

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

Hyper Parameters

input_size = 1
output_size = 1
num_epochs = 1000
learning_rate = 0.001

x_train = np.array([[2.3], [4.4], [3.7], [6.1], [7.3], [2.1],[5.6], [7.7], [8.7], [4.1],

                [6.7], [6.1], [7.5], [2.1], [7.2],

                [5.6], [5.7], [7.7], [3.1]], dtype=np.float32)

#xtrain生成矩阵数据

y_train = np.array([[3.7], [4.76], [4.], [7.1], [8.6], [3.5],[5.4], [7.6], [7.9], [5.3],

                [7.3], [7.5], [8.5], [3.2], [8.7],

                [6.4], [6.6], [7.9], [5.3]], dtype=np.float32)

plt.figure()
#画图散点图
plt.scatter(x_train,y_train)
plt.xlabel(‘x_train’)
#x轴名称
plt.ylabel(‘y_train’)
#y轴名称
#显示图片
plt.show()

Linear Regression Model

class LinearRegression(nn.Module):
def init(self, input_size, output_size):
super(LinearRegression, self).init()
self.linear = nn.Linear(input_size, output_size)

def forward(self, x):
    out = self.linear(x)
    return out

model = LinearRegression(input_size, output_size)

Loss and Optimizer

criterion = nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate) 采用随机梯度下降

Train the Model

for epoch in range(num_epochs):
# Convert numpy array to torch Variable
inputs = Variable(torch.from_numpy(x_train))
targets = Variable(torch.from_numpy(y_train))

# Forward + Backward + Optimize
optimizer.zero_grad()  
outputs = model(inputs)#前向传播
loss = criterion(outputs, targets)#计算loss    #实例化后好像直接调用实例名()
loss.backward()
optimizer.step()#更新参数

if (epoch+1) % 5 == 0:
	a=loss.item()#新版本下用item(),而不是data()
	

	print('epoch[%d/%d],Loss: %.4f'%(epoch+1,num_epochs,a))

Plot the graph

c=list(range(20))

model.eval()
predicted = model(Variable(torch.from_numpy(x_train))).data.numpy()
plt.plot(x_train, y_train, ‘ro’)
plt.plot(x_train, predicted, label=‘predict’)

plt.legend()
plt.show()

在这里插入图片描述在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值