我有一个以.pth格式为扩展名的预训练模型。我想将其转换为Tensorflow protobuf格式,但我找不到任何方法来实现这一点。我看到ONNX可以将PyTorch模型转换为ONNX格式,然后再从ONNX转换为Tensorflow格式。但是在这种方法中,在转换的第一阶段中出现了以下错误。
from torch.autograd import Variable
import torch.onnx
import torchvision
import torch
dummy_input = Variable(torch.randn(1, 3, 256, 256))
model = torch.load('./my_model.pth')
torch.onnx.export(model, dummy_input, "moment-in-time.onnx")`
它会出现如下错误。
File "t.py", line 9, in <module>
torch.onnx.export(model, dummy_input, "moment-in-time.onnx")
File "/usr/local/lib/python3.5/dist-packages/torch/onnx/__init__.py", line 75, in export
_export(model, args, f, export_params, verbose, training)
File "/usr/local/lib/python3.5/dist-packages/torch/onnx/__init__.py", line 108, in _export
orig_state_dict_keys = model.state_dict().keys()
AttributeError: 'dict' object has no attribute 'state_dict'
可能的解决方案是什么?
.pth
文件是一个状态字典,而不是完整的模型。首先需要创建一个模型,然后加载该状态字典,然后开始转换过程。请参考这个答案。 - layog