用pytorch写一个简单的线性回归模型

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

定义超参数

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)

x轴名称

plt.xlabel(‘x_train’)

y轴名称

plt.ylabel(‘y_train’)

显示图片

plt.show()

定义线性回归模型

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)

损失函数定义,参数优化器定义

criterion = nn.MSELoss() # 定义损失类型为均方误差
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)

模型训练

for epoch in range(num_epochs):
# np数组转化为张量
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.backward()
# 参数优化
optimizer.step()
# 每迭代5次打印一次损失值
if (epoch+1) % 5 == 0:
    print ('Epoch [%d/%d], Loss: %.4f' 
           %(epoch+1, num_epochs, loss.item()))

画图

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()线性回归结果画图

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值