torch.load加载权重时报错 Magic Number Error
有时候使用 torch.load 加载比较古老的权重文件时可能报错 Magic Number Error,这有可能是因为该文件使用 pickle 存储并且编码使用了 latin1,此时可以这样加载:
def resnet50(weights_path=None, **kwargs): """Constructs a ResNet-50 model. """ model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs) if weights_path: import pickle with open(weights_path, 'rb') as f: obj = f.read() weights = {key: weight_dict for key, weight_dict in pickle.loads(obj, encoding='latin1').items()} model.load_state_dict(weights) return model
参考:
https://github.com/cydonia999/VGGFace2-pytorch/issues/2#issuecomment-463571389