)
1. AlexNet基础与PyTorch环境准备AlexNet是2012年ImageNet竞赛冠军模型首次证明了深度学习在计算机视觉中的强大能力。它采用5层卷积3层全连接结构引入ReLU激活函数、局部响应归一化(LRN)和Dropout等创新技术。实测在猫狗分类任务中即使原始输入尺寸缩小到65x65仍能达到85%的准确率。PyTorch实现需要准备以下环境Python 3.8PyTorch 1.12需匹配CUDA版本torchvision用于图像预处理matplotlib结果可视化安装命令示例conda create -n alexnet python3.8 conda install pytorch torchvision -c pytorch pip install matplotlib关键配置验证import torch print(torch.__version__) # 应输出1.12 print(torch.cuda.is_available()) # 确认GPU可用2. 数据预处理实战技巧猫狗数据集常见问题图片尺寸不一、样本不均衡、数据量不足。我们采用分层处理2.1 智能分类与增强原始数据通常混合存放可用正则表达式自动分类import re from PIL import Image def classify_images(src_dir, dst_dir): os.makedirs(f{dst_dir}/cat, exist_okTrue) os.makedirs(f{dst_dir}/dog, exist_okTrue) for img_name in os.listdir(src_dir): src_path os.path.join(src_dir, img_name) animal re.search(r(cat|dog), img_name).group() shutil.copy(src_path, f{dst_dir}/{animal})2.2 动态数据增强方案使用torchvision的transforms组合增强策略from torchvision import transforms train_transform transforms.Compose([ transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ColorJitter(brightness0.3, contrast0.3), transforms.ToTensor(), transforms.Normalize(mean[0.485, 0.456, 0.406], std[0.229, 0.224, 0.225]) ]) valid_transform transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(mean[0.485, 0.456, 0.406], std[0.229, 0.224, 0.225]) ])3. 网络构建核心细节3.1 卷积层参数计算秘诀AlexNet首层卷积核为11x11现代实现常调整为7x7或5x5以适应小尺寸输入。计算输出尺寸的公式输出高度 floor((输入高度 2*padding - kernel_size)/stride 1)示例输入224x224kernel11, stride4, padding2时(224 2*2 - 11)/4 1 553.2 完整网络实现import torch.nn as nn class AlexNet(nn.Module): def __init__(self, num_classes2): super().__init__() self.features nn.Sequential( nn.Conv2d(3, 64, kernel_size5, stride2, padding2), nn.ReLU(inplaceTrue), nn.MaxPool2d(kernel_size3, stride2), nn.Conv2d(64, 192, kernel_size3, padding1), nn.ReLU(inplaceTrue), nn.MaxPool2d(kernel_size3, stride2), nn.Conv2d(192, 384, kernel_size3, padding1), nn.ReLU(inplaceTrue), nn.Conv2d(384, 256, kernel_size3, padding1), nn.ReLU(inplaceTrue), nn.Conv2d(256, 256, kernel_size3, padding1), nn.ReLU(inplaceTrue), nn.MaxPool2d(kernel_size3, stride2), ) self.classifier nn.Sequential( nn.Dropout(), nn.Linear(256 * 6 * 6, 4096), nn.ReLU(inplaceTrue), nn.Dropout(), nn.Linear(4096, 4096), nn.ReLU(inplaceTrue), nn.Linear(4096, num_classes), ) def forward(self, x): x self.features(x) x torch.flatten(x, 1) x self.classifier(x) return x4. 训练优化与调参技巧4.1 学习率动态调整采用ReduceLROnPlateau策略optimizer torch.optim.SGD( model.parameters(), lr0.01, momentum0.9, weight_decay0.0005 ) scheduler torch.optim.lr_scheduler.ReduceLROnPlateau( optimizer, modemax, factor0.1, patience3 )4.2 早停机制实现best_acc 0 for epoch in range(100): train(model, train_loader) acc validate(model, valid_loader) if acc best_acc: best_acc acc torch.save(model.state_dict(), best.pth) scheduler.step(acc) if optimizer.param_groups[0][lr] 1e-6: print(Early stopping) break5. 结果分析与模型部署训练完成后通过混淆矩阵分析常见错误from sklearn.metrics import confusion_matrix y_true, y_pred [], [] with torch.no_grad(): for inputs, labels in test_loader: outputs model(inputs) y_true.extend(labels.numpy()) y_pred.extend(outputs.argmax(1).numpy()) print(confusion_matrix(y_true, y_pred))部署时建议使用TorchScripttraced_model torch.jit.trace(model, torch.rand(1,3,224,224)) traced_model.save(alexnet_traced.pt)实际项目中遇到验证集准确率波动大的情况发现是数据增强中的随机裁剪幅度过大导致。将RandomResizedCrop的scale参数从(0.08,1.0)调整为(0.5,1.0)后模型稳定性显著提升。