本教程将带您了解如何使用 PyTorch 构建卷积神经网络(CNN)进行图像分类。CNN 是深度学习中一种强大的图像识别模型,广泛应用于计算机视觉领域。
基础概念
- 卷积层(Convolutional Layer):用于提取图像特征。
- 激活函数(Activation Function):用于引入非线性,使模型能够学习更复杂的特征。
- 池化层(Pooling Layer):用于降低特征图的尺寸,减少计算量。
- 全连接层(Fully Connected Layer):用于将特征图转换为类别标签。
实践步骤
导入库:首先,我们需要导入 PyTorch 和其他必要的库。
import torch import torch.nn as nn import torch.optim as optim
定义网络结构:接下来,我们定义一个简单的 CNN 结构。
class SimpleCNN(nn.Module): def __init__(self): super(SimpleCNN, self).__init__() self.conv1 = nn.Conv2d(1, 32, kernel_size=3, stride=1, padding=1) self.conv2 = nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1) self.fc1 = nn.Linear(64 * 7 * 7, 128) self.fc2 = nn.Linear(128, 10) def forward(self, x): x = nn.functional.relu(self.conv1(x)) x = nn.functional.max_pool2d(x, 2) x = nn.functional.relu(self.conv2(x)) x = nn.functional.max_pool2d(x, 2) x = x.view(-1, 64 * 7 * 7) x = nn.functional.relu(self.fc1(x)) x = self.fc2(x) return x
训练模型:使用训练数据训练模型。
model = SimpleCNN() criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=0.001) for epoch in range(10): for data, target in train_loader: optimizer.zero_grad() output = model(data) loss = criterion(output, target) loss.backward() optimizer.step()
评估模型:使用测试数据评估模型性能。
correct = 0 total = 0 with torch.no_grad(): for data, target in test_loader: outputs = model(data) _, predicted = torch.max(outputs.data, 1) total += target.size(0) correct += (predicted == target).sum().item() print('Accuracy of the network on the 10000 test images: %d %%' % (100 * correct / total))
扩展阅读
更多关于 PyTorch 和 CNN 的内容,请参考以下链接:
图片展示
卷积神经网络结构图
PyTorch 图标