使用PyTorch框架实现AlexNet网络模型,并使用minist数据集进行训练和测试的代码
时间: 2024-01-22 18:19:17 浏览: 95
以下是使用PyTorch框架实现AlexNet网络模型,并使用MNIST数据集进行训练和测试的代码:
```python
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
# 定义网络模型
class AlexNet(nn.Module):
def __init__(self):
super(AlexNet, self).__init__()
self.conv1 = nn.Conv2d(1, 64, kernel_size=11, stride=4, padding=2)
self.pool1 = nn.MaxPool2d(kernel_size=3, stride=2)
self.conv2 = nn.Conv2d(64, 192, kernel_size=5, padding=2)
self.pool2 = nn.MaxPool2d(kernel_size=3, stride=2)
self.conv3 = nn.Conv2d(192, 384, kernel_size=3, padding=1)
self.conv4 = nn.Conv2d(384, 256, kernel_size=3, padding=1)
self.conv5 = nn.Conv2d(256, 256, kernel_size=3, padding=1)
self.pool3 = nn.MaxPool2d(kernel_size=3, stride=2)
self.fc1 = nn.Linear(256 * 6 * 6, 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.pool1(torch.relu(self.conv1(x)))
x = self.pool2(torch.relu(self.conv2(x)))
x = torch.relu(self.conv3(x))
x = torch.relu(self.conv4(x))
x = self.pool3(torch.relu(self.conv5(x)))
x = x.view(-1, 256 * 6 * 6)
x = torch.relu(self.fc1(x))
x = self.dropout1(x)
x = torch.relu(self.fc2(x))
x = self.dropout2(x)
x = self.fc3(x)
return x
# 定义数据转换
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])
# 加载数据集
train_dataset = datasets.MNIST(root='./data', train=True, transform=transform, download=True)
test_dataset = datasets.MNIST(root='./data', train=False, transform=transform)
# 定义参数
lr = 0.01
momentum = 0.5
batch_size = 128
epochs = 10
# 加载数据
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=lr, momentum=momentum)
# 训练模型
for epoch in range(1, epochs+1):
train_loss = 0.0
train_correct = 0
model.train()
for data, target in train_loader:
optimizer.zero_grad()
output = model(data)
loss = criterion(output, target)
loss.backward()
optimizer.step()
train_loss += loss.item() * data.size(0)
_, preds = torch.max(output, 1)
train_correct += torch.sum(preds == target.data)
train_loss = train_loss / len(train_loader.dataset)
train_acc = train_correct.double() / len(train_loader.dataset)
print('Epoch: {} \tTraining Loss: {:.6f} \tTraining Accuracy: {:.6f}'.format(epoch, train_loss, train_acc))
# 测试模型
with torch.no_grad():
test_loss = 0.0
test_correct = 0
model.eval()
for data, target in test_loader:
output = model(data)
loss = criterion(output, target)
test_loss += loss.item() * data.size(0)
_, preds = torch.max(output, 1)
test_correct += torch.sum(preds == target.data)
test_loss = test_loss / len(test_loader.dataset)
test_acc = test_correct.double() / len(test_loader.dataset)
print('Test Loss: {:.6f} \tTest Accuracy: {:.6f}'.format(test_loss, test_acc))
```
注:由于MNIST数据集是一个手写数字识别数据集,与AlexNet网络模型设计不符,因此训练的精度可能不是很高。
阅读全文