pytorch 实现多项式回归
时间: 2023-11-12 09:08:51 浏览: 94
PyTorch实现多项式回归的基本步骤如下:
1. 导入所需的包:
```python
import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.optim as optim
```
2. 准备训练数据:
```python
x = torch.tensor([[1.0], [2.0], [3.0], [4.0]]) # 输入特征
y = torch.tensor([[0.5], [1.0], [2.0], [3.0]]) # 目标值
```
3. 定义多项式回归模型:
```python
class PolynomialRegression(nn.Module):
def __init__(self, degree):
super(PolynomialRegression, self).__init__()
self.degree = degree
self.fc = nn.Linear(degree + 1, 1)
def forward(self, x):
x_poly = x.pow(torch.arange(self.degree + 1).float())
return self.fc(x_poly)
model = PolynomialRegression(degree)
```
4. 定义损失函数和优化器:
```python
criterion = nn.MSELoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)
```
5. 训练模型:
```python
num_epochs = 1000 # 迭代次数
for epoch in range(num_epochs):
# 前向传播
outputs = model(x)
loss = criterion(outputs, y)
# 反向传播和优化
optimizer.zero_grad()
loss.backward()
optimizer.step()
# 打印训练信息
if (epoch+1) % 100 == 0:
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, loss.item()))
```
以上是使用PyTorch实现多项式回归的基本步骤。你可以根据需要调整多项式的阶数(degree)和优化器的学习率(lr)等超参数来进行模型的优化。
阅读全文