使用PyTorch框架实现AlexNet网络模型,并进行训练和测试的代码
时间: 2024-01-22 20:19:20 浏览: 119
以下是使用PyTorch框架实现AlexNet网络模型,并进行训练和测试的代码:
```python
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import transforms, datasets
# 定义超参数
batch_size = 32
learning_rate = 0.001
num_epochs = 10
# 加载数据集
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])
])
train_dataset = datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_dataset = datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
# 定义AlexNet 模型
class AlexNet(nn.Module):
def __init__(self):
super(AlexNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2)
self.relu1 = nn.ReLU(inplace=True)
self.pool1 = nn.MaxPool2d(kernel_size=3, stride=2)
self.conv2 = nn.Conv2d(64, 192, kernel_size=5, padding=2)
self.relu2 = nn.ReLU(inplace=True)
self.pool2 = nn.MaxPool2d(kernel_size=3, stride=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=3, stride=2)
self.fc1 = nn.Linear(6 * 6 * 256, 4096)
self.dropout1 = nn.Dropout()
self.fc2 = nn.Linear(4096, 4096)
self.dropout2 = nn.Dropout()
self.fc3 = nn.Linear(4096, 10)
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(-1, 6 * 6 * 256)
x = self.fc1(x)
x = self.dropout1(x)
x = self.fc2(x)
x = self.dropout2(x)
x = self.fc3(x)
return x
model = AlexNet()
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=learning_rate, momentum=0.9)
# 训练模型
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
optimizer.zero_grad()
outputs = model(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
if (i+1) % 100 == 0:
print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'
.format(epoch+1, num_epochs, i+1, len(train_loader), loss.item()))
# 测试模型
model.eval()
with torch.no_grad():
correct = 0
total = 0
for images, labels in test_loader:
outputs = model(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: {} %'.format(100 * correct / total))
```
在上述代码中,我们使用了CIFAR10数据集进行训练和测试。首先,我们使用`transforms`来对图像进行预处理。然后,我们使用`datasets`加载数据集,并使用`DataLoader`来创建一个迭代器,用于训练和测试我们的模型。
接下来,我们定义了AlexNet模型,并使用`nn.Module`类来实现它。我们在模型中定义了卷积层、池化层和全连接层。我们还使用了ReLU激活函数和Dropout层来提高模型的性能。在模型的`forward`方法中,我们定义了模型的前向传播过程。
然后,我们定义了损失函数和优化器,并使用它们来训练我们的模型。在每个epoch中,我们迭代数据集中的所有批次,并计算损失。我们使用反向传播来计算梯度,并使用优化器来更新模型的参数。
最后,我们使用测试数据集来评估模型的性能。我们计算模型在测试数据集上的准确率,并输出结果。
阅读全文