基于alexnet cifar-10 pytorch
时间: 2023-07-04 19:14:10 浏览: 123
好的,我来为您介绍如何在PyTorch中使用AlexNet对CIFAR-10数据集进行训练。以下是基于PyTorch的代码示例:
首先,我们需要加载CIFAR-10数据集。PyTorch提供了内置的方法来加载和预处理数据集:
```python
import torch
import torchvision
import torchvision.transforms as transforms
# 定义数据预处理
transform = transforms.Compose(
[transforms.Resize((227, 227)),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
# 加载CIFAR-10数据集
trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64,
shuffle=True, num_workers=2)
testset = torchvision.datasets.CIFAR10(root='./data', train=False,
download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=64,
shuffle=False, num_workers=2)
```
接下来,我们需要定义AlexNet模型并进行微调。在这里,我们将最后一层的输出从1000个类别更改为10个类别,以适应CIFAR-10数据集的分类任务:
```python
import torch.nn as nn
import torch.optim as optim
from torchvision.models import alexnet
# 加载预训练的AlexNet模型
model = alexnet(pretrained=True)
# 将最后一层的输出从1000个类别更改为10个类别
num_features = model.classifier[6].in_features
model.classifier[6] = nn.Linear(num_features, 10)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
```
最后,我们可以使用反向传播算法和随机梯度下降算法来训练这个模型:
```python
# 训练模型
for epoch in range(10): # 遍历数据集10次
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
# 获取输入并将其送入模型中
inputs, labels = data
optimizer.zero_grad()
outputs = model(inputs)
# 计算损失并执行反向传播
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# 打印统计信息
running_loss += loss.item()
if i % 200 == 199: # 每200个batch打印一次
print('[%d, %5d] loss: %.3f' %
(epoch + 1, i + 1, running_loss / 200))
running_loss = 0.0
print('Finished Training')
```
最后,我们可以使用测试集来测试训练出的模型的性能:
```python
# 在测试集上测试模型
correct = 0
total = 0
with torch.no_grad():
for data in testloader:
images, labels = data
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: %d %%' % (
100 * correct / total))
```
希望这能对您有所帮助!
阅读全文