gpt4 book ai didi

python-3.x - 运行时错误 : Error(s) in loading state_dict for ResNet:

转载 作者:行者123 更新时间:2023-12-03 23:29:00 25 4
gpt4 key购买 nike

我正在使用以下代码加载我的模型。

def load_model(checkpoint_path):
'''
Function that loads a checkpoint and rebuilds the model
'''

checkpoint = torch.load(checkpoint_path, map_location = 'cpu')

if checkpoint['architecture'] == 'resnet18':
model = models.resnet18(pretrained=True)

# Freezing the parameters
for param in model.parameters():
param.requires_grad = False


else:
print('Wrong Architecture!')
return None

model.class_to_idx = checkpoint['class_to_idx']

classifier = nn.Sequential(OrderedDict([
('fc1', nn.Linear(512, 1024)),
('relu1', nn.ReLU()),
('dropout', nn.Dropout(0.2)),
('fc2', nn.Linear(1024, 102))
]))


model.fc = classifier

model.load_state_dict(checkpoint['state_dict'])

return model

并且在运行时
# Load your model to this variable
model = load_model('checkpoint.pt')

我收到以下错误,

RuntimeError Traceback (most recent call last) in () 1 # Load your model to this variable ----> 2 model = load_model('checkpoint.pt') 3 4 # If you used something other than 224x224 cropped images, set the correct size here 5 image_size = 224

<ipython-input-11-81aef50793cb> in load_model(checkpoint_path)
30 model.fc = classifier
31
---> 32 model.load_state_dict(checkpoint['state_dict'])
33
34 return model

/opt/conda/lib/python3.6/site-packages/torch/nn/modules/module.py in
load_state_dict(self, state_dict, strict)
719 if len(error_msgs) > 0:
720 raise RuntimeError('Error(s) in loading state_dict for
{}:\n\t{}'.format(
--> 721 self.__class__.__name__,
"\n\t".join(error_msgs)))
722
723 def parameters(self):

RuntimeError: Error(s) in loading state_dict for ResNet:
Unexpected key(s) in state_dict: "bn1.num_batches_tracked",
"layer1.0.bn1.num_batches_tracked", "layer1.0.bn2.num_batches_tracked",
"layer1.1.bn1.num_batches_tracked", "layer1.1.bn2.num_batches_tracked",
"layer2.0.bn1.num_batches_tracked", "layer2.0.bn2.num_batches_tracked",
"layer2.0.downsample.1.num_batches_tracked",
"layer2.1.bn1.num_batches_tracked", "layer2.1.bn2.num_batches_tracked",
"layer3.0.bn1.num_batches_tracked", "layer3.0.bn2.num_batches_tracked",
"layer3.0.downsample.1.num_batches_tracked",
"layer3.1.bn1.num_batches_tracked", "layer3.1.bn2.num_batches_tracked",
"layer4.0.bn1.num_batches_tracked", "layer4.0.bn2.num_batches_tracked",
"layer4.0.downsample.1.num_batches_tracked",
"layer4.1.bn1.num_batches_tracked", "layer4.1.bn2.num_batches_tracked".

最佳答案

我使用的是 Pytorch 0.4.1,但我加载的 Jupyter Notebook 使用的是 0.4.0。所以我将 strict=False 属性添加到 load_state_dict()

model.load_state_dict(checkpoint['state_dict'], strict=False)

关于python-3.x - 运行时错误 : Error(s) in loading state_dict for ResNet:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54058256/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com