1.场景一:直接训练了模型20次,发现loss还没有收敛,想要继续在20的基础上继续训练
处理方案:
target_model = target_net().to(device)checkpoint = torch.load('./xxx.pth')target_model.load_state_dict(checkpoint)
这样就把原来已经训练20次的xxx.pth模型重新加载了。
保存模型的方法:
targeted_model_file_name = './xxx.pth'torch.save(target_model.state_dict(), targeted_model_file_name)target_model.eval()
2.场景二:训练过程中,每迭代一定次数就保存一次模型,避免训练中断,以恢复模型
if epoch%20==0path='./model' + str(epoch) +'.pth'
参考:PyTorch笔记之模型保存和加载
Pytorch模型保存与加载,并在加载的模型基础上继续训练
保存模型的两种方法:
torch.save(the_model,PATH)the_model = torch.load(PATH)
torch.save((the_model.state_dict(),PATH)#以保存训练有素的模型the_model.load_state_dict(torch.load(PATH))#加载保存的模型。