以下是一个基于 PyTorch 框架的卷积神经网络模型,用于预测 CIFAR-100 数据集中的图片类别。
首先,我们需要导入所需的库。
```python
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
```
接下来,我们可以定义 CIFAR-100 数据集的变换和加载器。
```python
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.CIFAR100(root='./data', train=True, download=True, transform=transform_train)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=128, shuffle=True, num_workers=2)
testset = torchvision.datasets.CIFAR100(root='./data', train=False, download=True, transform=transform_test)
testloader = torch.utils.data.DataLoader(testset, batch_size=128, shuffle=False, num_workers=2)
```
接下来,我们可以定义一个基于卷积神经网络的模型。
```python
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 64, 3, padding=1)
self.conv2 = nn.Conv2d(64, 64, 3, padding=1)
self.pool1 = nn.MaxPool2d(2, 2)
self.conv3 = nn.Conv2d(64, 128, 3, padding=1)
self.conv4 = nn.Conv2d(128, 128, 3, padding=1)
self.pool2 = nn.MaxPool2d(2, 2)
self.conv5 = nn.Conv2d(128, 256, 3, padding=1)
self.conv6 = nn.Conv2d(256, 256, 3, padding=1)
self.conv7 = nn.Conv2d(256, 256, 3, padding=1)
self.pool3 = nn.MaxPool2d(2, 2)
self.conv8 = nn.Conv2d(256, 512, 3, padding=1)
self.conv9 = nn.Conv2d(512, 512, 3, padding=1)
self.conv10 = nn.Conv2d(512, 512, 3, padding=1)
self.pool4 = nn.MaxPool2d(2, 2)
self.conv11 = nn.Conv2d(512, 512, 3, padding=1)
self.conv12 = nn.Conv2d(512, 512, 3, padding=1)
self.conv13 = nn.Conv2d(512, 512, 3, padding=1)
self.pool5 = nn.MaxPool2d(2, 2)
self.fc1 = nn.Linear(512 * 1 * 1, 4096)
self.fc2 = nn.Linear(4096, 4096)
self.fc3 = nn.Linear(4096, 100)
def forward(self, x):
x = nn.functional.relu(self.conv1(x))
x = nn.functional.relu(self.conv2(x))
x = self.pool1(x)
x = nn.functional.relu(self.conv3(x))
x = nn.functional.relu(self.conv4(x))
x = self.pool2(x)
x = nn.functional.relu(self.conv5(x))
x = nn.functional.relu(self.conv6(x))
x = nn.functional.relu(self.conv7(x))
x = self.pool3(x)
x = nn.functional.relu(self.conv8(x))
x = nn.functional.relu(self.conv9(x))
x = nn.functional.relu(self.conv10(x))
x = self.pool4(x)
x = nn.functional.relu(self.conv11(x))
x = nn.functional.relu(self.conv12(x))
x = nn.functional.relu(self.conv13(x))
x = self.pool5(x)
x = x.view(-1, 512 * 1 * 1)
x = nn.functional.relu(self.fc1(x))
x = nn.functional.dropout(x, training=self.training)
x = nn.functional.relu(self.fc2(x))
x = nn.functional.dropout(x, training=self.training)
x = self.fc3(x)
return x
```
接下来,我们可以实例化模型和优化器,并定义损失函数。
```python
net = Net()
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.1, momentum=0.9, weight_decay=1e-4)
```
最后,我们可以训练模型并在测试集上进行测试。
```python
for epoch in range(200):
net.train()
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()
print('[%d] training loss: %.3f' % (epoch + 1, running_loss / len(trainloader)))
net.eval()
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('[%d] testing accuracy: %.3f' % (epoch + 1, 100 * correct / total))
```
这样,我们就创建了一个基于卷积神经网络的模型,用于预测 CIFAR-100 数据集中的图片类别。