可以帮我写一份resnet的迁移学习代码吗
时间: 2023-06-24 11:07:26 浏览: 119
当然可以,以下是一个使用ResNet50进行迁移学习的PyTorch代码示例:
```python
import torch
import torch.nn as nn
import torchvision
from torchvision import datasets, models, transforms
# 设置训练和验证数据的路径
data_dir = 'path/to/data'
train_dir = data_dir + '/train'
val_dir = data_dir + '/val'
# 预处理数据
# 训练集图片随机裁剪到224x224大小,进行数据扩增
# 验证集图片按比例缩放到256x256大小,中心裁剪到224x224大小
data_transforms = {
'train': transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
'val': transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
}
# 加载数据
# 使用ImageFolder读取目录下的图片,并把图片路径作为label
image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms[x])
for x in ['train', 'val']}
dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=32,
shuffle=True, num_workers=4)
for x in ['train', 'val']}
dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'val']}
class_names = image_datasets['train'].classes
# 加载预训练的ResNet50模型
model_ft = models.resnet50(pretrained=True)
# 替换最后一层全连接层,输出为我们需要的分类数
num_ftrs = model_ft.fc.in_features
model_ft.fc = nn.Linear(num_ftrs, 2)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer_ft = torch.optim.SGD(model_ft.parameters(), lr=0.001, momentum=0.9)
# 在GPU上训练模型
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model_ft = model_ft.to(device)
# 训练模型
# 只训练最后一层全连接层,不更新ResNet50的参数
# 在验证集上测试模型
# 训练5个epoch
num_epochs = 5
for epoch in range(num_epochs):
for phase in ['train', 'val']:
if phase == 'train':
model_ft.train() # 训练模式
else:
model_ft.eval() # 推理模式
running_loss = 0.0
running_corrects = 0
for inputs, labels in dataloaders[phase]:
inputs = inputs.to(device)
labels = labels.to(device)
optimizer_ft.zero_grad()
with torch.set_grad_enabled(phase == 'train'):
outputs = model_ft(inputs)
_, preds = torch.max(outputs, 1)
loss = criterion(outputs, labels)
if phase == 'train':
loss.backward()
optimizer_ft.step()
running_loss += loss.item() * inputs.size(0)
running_corrects += torch.sum(preds == labels.data)
epoch_loss = running_loss / dataset_sizes[phase]
epoch_acc = running_corrects.double() / dataset_sizes[phase]
print('{} Loss: {:.4f} Acc: {:.4f}'.format(phase, epoch_loss, epoch_acc))
```
这个代码示例中,我们首先使用`torchvision`库中的`transforms`对训练和验证集的数据进行预处理,然后使用`datasets.ImageFolder`读取目录下的图片,并把图片路径作为label。接着我们加载预训练的ResNet50模型,并替换最后一层全连接层输出为二分类。然后定义损失函数和优化器,在GPU上训练模型。我们只训练最后一层全连接层,不更新ResNet50的参数。在每个epoch中,在训练集上训练模型,在验证集上测试模型。最后训练5个epoch。
阅读全文