本项目使用PyTorch实现经典VGG卷积神经网络,并详细记录了从模型搭建到训练、测试全过程,附有训练与验证数据集的损失与精度变化曲线。通过详尽注释帮助理解每一步骤的目的和作用,适合深度学习初学者研究和实践。
VGG(Visual Geometry Group)网络是由牛津大学的Visual Geometry Group团队在2014年提出的一种深度卷积神经网络(CNN)。它以其深而狭窄的结构著名,使用了大量的3x3卷积层来构建模型,这使得VGG在ImageNet图像分类任务上取得了很好的效果。PyTorch是一个流行的深度学习框架,提供了灵活的API,使搭建和训练深度学习模型变得简单易行。
本篇将详细介绍如何使用PyTorch实现VGG模型,并生成训练集和测试集的损失与准确率折线图。我们需要理解VGG网络的基本结构:它通常由多个卷积层堆叠而成,每个阶段的卷积层后跟着一个最大池化层,最后是全连接层。常见的变体包括VGG16和VGG19,分别包含16和19层卷积。
在PyTorch中定义我们的VGG模型:
```python
import torch.nn as nn
class VGG(nn.Module):
def __init__(self, num_classes=1000):
super(VGG, self).__init__()
# 定义每个阶段的卷积层和池化层
self.features = nn.Sequential(
# 阶段1
nn.Conv2d(3, 64, kernel_size=3, padding=1), nn.ReLU(),
nn.Conv2d(64, 64, kernel_size=3, padding=1), nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2),
# 阶段2
nn.Conv2d(64, 128, kernel_size=3, padding=1), nn.ReLU(),
nn.Conv2d(128, 128, kernel_size=3, padding=1), nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2),
# ...其他阶段,依此类推
)
# 全连接层
self.classifier = nn.Sequential(
nn.Linear(512 * 7 * 7, 4096), nn.ReLU(),
nn.Dropout(p=0.5),
nn.Linear(4096, 4096), nn.ReLU(),
nn.Dropout(p=0.5),
nn.Linear(4096, num_classes)
)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.classifier(x)
return x
```
在训练过程中,我们需要定义损失函数(如交叉熵损失)和优化器(如SGD)。同时,为了可视化损失和准确率,我们可以使用`torch.utils.tensorboard`或`matplotlib`库来绘制图表:
```python
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision.datasets import CIFAR10
from torchvision.transforms import ToTensor, Normalize
# 加载数据
transform = transforms.Compose([ToTensor(), Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
train_dataset = CIFAR10(root=./data, train=True, download=True, transform=transform)
test_dataset = CIFAR10(root=./data, train=False, download=True, transform=transform)
train_loader = DataLoader(train_dataset, batch_size=100, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=100, shuffle=False)
# 初始化模型和优化器
vgg_model = VGG(num_classes=10)
optimizer = optim.SGD(vgg_model.parameters(), lr=0.001, momentum=0.9)
# 训练过程
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
# 前向传播,计算损失
outputs = vgg_model(images)
loss = criterion(outputs, labels)
# 反向传播,更新权重
optimizer.zero_grad()
loss.backward()
optimizer.step()
# 记录并打印训练状态
if (i+1) % 100 == 0:
print(fEpoch [{epoch+1}/{num_epochs}], Step [{i+1}/{len(train_loader)}], Loss: {loss.item():.4f})
# 计算验证集准确率
with torch.no_grad():
correct = 0
total = 0
for images, labels in test_loader:
outputs = vgg_model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
accuracy = 100 * correct / total
print