堆叠层数越多,效果越差
网络搭建过程中将一系列的残差结构进行堆叠,残差结构越多,节省的参数也越多
使用别人预训练模型参数时,要注意别人的预处理方式
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import models, transforms, datasets
# 定义目标任务的数据加载和预处理
data_transforms = {
'train': transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
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_data' # 指定目标任务的数据目录
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']}
# 加载预训练模型,如ResNet
model = models.resnet18(pretrained=True)
# 冻结预训练模型的参数
for param in model.parameters():
param.requires_grad = False
# 替换模型的最后一层,以适应目标任务的类别数量
num_ftrs = model.fc.in_features
model.fc = nn.Linear(num_ftrs, num_classes)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.fc.parameters(), lr=0.001, momentum=0.9)
# 训练模型
def train_model(model, criterion, optimizer, num_epochs=25):
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('{} Loss: {:.4f} Acc: {:.4f}'.format(phase, epoch_loss, epoch_acc))
# 训练模型
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model = model.to(device)
train_model(model, criterion, optimizer, num_epochs=25)
在这个示例中,我们使用了预训练的ResNet模型,微调了最后一层以适应目标任务的类别数量,并定义了数据加载、损失函数和优化器。你需要根据自己的任务和数据集进行相应的修改。确保数据加载和处理、模型选择和微调都符合你的特定需求