有時候使用 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