cifar10数据集分类
时间: 2025-01-01 09:33:53 浏览: 10
### 使用CIFAR-10数据集实现图像分类
#### 加载和准备数据集
为了使用 `torchvision.datasets.CIFAR10` 来加载 CIFAR-10 数据集,可以设置一些必要的参数来指定数据集的位置以及是否要下载它。通过传递布尔值给 `train` 参数可以选择加载训练集还是测试集[^1]。
```python
import torchvision.transforms as transforms
from torchvision import datasets
transform = transforms.Compose([
transforms.ToTensor(),
])
trainset = datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
testset = datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)
```
#### 创建DataLoader实例
创建 DataLoader 实例以便于批量读取数据,并且可以在迭代过程中应用随机打乱等操作。
```python
from torch.utils.data import DataLoader
batch_size = 64
train_loader = DataLoader(trainset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(testset, batch_size=batch_size, shuffle=False)
```
#### 定义网络结构
构建卷积神经网络(CNN)作为分类器模型。这里展示了一个简单的 CNN 架构例子:
```python
import torch.nn as nn
import torch.nn.functional as F
class SimpleCNN(nn.Module):
def __init__(self):
super(SimpleCNN, self).__init__()
self.conv1 = nn.Conv2d(in_channels=3, out_channels=6, kernel_size=5)
self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv2 = nn.Conv2d(in_channels=6, out_channels=16, kernel_size=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(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5) # Flatten tensor
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
net = SimpleCNN()
device = 'cuda' if torch.cuda.is_available() else 'cpu'
net.to(device)
```
#### 训练过程
编写循环来进行多次 epoch 的训练,在每次迭代中更新权重以最小化损失函数。
```python
import torch.optim as optim
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
for epoch in range(2): # Loop over the dataset multiple times
running_loss = 0.0
for i, data in enumerate(train_loader, 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 % 2000 == 1999: # Print every 2000 mini-batches
print(f'[Epoch {epoch + 1}, Batch {i + 1}] Loss: {running_loss / 2000:.3f}')
running_loss = 0.0
print('Finished Training')
```
#### 测试与评估性能
最后一步是对测试集执行预测,并计算每种类别的准确性。
```python
correct_predictions_per_class = list(0. for _ in range(10))
total_samples_per_class = list(0. for _ in range(10))
with torch.no_grad():
for data in test_loader:
images, labels = data[0].to(device), data[1].to(device)
outputs = net(images)
_, predicted_classes = torch.max(outputs, dim=1)
matches = (predicted_classes == labels).squeeze()
for idx in range(len(matches)):
label = labels[idx]
correct_predictions_per_class[label] += matches[idx].item()
total_samples_per_class[label] += 1
for cls_idx in range(10):
accuracy_percentage = 100 * correct_predictions_per_class[cls_idx] / total_samples_per_class[cls_idx]
print(f'Accuracy of class {cls_idx}: {accuracy_percentage}%')
```
阅读全文