用pytorch写一个迁移学习代码
时间: 2023-04-12 22:01:05 浏览: 146
好的,以下是一个用 PyTorch 实现的迁移学习代码示例:
```python
import torch
import torch.nn as nn
import torchvision.models as models
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
from torch.optim import Adam
# 加载预训练的 ResNet50 模型
model = models.resnet50(pretrained=True)
# 冻结所有层的参数
for param in model.parameters():
param.requires_grad = False
# 替换最后一层全连接层
num_features = model.fc.in_features
model.fc = nn.Linear(num_features, 10)
# 定义数据增强和预处理的转换
transform = transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
# 加载数据集
train_dataset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = Adam(model.fc.parameters(), lr=0.001)
# 训练模型
for epoch in range(10):
for i, (images, labels) in enumerate(train_loader):
optimizer.zero_grad()
outputs = model(images)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
if (i+1) % 100 == 0:
print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'.format(epoch+1, 10, i+1, len(train_loader), loss.item()))
```
希望这个示例能够帮助你理解如何用 PyTorch 实现迁移学习。
阅读全文