hub
hub copied to clipboard
Bug: TF Hub is not compatible with Keras 3 and TensorFlow 2.16+
What happened?
When I try to create Keras model using TF 2.16+ I've got an error: ValueError: Exception encountered when calling layer 'keras_layer' (type KerasLayer). A KerasTensor is symbolic: it's a placeholder for a shape an a dtype. It doesn't have any actual numerical value. You cannot convert it to a NumPy array.
Relevant code
import tensorflow as tf
import tensorflow_hub as hub
image = tf.keras.layers.Input(shape=(224, 224, 3), dtype=tf.float32, name="image")
feature_vector = hub.KerasLayer("https://www.kaggle.com/models/google/mobilenet-v2/frameworks/tensorFlow2/variations/100-224-feature-vector/versions/2", trainable=False)(image)
softmax = tf.keras.layers.Dense(20, activation='softmax')(feature_vector)
classification_model = tf.keras.Model(inputs={'image': image}, outputs={'softmax': softmax})
Relevant log output
ValueError: Exception encountered when calling layer 'keras_layer' (type KerasLayer).
A KerasTensor is symbolic: it's a placeholder for a shape an a dtype. It doesn't have any actual numerical value. You cannot convert it to a NumPy array.
tensorflow_hub Version
0.12.0 (latest stable release)
TensorFlow Version
other (please specify)
Other libraries
TF 2.16
Python Version
3.x
OS
Linux
Hi @rkazants. Thanks for posting.
Can you try upgrading to the latest tensorflow_hub version 0.16.1 and installing tf-keras as a peer dependency?
Some extra context:
TensorFlow v2.16 points tf.keras to Keras 3, which unfortunately breaks a number of workflows with tensorflow_hub. We're working to make tensorflow_hub compatible with Keras 3 but in the meantime the recommendation is to use Keras 2 via tf-keras.
@KeijiBranshi Thanks. It worked
- Install tf_keras via pip install tf-keras
- Run the below code at the first of your code ( before importing tensorflow ):
import os
os.environ['TF_USE_LEGACY_KERAS']='1'
Now your code should work properly with using keras 2
Done with the above installation still getting the error can anyone help with it
@Aarushi16V The following is what worked for me.
!pip3 install tf_keras==2.16 !pip3 install --upgrade tensorflow-hub
import os os.environ['TF_USE_LEGACY_KERAS']='1'