resnet18实现cifar10分类
时间: 2023-08-20 15:07:43 浏览: 112
下面是一个使用ResNet-18模型实现CIFAR-10分类的示例代码:
```python
import torch
import torchvision
import torchvision.transforms as transforms
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
# 数据预处理
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 = DataLoader(trainset, batch_size=128, shuffle=True, num_workers=2)
testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform_test)
testloader = DataLoader(testset, batch_size=100, shuffle=False, num_workers=2)
# 定义ResNet-18模型
class ResNet(nn.Module):
def __init__(self):
super(ResNet, self).__init__()
self.resnet18 = torchvision.models.resnet18(pretrained=False)
self.fc = nn.Linear(1000, 10) # CIFAR-10有10个类别
def forward(self, x):
x = self.resnet18(x)
x = self.fc(x)
return x
model = ResNet()
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
# 训练模型
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
for epoch in range(10):
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
inputs, labels = data
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if i % 200 == 199:
print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 200))
running_loss = 0.0
print('Finished Training')
# 在测试集上评估模型
correct = 0
total = 0
with torch.no_grad():
for data in testloader:
images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy on the test images: %d %%' % (100 * correct / total))
```
这段代码使用了PyTorch框架,首先定义了数据预处理的方式,然后使用`torchvision.datasets.CIFAR10`加载CIFAR-10数据集,并使用`torch.utils.data.DataLoader`创建数据加载器。接着定义了一个基于ResNet-18的模型,包含一个全连接层用于分类。然后定义了损失函数和优化器。最后,使用训练数据对模型进行训练,并在测试集上评估模型的准确率。
阅读全文