1

I’m trying to import a DNN trained model from MATLAB to PyTorch.

I’ve found solutions for the opposite case (from PyTorch to MATLAB), but no proposed solutions on how to import a trained model from MATLAB to PyTorch.

Any ideas, please?

desertnaut
  • 57,590
  • 26
  • 140
  • 166
Oubi
  • 15
  • 4

1 Answers1

2

You can first export your model to ONNX format, and then load it using ONNX; prerequisites are:

pip install onnx onnxruntime

Then,

onnx.load('model.onnx')
# Check that the IR is well formed
onnx.checker.check_model(model)

Until this point, you still don't have a PyTorch model. This can be done through various ways since it's not natively supported.


A workaround (by loading only the model parameters)

import onnx
onnx_model = onnx.load('model.onnx')

graph = onnx_model.graph
initalizers = dict()
for init in graph.initializer:
    initalizers[init.name] = numpy_helper.to_array(init)

for name, p in model.named_parameters():
    p.data = (torch.from_numpy(initalizers[name])).data

Using onnx2pytorch

import onnx

from onnx2pytorch import ConvertModel

onnx_model = onnx.load('model.onnx')
pytorch_model = ConvertModel(onnx_model)

Note: Time Consuming

Using onnx2keras, then MMdnn to convert from Keras to PyTorch (Examples)

ndrwnaguib
  • 5,623
  • 3
  • 28
  • 51