用Pytorch卷积神经网络做回归预测的代码
时间: 2023-08-13 13:04:59 浏览: 119
下面是一个使用 PyTorch 卷积神经网络进行回归预测的简单示例代码:
```python
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
# 定义一个卷积神经网络模型
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 4 * 4, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 1)
def forward(self, x):
x = self.pool(nn.functional.relu(self.conv1(x)))
x = self.pool(nn.functional.relu(self.conv2(x)))
x = x.view(-1, 16 * 4 * 4)
x = nn.functional.relu(self.fc1(x))
x = nn.functional.relu(self.fc2(x))
x = self.fc3(x)
return x
# 准备数据
x_train = np.random.rand(100, 1, 28, 28)
y_train = np.random.rand(100, 1)
# 转换为张量
x_train = torch.from_numpy(x_train).float()
y_train = torch.from_numpy(y_train).float()
# 定义模型、损失函数和优化器
model = Net()
criterion = nn.MSELoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)
# 训练模型
for epoch in range(100):
optimizer.zero_grad()
output = model(x_train)
loss = criterion(output, y_train)
loss.backward()
optimizer.step()
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, 100, loss.item()))
# 使用训练好的模型进行预测
x_test = np.random.rand(10, 1, 28, 28)
x_test = torch.from_numpy(x_test).float()
y_pred = model(x_test)
print(y_pred)
```
在这个例子中,我们定义了一个包含两个卷积层和三个全连接层的卷积神经网络模型。我们使用随机生成的数据进行训练,并使用均方误差损失函数和随机梯度下降优化器进行训练。最后,我们使用训练好的模型进行预测。
阅读全文