pytorch构建线性回归模型
时间: 2023-10-30 17:07:01 浏览: 108
好的,以下是使用PyTorch构建线性回归模型的步骤:
1. 导入必要的库和模块
```python
import torch
import torch.nn as nn
import numpy as np
```
2. 准备数据
```python
# 生成随机数据
np.random.seed(2021)
x = np.random.rand(100, 1)
y = 3 * x + 2 + 0.2 * np.random.rand(100, 1)
# 转换为Tensor
x_tensor = torch.from_numpy(x).float()
y_tensor = torch.from_numpy(y).float()
```
3. 定义模型
```python
class LinearRegression(nn.Module):
def __init__(self):
super(LinearRegression, self).__init__()
self.linear = nn.Linear(1, 1)
def forward(self, x):
out = self.linear(x)
return out
model = LinearRegression()
```
4. 定义损失函数和优化器
```python
criterion = nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
```
5. 训练模型
```python
num_epochs = 1000
for epoch in range(num_epochs):
# 前向传播
outputs = model(x_tensor)
loss = criterion(outputs, y_tensor)
# 反向传播和优化
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (epoch+1) % 100 == 0:
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, loss.item()))
```
6. 测试模型
```python
# 测试模型
model.eval()
with torch.no_grad():
predicted = model(x_tensor).detach().numpy()
# 可视化结果
import matplotlib.pyplot as plt
plt.plot(x, y, 'ro', label='Original data')
plt.plot(x, predicted, label='Fitted line')
plt.legend()
plt.show()
```
阅读全文