Pytorch迁移学习代码实战
时间: 2023-12-08 17:03:20 浏览: 108
学习pytorch练习代码
迁移学习是在一个领域中训练的深度学习模型在另一个领域中重复使用的技术。在Pytorch中,迁移学习可以通过使用预训练模型和微调来实现。以下是一个基本的迁移学习代码实战:
首先,导入必要的库:
```python
import torch
import torchvision
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, models, transforms
```
接下来,定义数据路径和数据扩充:
```python
data_dir = "./data" # 数据路径
# 数据扩充及归一化
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])
]),
}
```
然后,加载数据:
```python
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=4, 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
```
接下来,定义预训练模型:
```python
model_ft = models.resnet18(pretrained=True)
num_ftrs = model_ft.fc.in_features
model_ft.fc = nn.Linear(num_ftrs, 2)
```
然后,定义损失函数和优化器:
```python
criterion = nn.CrossEntropyLoss()
optimizer_ft = optim.SGD(model_ft.parameters(), lr=0.001, momentum=0.9)
```
接着,定义训练函数:
```python
def train_model(model, criterion, optimizer, num_epochs=25):
for epoch in range(num_epochs):
print('Epoch {}/{}'.format(epoch, num_epochs - 1))
print('-' * 10)
# 每个epoch都有训练和验证阶段
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('{} Loss: {:.4f} Acc: {:.4f}'.format(phase, epoch_loss, epoch_acc))
return model
```
最后,训练模型并保存:
```python
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model_ft = model_ft.to(device)
model_ft = train_model(model_ft, criterion, optimizer_ft, num_epochs=25)
torch.save(model_ft.state_dict(), './model_ft.pth')
```
以上就是一个基本的Pytorch迁移学习代码实战。其中,我们使用resnet18作为预训练模型,在两个类别的图像数据集上微调模型。你可以根据自己的需求修改代码并尝试不同的预训练模型。
阅读全文