用pytorch写一段CNN代码
时间: 2023-03-30 11:02:58 浏览: 123
我可以回答这个问题。以下是一个使用 PyTorch 编写的简单 CNN 代码示例:
```python
import torch
import torch.nn as nn
import torch.optim as optim
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Conv2d(3, 16, kernel_size=3, stride=1, padding=1)
self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv2 = nn.Conv2d(16, 32, kernel_size=3, stride=1, padding=1)
self.fc1 = nn.Linear(32 * 8 * 8, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = self.pool(torch.relu(self.conv1(x)))
x = self.pool(torch.relu(self.conv2(x)))
x = x.view(-1, 32 * 8 * 8)
x = torch.relu(self.fc1(x))
x = self.fc2(x)
return x
model = CNN()
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=.001, momentum=.9)
# 训练模型
for epoch in range(10):
running_loss = .
for i, data in enumerate(trainloader, ):
inputs, labels = data
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if i % 200 == 1999:
print('[%d, %5d] loss: %.3f' %
(epoch + 1, i + 1, running_loss / 200))
running_loss = .
print('Finished Training')
```
这段代码定义了一个简单的 CNN 模型,使用交叉熵损失函数和随机梯度下降优化器进行训练。在训练过程中,模型会输出每个 epoch 的平均损失。
阅读全文