假设你是一个pytorch,请写出一个pretrain=true、class=10的resnet50的代码,训练cifar10数据集
时间: 2024-03-01 16:55:52 浏览: 69
好的,以下是一个PyTorch中pretrain=true、class=10的ResNet50的代码,用于训练CIFAR10数据集。
```python
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
# 定义transform
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.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=128,
shuffle=False, num_workers=2)
# 定义ResNet50
class ResNet50(nn.Module):
def __init__(self, num_classes=10):
super(ResNet50, self).__init__()
self.resnet50 = torchvision.models.resnet50(pretrained=True)
num_ftrs = self.resnet50.fc.in_features
self.resnet50.fc = nn.Linear(num_ftrs, num_classes)
def forward(self, x):
x = self.resnet50(x)
return x
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
net = ResNet50().to(device)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.1, momentum=0.9, weight_decay=5e-4)
# 训练模型
for epoch in range(100): # 训练100个epoch
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 = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if i % 100 == 99: # 每100个batch输出一次损失值
print('[%d, %5d] loss: %.3f' %
(epoch + 1, i + 1, running_loss / 100))
running_loss = 0.0
print('Finished Training')
# 保存模型
PATH = './cifar_net.pth'
torch.save(net.state_dict(), PATH)
```
需要说明的是,这段代码中使用了预训练的ResNet50模型,该模型在ImageNet数据集上进行了预训练,因此具有较好的特征提取能力。在训练CIFAR10数据集时,只需对ResNet50的最后一层进行修改,使其输出10个类别的概率即可。
阅读全文