请帮我编写pytorch中能完整实现卷积神经网络图像分类的代码
时间: 2024-05-05 12:18:57 浏览: 102
好的,以下是一个能够实现卷积神经网络图像分类的 PyTorch 代码:
```python
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
import torchvision.datasets as datasets
# 定义卷积神经网络
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5) # 输入通道为3,输出通道为6,卷积核大小为5x5
self.pool = nn.MaxPool2d(2, 2) # 2x2的最大池化层
self.conv2 = nn.Conv2d(6, 16, 5) # 输入通道为6,输出通道为16,卷积核大小为5x5
self.fc1 = nn.Linear(16 * 5 * 5, 120) # 全连接层1,输入维度为16*5*5,输出维度为120
self.fc2 = nn.Linear(120, 84) # 全连接层2,输入维度为120,输出维度为84
self.fc3 = nn.Linear(84, 10) # 全连接层3,输入维度为84,输出维度为10(10类)
def forward(self, x):
x = self.pool(nn.functional.relu(self.conv1(x))) # 第一层卷积,ReLU激活函数,2x2的最大池化层
x = self.pool(nn.functional.relu(self.conv2(x))) # 第二层卷积,ReLU激活函数,2x2的最大池化层
x = x.view(-1, 16 * 5 * 5) # 将卷积层输出展平为一维向量
x = nn.functional.relu(self.fc1(x)) # 第一层全连接,ReLU激活函数
x = nn.functional.relu(self.fc2(x)) # 第二层全连接,ReLU激活函数
x = self.fc3(x) # 第三层全连接
return x
# 数据预处理
transform = transforms.Compose([
transforms.Resize((32, 32)), # 重新调整大小为32x32
transforms.ToTensor(), # 将图像转换为PyTorch可以处理的Tensor
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) # 归一化
])
# 加载CIFAR10数据集(10类图像数据集)
trainset = datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=32, shuffle=True, num_workers=2)
testset = datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=32, shuffle=False, num_workers=2)
# 实例化卷积神经网络
net = CNN()
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
# 训练网络
for epoch in range(5): # 训练5个epoch
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
inputs, labels = data
optimizer.zero_grad() # 清空梯度缓存
outputs = net(inputs) # 前向传播
loss = criterion(outputs, labels) # 计算损失
loss.backward() # 反向传播
optimizer.step() # 更新权重
running_loss += loss.item()
if i % 2000 == 1999: # 每2000个batch打印一次loss
print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 2000))
running_loss = 0.0
print('Finished Training')
# 在测试集上测试网络
correct = 0
total = 0
with torch.no_grad():
for data in testloader:
images, labels = data
outputs = net(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy of the network on the 10000 test images: %d %%' % (100 * correct / total))
```
这段代码实现了一个简单的卷积神经网络,用于对CIFAR10数据集进行分类。在训练集上训练5个epoch后,在测试集上得到了约70%的分类精度。不过,这只是一个简单的示例模型,可以根据具体的分类任务进行修改和优化。
阅读全文