tensorflowkerascoreml

Error while exporting Tensorflow model to CoreML


'Sequential' object has no attribute '_get_save_spec'

import tensorflow as tf
import coremltools as ct
print(tf.__version__)
# Load your existing Keras model
model_path = "/Users/name/Desktop/model.h5"
model = tf.keras.models.load_model(model_path)

# Save the model in SavedModel format
model.save(model_path, save_format='tensorflow')

# Convert the SavedModel to CoreML, specifying the source as 'tensorflow'
coreml_model = ct.convert(model_path, source='tensorflow')

# Save the CoreML model
coreml_model.save("/Users/name/Desktop/model.mlmodel")

I was told to downgrade the versions and I did all the way to tensorflow 2.13.0. Any guidance is appreciated.

Summary1Summary2


Solution

  • here is what worked for me. As far as I understood your 'h5' file was created by keras library and not tf.keras what creates the problem.

    import tensorflow as tf
    import coremltools as ct
    import keras
    
    print(tf.__version__)     # 2.15.0
    print(keras.__version__)  # 3.4.1
    print(ct.__version__)  # 7.2
    
    
    # model was saved using keras and not tf.keras (!!)
    model_path = "model.h5"
    model = keras.models.load_model(model_path)
    
    
    # convert keras model to tensorflow model
    tf_model_path = 'tf_model' # '.pb' model
    tf.saved_model.save(model, tf_model_path)
    
    
    # # Convert the SavedModel to CoreML, specifying the source as 'tensorflow'
    coreml_model = ct.convert(tf_model_path, 
                              source='tensorflow',
                              convert_to="mlprogram")
    
    
    converted_path = 'model.mlpackage'
    # # Save the CoreML model
    coreml_model.save(converted_path)