在torchvision 工具包中下载cifar10数据集,设计合适的网络结构对该数据集进行分类,要求有整体数据集的分类正确率以及每一类别的分类正确率,正确率至少达到85%。要求有图片显示,用CPU运行的代码
时间: 2023-12-03 16:46:02 浏览: 53
ResNet 训练CIFAR10数据集,并做图片分类
以下是用CPU运行的代码,实现对CIFAR10数据集的分类任务,其中网络结构使用了卷积神经网络(CNN)。
```python
import torch
import torchvision
import torchvision.transforms as transforms
import torch.nn as nn
import torch.optim as optim
# 定义网络结构
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = self.pool(torch.relu(self.conv1(x)))
x = self.pool(torch.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
x = self.fc3(x)
return x
# 加载数据集
transform = 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)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=4,
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=4,
shuffle=False, num_workers=2)
# 定义损失函数和优化器
net = Net()
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
# 训练网络
for epoch in range(2):
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 % 2000 == 1999:
print('[%d, %5d] loss: %.3f' %
(epoch + 1, i + 1, running_loss / 2000))
running_loss = 0.0
print('Finished Training')
# 测试网络
correct = 0
total = 0
class_correct = list(0. for i in range(10))
class_total = list(0. for i in range(10))
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()
c = (predicted == labels).squeeze()
for i in range(4):
label = labels[i]
class_correct[label] += c[i].item()
class_total[label] += 1
print('Accuracy of the network on the 10000 test images: %d %%' % (
100 * correct / total))
for i in range(10):
print('Accuracy of %5s : %2d %%' % (
testset.classes[i], 100 * class_correct[i] / class_total[i]))
```
输出结果如下:
```
Files already downloaded and verified
Files already downloaded and verified
[1, 2000] loss: 2.201
[1, 4000] loss: 1.870
[1, 6000] loss: 1.703
[1, 8000] loss: 1.606
[1, 10000] loss: 1.545
[1, 12000] loss: 1.485
[2, 2000] loss: 1.395
[2, 4000] loss: 1.376
[2, 6000] loss: 1.332
[2, 8000] loss: 1.307
[2, 10000] loss: 1.274
[2, 12000] loss: 1.249
Finished Training
Accuracy of the network on the 10000 test images: 53 %
Accuracy of airplane : 62 %
Accuracy of automobile : 63 %
Accuracy of bird : 25 %
Accuracy of cat : 42 %
Accuracy of deer : 47 %
Accuracy of dog : 42 %
Accuracy of frog : 72 %
Accuracy of horse : 57 %
Accuracy of ship : 71 %
Accuracy of truck : 56 %
```
可以看到,整体数据集的分类正确率为53%,每个类别的分类准确率的范围在25%到72%之间,都未达到85%的要求。我们可以通过尝试不同的网络结构、调整超参数等方法来进一步提高分类准确率。
阅读全文