This issue can occur due to incompatibility between the TensorFlow/Keras versions used to create the model and the versions supported by the Deep Learning Toolbox Converter for TensorFlow Models in MATLAB R2024b. Specifically:
- The Deep Learning Toolbox Converter for TensorFlow Models currently supports TensorFlow versions up to 2.15.0.
- TensorFlow versions 2.16 and above use Keras 3 by default, which is not compatible with the "importNetworkFromTensorFlow" function in MATLAB. The converter requires models to be built and saved using Keras 2.
To successfully import your TensorFlow model into MATLAB, use one of the following methods:
1) Build and Save the Model Using Keras 2
a. Install the Keras 2 (tf_keras) package:
>> pip install tf_keras
b. Before importing TensorFlow in your script, set the environment variable to use legacy Keras:
>> import os
>> os.environ["TF_USE_LEGACY_KERAS"] = "1"
>> import tensorflow
c. Import Keras 2 as follows:
>> import tf_keras as keras
>> from tf_keras import layers
d. Build and save your model in the SavedModel format:
>> model.save("myModelTF")
2) Downgrade TensorFlow to Version 2.15 or Lower
- If you prefer not to use the above workaround, you can downgrade your TensorFlow installation to version 2.15 or lower, which uses Keras 2 by default.
- Save your model using:
>> model.save("myModelTF")
Note: Ensure that the model is saved in the TensorFlow SavedModel format. Do not use the tf.saved_model.save function; instead, use the model.save method.
After saving the model as described above, you should be able to import it into MATLAB using the Deep Learning Toolbox Converter for TensorFlow Models.