基于pytorch迁移学习resnet50完整代码
时间: 2023-07-17 09:07:05 浏览: 167
当使用PyTorch进行迁移学习时,可以使用预训练的ResNet-50模型作为基础模型,并在其基础上进行微调。以下是一个基于PyTorch的完整代码示例:
```python
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import models, transforms, datasets
# 设置随机种子,保证实验可复现性
torch.manual_seed(123)
# 数据预处理和加载
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])
])
}
data_dir = 'path/to/your/dataset' # 设置数据集的路径
image_datasets = {x: datasets.ImageFolder(f'{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) for x in ['train', 'val']}
dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'val']}
class_names = image_datasets['train'].classes
# 加载预训练模型
model = models.resnet50(pretrained=True)
num_ftrs = model.fc.in_features
model.fc = nn.Linear(num_ftrs, len(class_names)) # 替换最后一层全连接层
# 定义损失函数和优化器
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 = model.to(device)
criterion = criterion.to(device)
num_epochs = 10
best_acc = 0.0
for epoch in range(num_epochs):
for phase in ['train', 'val']:
if phase == 'train':
model.train()
else:
model.eval()
running_loss = 0.0
running_corrects = 0
for inputs, labels in dataloaders[phase]:
inputs = inputs.to(device)
labels = labels.to(device)
optimizer.zero_grad()
with torch.set_grad_enabled(phase == 'train'):
outputs = model(inputs)
_, preds = torch.max(outputs, 1)
loss = criterion(outputs, labels)
if phase == 'train':
loss.backward()
optimizer.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(f'{phase} Loss: {epoch_loss:.4f} Acc: {epoch_acc:.4f}')
if phase == 'val' and epoch_acc > best_acc:
best_acc = epoch_acc
# 在测试集上评估模型
model.eval()
test_dataset = datasets.ImageFolder(f'{data_dir}/test', data_transforms['val'])
test_dataloader = torch.utils.data.DataLoader(test_dataset, batch_size=32, shuffle=False)
test_corrects = 0
for inputs, labels in test_dataloader:
inputs = inputs.to(device)
labels = labels.to(device)
with torch.set_grad_enabled(False):
outputs = model(inputs)
_, preds = torch.max(outputs, 1)
test_corrects += torch.sum(preds == labels.data)
test_acc = test_corrects.double() / len(test_dataset)
print(f'Test Accuracy: {test_acc:.4f}')
```
请注意,上述代码中的数据集路径、训练轮数、优化器参数等需要根据您的具体情况进行适当修改。此代码将在训练集上微调预训练的ResNet-50模型,并在验证集和测试集上评估性能。
阅读全文