基于pytorch对cifar 10分类,要求准确度达到85以上,并输出分类图像结果
时间: 2023-07-19 13:04:04 浏览: 180
好的,首先需要准备CIFAR-10数据集,可以使用PyTorch内置的`torchvision.datasets.CIFAR10`来进行下载和加载数据集。然后,我们可以使用卷积神经网络来对图像进行分类。下面是一个简单的代码示例:
```python
import torch
import torchvision
import torchvision.transforms as transforms
import torch.nn as nn
import torch.optim as optim
# 超参数
batch_size = 128
learning_rate = 0.001
num_epochs = 20
# 数据预处理
transform_train = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
transform_test = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
# 加载数据集
trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform_train)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=2)
testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform_test)
testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size, shuffle=False, num_workers=2)
# 定义模型
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 32, 3, padding=1)
self.conv2 = nn.Conv2d(32, 64, 3, padding=1)
self.conv3 = nn.Conv2d(64, 128, 3, padding=1)
self.pool = nn.MaxPool2d(2, 2)
self.fc1 = nn.Linear(128 * 4 * 4, 512)
self.fc2 = nn.Linear(512, 10)
def forward(self, x):
x = self.pool(nn.functional.relu(self.conv1(x)))
x = self.pool(nn.functional.relu(self.conv2(x)))
x = self.pool(nn.functional.relu(self.conv3(x)))
x = x.view(-1, 128 * 4 * 4)
x = nn.functional.relu(self.fc1(x))
x = self.fc2(x)
return x
net = Net()
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(net.parameters(), lr=learning_rate)
# 训练模型
for epoch in range(num_epochs):
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
inputs, labels = data
optimizer.zero_grad()
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if i % 100 == 99:
print('[%d, %5d] loss: %.3f' % (epoch+1, i+1, running_loss/100))
running_loss = 0.0
print('Finished Training')
# 测试模型
correct = 0
total = 0
with torch.no_grad():
for data in testloader:
images, labels = data
outputs = net(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))
```
在训练完成后,我们可以使用以下代码来输出分类图像结果:
```python
import matplotlib.pyplot as plt
import numpy as np
# 获取测试集中的图片和标签
dataiter = iter(testloader)
images, labels = dataiter.next()
# 预测图片的标签
outputs = net(images)
_, predicted = torch.max(outputs, 1)
# 打印前25张图片及其预测标签
fig, axes = plt.subplots(nrows=5, ncols=5, figsize=(10,10))
fig.tight_layout()
for i, ax in enumerate(axes.flat):
ax.imshow(np.transpose(images[i], (1, 2, 0)))
ax.set_title("Predicted: {}".format(predicted[i]))
ax.axis('off')
plt.show()
```
这样就可以输出分类图像结果了。
阅读全文