alexnet代码pytorch cifar100
时间: 2024-06-08 07:09:44 浏览: 159
AlexNet卷积神经网络图像分类Pytorch训练代码 使用Cifar100数据集
5星 · 资源好评率100%
以下是使用PyTorch实现AlexNet在CIFAR-100数据集上的代码:
```
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.datasets as datasets
import torchvision.transforms as transforms
# 定义AlexNet模型
class AlexNet(nn.Module):
def __init__(self):
super(AlexNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1)
self.relu1 = nn.ReLU(inplace=True)
self.pool1 = nn.MaxPool2d(kernel_size=2)
self.conv2 = nn.Conv2d(64, 192, kernel_size=3, padding=1)
self.relu2 = nn.ReLU(inplace=True)
self.pool2 = nn.MaxPool2d(kernel_size=2)
self.conv3 = nn.Conv2d(192, 384, kernel_size=3, padding=1)
self.relu3 = nn.ReLU(inplace=True)
self.conv4 = nn.Conv2d(384, 256, kernel_size=3, padding=1)
self.relu4 = nn.ReLU(inplace=True)
self.conv5 = nn.Conv2d(256, 256, kernel_size=3, padding=1)
self.relu5 = nn.ReLU(inplace=True)
self.pool3 = nn.MaxPool2d(kernel_size=2)
self.fc1 = nn.Linear(256 * 2 * 2, 4096)
self.relu6 = nn.ReLU(inplace=True)
self.dropout1 = nn.Dropout()
self.fc2 = nn.Linear(4096, 4096)
self.relu7 = nn.ReLU(inplace=True)
self.dropout2 = nn.Dropout()
self.fc3 = nn.Linear(4096, 100)
def forward(self, x):
x = self.conv1(x)
x = self.relu1(x)
x = self.pool1(x)
x = self.conv2(x)
x = self.relu2(x)
x = self.pool2(x)
x = self.conv3(x)
x = self.relu3(x)
x = self.conv4(x)
x = self.relu4(x)
x = self.conv5(x)
x = self.relu5(x)
x = self.pool3(x)
x = x.view(x.size(0), 256 * 2 * 2)
x = self.fc1(x)
x = self.relu6(x)
x = self.dropout1(x)
x = self.fc2(x)
x = self.relu7(x)
x = self.dropout2(x)
x = self.fc3(x)
return x
# 加载数据集
train_dataset = datasets.CIFAR100(root='./data', train=True, download=True, transform=transforms.ToTensor())
test_dataset = datasets.CIFAR100(root='./data', train=False, download=True, transform=transforms.ToTensor())
# 定义训练参数
batch_size = 128
learning_rate = 0.01
num_epochs = 50
# 定义数据加载器
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
# 定义模型、损失函数和优化器
model = AlexNet()
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=learning_rate, momentum=0.9)
# 训练模型
for epoch in range(num_epochs):
train_loss = 0.0
train_acc = 0.0
model.train()
for i, (images, labels) in enumerate(train_loader):
optimizer.zero_grad()
outputs = model(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
train_loss += loss.item() * images.size(0)
_, preds = torch.max(outputs, 1)
train_acc += torch.sum(preds == labels.data)
train_loss /= len(train_loader.dataset)
train_acc /= len(train_loader.dataset)
test_loss = 0.0
test_acc = 0.0
model.eval()
with torch.no_grad():
for i, (images, labels) in enumerate(test_loader):
outputs = model(images)
loss = criterion(outputs, labels)
test_loss += loss.item() * images.size(0)
_, preds = torch.max(outputs, 1)
test_acc += torch.sum(preds == labels.data)
test_loss /= len(test_loader.dataset)
test_acc /= len(test_loader.dataset)
print('Epoch [{}/{}], Train Loss: {:.4f}, Train Acc: {:.4f}, Test Loss: {:.4f}, Test Acc: {:.4f}'.format(
epoch+1, num_epochs, train_loss, train_acc, test_loss, test_acc))
```
注意,在CIFAR-100数据集上使用AlexNet模型需要对其进行一些修改,具体可以参考[这篇论文](https://arxiv.org/pdf/1404.2188.pdf)。此外,为了便于训练,我们使用了较小的学习率(0.01)和较小的batch_size(128)。
阅读全文