【发布时间】:2020-04-14 10:39:04
【问题描述】:
我已经使用 pytorch 获得了完整的模型,但是我想将 .pth 文件转换为 .pb,可以在 Tensorflow 中使用。有人有什么想法吗?
【问题讨论】:
标签: tensorflow pytorch
我已经使用 pytorch 获得了完整的模型,但是我想将 .pth 文件转换为 .pb,可以在 Tensorflow 中使用。有人有什么想法吗?
【问题讨论】:
标签: tensorflow pytorch
你可以使用ONNX:开放神经网络交换格式
要将.pth文件转换为.pb首先需要将PyTorch中定义的模型导出到ONNX,然后将ONNX模型导入Tensorflow(PyTorch => ONNX => Tensorflow)
这是从onnx/tutorials到Convert a PyTorch model to Tensorflow using ONNX的MNISTModel示例
torch.save(model.state_dict(), 'output/mnist.pth')
trained_model = Net()
trained_model.load_state_dict(torch.load('output/mnist.pth'))
# Export the trained model to ONNX
dummy_input = Variable(torch.randn(1, 1, 28, 28)) # one black and white 28 x 28 picture will be the input to the model
torch.onnx.export(trained_model, dummy_input, "output/mnist.onnx")
model = onnx.load('output/mnist.onnx')
# Import the ONNX model to Tensorflow
tf_rep = prepare(model)
tf_rep.export_graph('output/mnist.pb')
@tsveti_iko 在评论中指出
注意:
prepare()是内置在onnx-tf中的,因此您首先需要通过控制台安装它,例如pip install onnx-tf,然后在代码中导入它:import onnx from onnx_tf.backend import prepare,然后您终于可以按照答案中的说明使用它了。
【讨论】:
prepare() 是在onnx-tf 中内置的,所以你首先需要通过控制台安装它,像这样pip install onnx-tf,然后在代码中像这样导入它:@ 987654338@ from onnx_tf.backend import prepare 之后,您终于可以按照答案中的说明使用它了。