pytorch 实现多元线性回归
时间: 2024-04-03 20:29:57 浏览: 136
在PyTorch中实现多元线性回归可以通过以下步骤完成:
1. 导入所需的库和模块:
```python
import torch
import torch.nn as nn
import torch.optim as optim
```
2. 准备数据:
```python
# 输入特征
x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]], dtype=torch.float32)
# 目标值
y = torch.tensor([[4], [7], [10], [13]], dtype=torch.float32)
```
3. 定义模型:
```python
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):
return self.linear(x)
```
4. 实例化模型和损失函数:
```python
model = LinearRegression(input_size=3, output_size=1)
criterion = nn.MSELoss()
```
5. 定义优化器:
```python
optimizer = optim.SGD(model.parameters(), lr=0.01)
```
6. 训练模型:
```python
num_epochs = 1000
for epoch in range(num_epochs):
# 前向传播
outputs = model(x)
loss = criterion(outputs, y)
# 反向传播和优化
optimizer.zero_grad()
loss.backward()
optimizer.step()
# 每100个epoch打印一次损失值
if (epoch+1) % 100 == 0:
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, loss.item()))
```
7. 使用模型进行预测:
```python
# 输入特征
test_input = torch.tensor([[2, 3, 4]], dtype=torch.float32)
# 预测
predicted = model(test_input)
print('Predicted value:', predicted.item())
```
阅读全文