实验内容与步骤 (1) 加载及预处理CIFAR-10图像数据。 (2) 构建基于CNN的CIFAR-10分类网络。 (3) 编译基于CNN的CIFAR-10分类网络。 (4) 训练基于CNN的CIFAR-10分类网络。 (5) 评估基于CNN的CIFAR-10分类模型性能。
时间: 2024-10-16 13:04:44 浏览: 72
Tensorflow之CNN实现CIFAR-10图像的分类python
实验内容与步骤如下:
1. **加载及预处理CIFAR-10图像数据**:
- 使用如`torchvision.datasets`库加载CIFAR-10数据集,指定数据目录、是否下载和数据变换(例如归一化、随机裁剪和翻转):
```python
from torchvision import datasets, transforms
transform_train = transforms.Compose([transforms.RandomHorizontalFlip(), transforms.RandomCrop(32, padding=4), transforms.ToTensor(), transforms.Normalize(mean=[0.4914, 0.4822, 0.4465], std=[0.2023, 0.1994, 0.2010])])
transform_test = transforms.Compose([transforms.ToTensor(), transforms.Normalize(mean=[0.4914, 0.4822, 0.4465], std=[0.2023, 0.1994, 0.2010])])
train_dataset = datasets.CIFAR10(root='./data', train=True, download=True, transform=transform_train)
test_dataset = datasets.CIFAR10(root='./data', train=False, download=True, transform=transform_test)
```
2. **构建基于CNN的CIFAR-10分类网络**:
- 例如,可以使用Keras或PyTorch中的预定义模型,如LeNet、ResNet、VGG等,或者自定义一个网络结构:
```python
from torchvision.models import resnet18
net = resnet18(pretrained=True)
num_classes = 10
net.fc = nn.Linear(net.fc.in_features, num_classes)
```
3. **编译基于CNN的CIFAR-10分类网络**:
- 设置损失函数(如交叉熵)、优化器和可能的额外配置(如学习率调度):
```python
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.AdamW(net.parameters(), lr=0.001)
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.1)
```
4. **训练基于CNN的CIFAR-10分类网络**:
- 进行若干轮迭代,每次迭代包含前向传播、计算损失、反向传播和更新权重:
```python
epochs = 20
for epoch in range(epochs):
train_loss, train_acc = train_fn(net, train_loader, criterion, optimizer, device)
val_loss, val_acc = validate_fn(net, test_loader, criterion, device)
scheduler.step()
```
5. **评估基于CNN的CIFAR-10分类模型性能**:
- 计算测试集的精度或者其他性能指标,如混淆矩阵或精确度、召回率等:
```python
def evaluate_model(net, dataloader, criterion, device):
net.eval()
running_loss = 0.0
running_corrects = 0
with torch.no_grad():
for inputs, labels in dataloader:
inputs = inputs.to(device)
labels = labels.to(device)
outputs = net(inputs)
loss = criterion(outputs, labels)
_, preds = torch.max(outputs, 1)
running_loss += loss.item() * inputs.size(0)
running_corrects += torch.sum(preds == labels.data)
return running_loss / len(dataloader.dataset), running_corrects.double() / len(dataloader.dataset)
test_loss, test_acc = evaluate_model(net, test_loader, criterion, device)
print(f"Test Loss: {test_loss:.4f}, Test Acc: {test_acc*100:.2f}%")
```
阅读全文