mrastikerdar
mrastikerdar

Reputation: 51

Converting Pytorch model to Keras using ONNX

I want to convert a pytorch model to keras using onnx based on this medium article:

https://medium.com/analytics-vidhya/pytorch-to-keras-using-onnx-71d98258ad76

I reproduced the same code as this article but when I want to convert the onnx model to keras I face this error:

ValueError: 'onnx::Add_6_reshape/' is not a valid root scope name. A root scope name has to match the following pattern: ^[A-Za-z0-9.][A-Za-z0-9_.\/>-]*$

Anyone knows how can I fix it?

Upvotes: 5

Views: 2441

Answers (1)

J. Lee
J. Lee

Reputation: 533

Depends on what model you are trying to convert, but can you try the following:

  1. Install pt2keras: https://github.com/JWLee89/pt2keras
pip install -U pt2keras
  1. Convert the model with the script below (tested)

import tensorflow as tf

from pt2keras import Pt2Keras
from pt2keras import converter

import torch.nn.functional as F
import torch.nn as nn


class Model(nn.Module):
    def __init__(self):
        super().__init__()
        self.hidden = nn.Linear(784, 128)
        self.output = nn.Linear(128, 10)

    def forward(self, x):
        x = self.hidden(x)
        x = F.sigmoid(x)
        x = self.output(x)
        return x


if __name__ == '__main__':
    input_shape = (1, 784)

    # Grab model
    model = Model()

    # Create pt2keras object
    converter = Pt2Keras()

    # convert model
    # model can be both pytorch nn.Module or 
    # string path to .onnx file. E.g. 'model.onnx'
    keras_model: tf.keras.Model = converter.convert(model, input_shape)

    # Save the model
    keras_model.save('output_model.h5')

I am the author of the package and this was mainly done quickly during my free time, but hopefully this works for you.

I tested the code above in my local environment and it works for me.

Upvotes: 0

Related Questions