用torch 1.8.1训练保存的模型,用torch 1.1.0进行模型加载。PyTorch的1.6版本将torch.save切换为使用新的基于zipfile的文件格式。 torch.load仍然保留以旧格式加载文件的功能。 如果出于任何原因您希望torch.save使用旧格式,请传递kwarg _use_new_zipfile_serialization = False。
The 1.6 release of PyTorch switched torch.save to use a new zipfile-based file format. torch.load still retains the ability to load files in the old format. If for any reason you want torch.save to use the old format, pass the kwarg _use_new_zipfile_serialization=False.
- 解决方法1
保存模型时,传递kwarg _use_new_zipfile_serialization = False参数,使用旧格式。
torch.save(net.state_dict(), model_dir + model_name + "_bce_itr_%d_train_%3f_tar_%3f.pth" % (
ite_num, running_loss / ite_num4val, running_tar_loss / ite_num4val), _use_new_zipfile_serialization=False)
- 解决方法2
将压缩格式转换为非压缩格式。
import torch
from model import U2NET
net = U2NET(3, 1)
state_dict = torch.load('/opt/xxx/work/U-2-Net/saved_models/u2net/u2net_bce_itr_2870000_train_0.112345_tar_0.013032.pth')
net.load_state_dict(state_dict)
torch.save(net.state_dict(), '/opt/xxx/work/U-2-Net/saved_models/u2net/u2net_bce_itr_2870000_train_0.112345_tar_0.013032_20210506.pth',
_use_new_zipfile_serialization=False)
参考资料
使用torch.load()加载模型参数时,提示“xxx.pt is a zip archive(did you mean to use torch.jit.load()?)“