pytorch - fastaiv2 到火炬服务器的 pytorch
问题描述
我通常使用 fastai(v2 或 v1)进行快速原型设计。现在我想将我用 fastai 训练的模型之一部署到 torchserver。
假设我们有一个像这样的简单模型:
learn = cnn_learner(data,
models.resnet34,
metrics=[accuracy, error_rate, score])
# after the training
torch.save(learn.model.state_dict(), "./test1.pth")
state = torch.load("./test1.pth")
model_torch_rep = models.resnet34()
model_torch_rep.load_state_dict(state)
我尝试了许多不同的东西,结果相同
RuntimeError Traceback (most recent call last)
<ipython-input-284-e4dbdce23d43> in <module>
----> 1 model_torch_rep.load_state_dict(state);
/opt/conda/lib/python3.6/site-packages/torch/nn/modules/module.py in load_state_dict(self, state_dict, strict)
837 if len(error_msgs) > 0:
838 raise RuntimeError('Error(s) in loading state_dict for {}:\n\t{}'.format(
--> 839 self.__class__.__name__, "\n\t".join(error_msgs)))
840 return _IncompatibleKeys(missing_keys, unexpected_keys)
841
RuntimeError: Error(s) in loading state_dict for ResNet:
Missing key(s) in state_dict: "conv1.weight", "bn1.weight", "bn1.bias", "bn1.running_mean", "bn1.running_var", "layer1.0.conv1.weight", "layer1.0.bn1.weight"
fastai 1.0.6 或 fastai 2.3.1 + pytorch 1.8.1 正在发生这种情况......
解决方案
刚刚想通了。
由于某种原因,您保存 state_dict 的方式添加了一个字符串“模块”。到加载的 state_dict 中的每个键。(这是因为你没有使用 FastAI 的 Learner 类来保存模型,我假设)。
只需删除“模块”。来自状态字典的子字符串,你都很好。
learn = cnn_learner(data,
models.resnet34,
metrics=[accuracy, error_rate, score])
# after the training
torch.save(learn.model.state_dict(), "./test1.pth")
state = torch.load("./test1.pth")
# fix dict keys
new_state = OrderedDict([(k.partition('module.')[2], v) for k, v in state.items()])
model_torch_rep = models.resnet34()
model_torch_rep.load_state_dict(new_state)
推荐阅读
- python - 对于 XGBoost 有没有办法在每个推理的基础上找到特征重要性
- r - 用 rbind 组合两个向量
- ruby - 删除值小于 1000 的哈希键
- python - 在时间戳上加入两个熊猫数据框
- c# - c# 从delegate.begininvoke 捕获异常而不调用delegate.endinvoke
- firebase - 如何使用 Firebase 规则存在于 Firestore 的 SubCollection 中
- mongodb - 从 mongoDB 获取数据时不打印输出
- java - 如果单元格高度发生更改,则可装箱文本不会出现
- arrays - 索引到第二个数组元素总是返回零
- sql - 总和不能低于零的正数和负数的总和