Depends on what model you are trying to convert, but can you try the following:
- Install pt2keras: https://github.com/JWLee89/pt2keras
pip install -U pt2keras
- 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.