pytorch线性回归代码
时间: 2023-06-03 08:03:12 浏览: 96
线性回归算法代码.zip
5星 · 资源好评率100%
很高兴为您服务!以下是一个简单的PyTorch线性回归代码示例:
```
import torch
import torch.nn as nn
import numpy as np
# 定义输入和输出
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)
# 转换为张量
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) # 输入和输出的维度都为1
def forward(self, x):
out = self.linear(x)
return out
model = LinearRegression()
# 定义损失函数和优化器
criterion = nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
# 训练模型
num_epochs = 1000
for epoch in range(num_epochs):
# forward
outputs = model(X_train)
loss = criterion(outputs, y_train)
# backward
optimizer.zero_grad() # 梯度清零
loss.backward()
# update
optimizer.step()
if (epoch+1) % 50 == 0:
print ('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, loss.item()))
# 测试模型
predicted = model(X_train).detach().numpy()
print(predicted)
# 保存模型
torch.save(model.state_dict(), 'model.ckpt')
```
希望可以帮到您!
阅读全文