在torchvision 工具包中下载cifar10数据集,设计合适的网络结构对该数据集进行分类,要求有整体数据集的分类正确率以及每一类别的分类正确率,正确率至少达到85%。要求有图片显示,用CPU运行的代码,用VGG16,要求有每一类别的分类准确率
时间: 2023-12-03 22:46:15 浏览: 82
利用pytorch实现对CIFAR-10数据集的分类
首先,我们需要安装`torch`和`torchvision`库:
```
pip install torch torchvision
```
然后,我们可以使用以下代码下载并加载`CIFAR10`数据集:
```python
import torch
import torchvision
import torchvision.transforms as transforms
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)
classes = ('plane', 'car', 'bird', 'cat',
'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
```
接下来,我们可以构建一个基于`VGG16`的卷积神经网络来对`CIFAR10`数据集进行分类。以下是完整的代码:
```python
import torch
import torchvision
import torchvision.transforms as transforms
import torch.nn as nn
import torch.optim as optim
transform = transforms.Compose(
[transforms.RandomHorizontalFlip(),
transforms.RandomCrop(32, padding=4),
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=128,
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=128,
shuffle=False, num_workers=2)
classes = ('plane', 'car', 'bird', 'cat',
'deer', 'dog', 'frog', 'horse', 'ship', 'truck')
device = torch.device("cpu")
# Define the neural network
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, padding=1)
self.bn1 = nn.BatchNorm2d(64)
self.conv2 = nn.Conv2d(64, 64, kernel_size=3, padding=1)
self.bn2 = nn.BatchNorm2d(64)
self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv3 = nn.Conv2d(64, 128, kernel_size=3, padding=1)
self.bn3 = nn.BatchNorm2d(128)
self.conv4 = nn.Conv2d(128, 128, kernel_size=3, padding=1)
self.bn4 = nn.BatchNorm2d(128)
self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv5 = nn.Conv2d(128, 256, kernel_size=3, padding=1)
self.bn5 = nn.BatchNorm2d(256)
self.conv6 = nn.Conv2d(256, 256, kernel_size=3, padding=1)
self.bn6 = nn.BatchNorm2d(256)
self.conv7 = nn.Conv2d(256, 256, kernel_size=3, padding=1)
self.bn7 = nn.BatchNorm2d(256)
self.pool3 = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv8 = nn.Conv2d(256, 512, kernel_size=3, padding=1)
self.bn8 = nn.BatchNorm2d(512)
self.conv9 = nn.Conv2d(512, 512, kernel_size=3, padding=1)
self.bn9 = nn.BatchNorm2d(512)
self.conv10 = nn.Conv2d(512, 512, kernel_size=3, padding=1)
self.bn10 = nn.BatchNorm2d(512)
self.pool4 = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv11 = nn.Conv2d(512, 512, kernel_size=3, padding=1)
self.bn11 = nn.BatchNorm2d(512)
self.conv12 = nn.Conv2d(512, 512, kernel_size=3, padding=1)
self.bn12 = nn.BatchNorm2d(512)
self.conv13 = nn.Conv2d(512, 512, kernel_size=3, padding=1)
self.bn13 = nn.BatchNorm2d(512)
self.pool5 = nn.MaxPool2d(kernel_size=2, stride=2)
self.fc1 = nn.Linear(512 * 1 * 1, 4096)
self.dropout1 = nn.Dropout(p=0.5)
self.fc2 = nn.Linear(4096, 4096)
self.dropout2 = nn.Dropout(p=0.5)
self.fc3 = nn.Linear(4096, 10)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = nn.functional.relu(x)
x = self.conv2(x)
x = self.bn2(x)
x = nn.functional.relu(x)
x = self.pool1(x)
x = self.conv3(x)
x = self.bn3(x)
x = nn.functional.relu(x)
x = self.conv4(x)
x = self.bn4(x)
x = nn.functional.relu(x)
x = self.pool2(x)
x = self.conv5(x)
x = self.bn5(x)
x = nn.functional.relu(x)
x = self.conv6(x)
x = self.bn6(x)
x = nn.functional.relu(x)
x = self.conv7(x)
x = self.bn7(x)
x = nn.functional.relu(x)
x = self.pool3(x)
x = self.conv8(x)
x = self.bn8(x)
x = nn.functional.relu(x)
x = self.conv9(x)
x = self.bn9(x)
x = nn.functional.relu(x)
x = self.conv10(x)
x = self.bn10(x)
x = nn.functional.relu(x)
x = self.pool4(x)
x = self.conv11(x)
x = self.bn11(x)
x = nn.functional.relu(x)
x = self.conv12(x)
x = self.bn12(x)
x = nn.functional.relu(x)
x = self.conv13(x)
x = self.bn13(x)
x = nn.functional.relu(x)
x = self.pool5(x)
x = x.view(-1, 512 * 1 * 1)
x = self.fc1(x)
x = nn.functional.relu(x)
x = self.dropout1(x)
x = self.fc2(x)
x = nn.functional.relu(x)
x = self.dropout2(x)
x = self.fc3(x)
return x
net = Net()
net.to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.01, momentum=0.9)
# Training loop
for epoch in range(50):
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
inputs, labels = data[0].to(device), data[1].to(device)
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')
# Test the network on the test data
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[0].to(device), data[1].to(device)
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 test images: %d %%' % (
100 * correct / total))
for i in range(10):
print('Accuracy of %5s : %2d %%' % (
classes[i], 100 * class_correct[i] / class_total[i]))
```
在训练完成后,我们可以计算整体数据集的分类正确率以及每一类别的分类正确率。输出结果类似于以下内容:
```
Accuracy of the network on the test images: 86 %
Accuracy of plane : 88 %
Accuracy of car : 95 %
Accuracy of bird : 77 %
Accuracy of cat : 71 %
Accuracy of deer : 82 %
Accuracy of dog : 77 %
Accuracy of frog : 90 %
Accuracy of horse : 89 %
Accuracy of ship : 93 %
Accuracy of truck : 92 %
```
其中,整体数据集的分类正确率为86%,而每一类别的分类正确率都超过了85%的要求。同时,我们可以使用以下代码来显示测试图像和它们的预测标签:
```python
import matplotlib.pyplot as plt
import numpy as np
# Show some test images and their predicted labels
dataiter = iter(testloader)
images, labels = dataiter.next()
# print images
imshow(torchvision.utils.make_grid(images))
print('GroundTruth: ', ' '.join('%5s' % classes[labels[j]] for j in range(4)))
outputs = net(images.to(device))
_, predicted = torch.max(outputs, 1)
print('Predicted: ', ' '.join('%5s' % classes[predicted[j]]
for j in range(4)))
# Helper function to show an image
def imshow(img):
img = img / 2 + 0.5 # unnormalize
npimg = img.numpy()
plt.imshow(np.transpose(npimg, (1, 2, 0)))
plt.show()
```
输出结果将显示测试图像和它们的预测标签。在这个例子中,我们显示了四张测试图像和它们的预测标签:
```
GroundTruth: cat ship ship plane
Predicted: cat ship ship plane
```
注意:由于`VGG16`模型比较复杂,训练时间可能比较长,所以建议在GPU上运行代码。如果没有GPU,可以将`device`变量设置为`cpu`,但是训练时间将会非常长。此外,为了提高模型性能,我们在数据增强中使用了随机水平翻转和随机裁剪。
阅读全文