基于 resnet 对 CIFAR-10 图片进行分类,要求准确度达到85以上,并输出分类图像结果
时间: 2023-12-03 14:46:08 浏览: 115
CIFAR-10的图片分类
好的,这里是一个基于ResNet的CIFAR-10分类器的代码,可以使用PyTorch实现:
```
import torch
import torchvision
import torchvision.transforms as transforms
import torch.nn as nn
import torch.optim as optim
import matplotlib.pyplot as plt
# 定义数据预处理方式
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))
])
# 加载CIFAR-10数据集
trainset = torchvision.datasets.CIFAR10(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.CIFAR10(root='./data', train=False,
download=True, transform=transform_test)
testloader = torch.utils.data.DataLoader(testset, batch_size=100,
shuffle=False, num_workers=2)
# 定义ResNet模型
class ResidualBlock(nn.Module):
def __init__(self, in_channels, out_channels, stride=1):
super(ResidualBlock, self).__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(out_channels)
self.relu = nn.ReLU(inplace=True)
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(out_channels)
self.stride = stride
if stride != 1 or in_channels != out_channels:
self.shortcut = nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(out_channels)
)
else:
self.shortcut = nn.Sequential()
def forward(self, x):
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out += self.shortcut(x)
out = self.relu(out)
return out
class ResNet(nn.Module):
def __init__(self, block, num_blocks, num_classes=10):
super(ResNet, self).__init__()
self.in_channels = 64
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
self.layer1 = self.make_layer(block, 64, num_blocks[0], stride=1)
self.layer2 = self.make_layer(block, 128, num_blocks[1], stride=2)
self.layer3 = self.make_layer(block, 256, num_blocks[2], stride=2)
self.layer4 = self.make_layer(block, 512, num_blocks[3], stride=2)
self.avg_pool = nn.AvgPool2d(4)
self.fc = nn.Linear(512, num_classes)
def make_layer(self, block, out_channels, num_blocks, stride):
strides = [stride] + [1] * (num_blocks - 1)
layers = []
for stride in strides:
layers.append(block(self.in_channels, out_channels, stride))
self.in_channels = out_channels
return nn.Sequential(*layers)
def forward(self, x):
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.layer1(out)
out = self.layer2(out)
out = self.layer3(out)
out = self.layer4(out)
out = self.avg_pool(out)
out = out.view(out.size(0), -1)
out = self.fc(out)
return out
net = ResNet(ResidualBlock, [2, 2, 2, 2])
device = 'cuda' if torch.cuda.is_available() else 'cpu'
net.to(device)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.1, momentum=0.9, weight_decay=5e-4)
# 训练模型
def train(net, trainloader, criterion, optimizer):
net.train()
train_loss = 0
correct = 0
total = 0
for i, data in enumerate(trainloader, 0):
inputs, labels = data
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
train_loss += loss.item()
_, predicted = outputs.max(1)
total += labels.size(0)
correct += predicted.eq(labels).sum().item()
return train_loss/(i+1), 100.*correct/total
# 测试模型
def test(net, testloader, criterion):
net.eval()
test_loss = 0
correct = 0
total = 0
with torch.no_grad():
for data in testloader:
images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = net(images)
loss = criterion(outputs, labels)
test_loss += loss.item()
_, predicted = outputs.max(1)
total += labels.size(0)
correct += predicted.eq(labels).sum().item()
return test_loss/(len(testloader)), 100.*correct/total
# 训练模型并输出分类结果
num_epochs = 200
train_losses, test_losses, train_accs, test_accs = [], [], [], []
for epoch in range(num_epochs):
train_loss, train_acc = train(net, trainloader, criterion, optimizer)
test_loss, test_acc = test(net, testloader, criterion)
train_losses.append(train_loss)
test_losses.append(test_loss)
train_accs.append(train_acc)
test_accs.append(test_acc)
print('Epoch [{}/{}], Train Loss: {:.4f}, Train Acc: {:.2f}%, Test Loss: {:.4f}, Test Acc: {:.2f}%'
.format(epoch+1, num_epochs, train_loss, train_acc, test_loss, test_acc))
# 保存准确度达到85%以上的模型
if test_acc >= 85:
torch.save(net.state_dict(), 'resnet_cifar10.pth')
print('Model saved!')
# 输出分类结果
net.eval()
images, labels = iter(testloader).next()
images, labels = images.to(device), labels.to(device)
outputs = net(images)
_, predicted = torch.max(outputs, 1)
# 显示分类结果
fig = plt.figure(figsize=(10, 10))
for i in range(100):
ax = fig.add_subplot(10, 10, i+1, xticks=[], yticks=[])
ax.imshow(images.cpu().numpy()[i].transpose((1, 2, 0)))
ax.set_title(predicted.cpu().numpy()[i])
plt.show()
```
这个代码实现了一个ResNet模型,可以对CIFAR-10数据集进行图像分类。在训练过程中,每个epoch会输出训练损失、训练准确率、测试损失和测试准确率。在准确率达到85%以上时,会自动保存模型参数到文件`resnet_cifar10.pth`中。训练结束后,还会输出一个100张测试图像的分类结果。
阅读全文