【发布时间】:2019-07-29 12:47:19
【问题描述】:
我目前正在使用 fast.ai 来训练图像分类器模型。
data = ImageDataBunch.single_from_classes(path, classes, ds_tfms=get_transforms(), size=224).normalize(imagenet_stats)
learner = cnn_learner(data, models.resnet34)
learner.model.load_state_dict(
torch.load('stage-2.pth', map_location="cpu")
)
导致:
torch.load('stage-2.pth', map_location="cpu") 文件 "/usr/local/lib/python3.6/site-packages/torch/nn/modules/module.py", 第 769 行,在 load_state_dict self.class.name, "\n\t".join(error_msgs))) RuntimeError: Error(s) in loading state_dict for Sequential:
...
state_dict 中有意外的键:“model”、“opt”。
我在 SO 中环顾四周并尝试使用以下解决方案:
# original saved file with DataParallel
state_dict = torch.load('stage-2.pth', map_location="cpu")
# create new OrderedDict that does not contain `module.`
from collections import OrderedDict
new_state_dict = OrderedDict()
for k, v in state_dict.items():
name = k[7:] # remove `module.`
new_state_dict[name] = v
# load params
learner.model.load_state_dict(new_state_dict)
导致:
RuntimeError: 为 Sequential 加载 state_dict 时出错:
state_dict 中有意外的键:“”。
我正在使用 Google Colab 训练我的模型,然后将训练后的模型移植到 docker 并尝试托管在本地服务器中。
可能是什么问题?会不会是不同版本的pytorch导致模型不匹配?
在我的 docker 配置中:
# Install pytorch and fastai
RUN pip install torch_nightly -f https://download.pytorch.org/whl/nightly/cpu/torch_nightly.html
RUN pip install fastai
虽然我的 Colab 正在使用以下内容:
!curl -s https://course.fast.ai/setup/colab | bash
【问题讨论】:
标签: python deep-learning pytorch fast-ai