Model Finetune
Transfer Learning:机器学习分支,研究源域的只是如何应用到目标域
模型微调
首先要加载模型参数
resnet18_ft = models.resnet18()
path_pretrained_model = os.path.join(BASEDIR, "resnet18-5c106cde.pth")
state_dict_load = torch.load(path_pretrained_model)
resnet18_ft.load_state_dict(state_dict_load)
在加载了模型参数之后,需要替换期中的全连接层为我们当前项目的需求
#我们替换resnet18最后的全连接层
num_ftrs = resnet18_ft.fc.in_features
resnet18_ft.fc = nn.Linear(num_ftrs, classes)
两种微调方法
#微调方法1
for param in resnet18_ft.parameters():
param.requires_grad = False
print("conv1.weights[0, 0, ...]:\n {}".format(resnet18_ft.conv1.weight[0, 0, ...]))
#微调方法2
fc_params_id = list(map(id, resnet18_ft.fc.parameters())) # 返回的是parameters的 内存地址
base_params = filter(lambda p: id(p) not in fc_params_id, resnet18_ft.parameters())
optimizer = optim.SGD([
{'params': base_params, 'lr': LR*0}, # 0
{'params': resnet18_ft.fc.parameters(), 'lr': LR}], momentum=0.9)
device选择的方法
torch.device('cuda' if torch.cude.is_available() else "cpu")