I am learning TensorFlow and transfer learning, and I am trying to add a TensorFlow Hub feature extractor to a Keras Sequential model. But I get this error:
ValueError: Only instances of keras.Layer can be added to a Sequential model.
My code:
import tensorflow as tf
import tensorflow_hub as hub
from tensorflow.keras import layers
def create_model(model_url, num_classes=10):
model = tf.keras.Sequential([
hub.KerasLayer(model_url, trainable=False, input_shape=(224,224,3)),
layers.Dense(num_classes, activation="softmax")
])
return model
resnet_model = create_model(resnet_url,
num_classes=train_data_10_percent.num_classes)
I expected hub.KerasLayer to work like a normal Keras layer, but Sequential gives this error.
Why is this happening, and what is the correct way to use TF Hub models inside a Sequential model?
TFHubhas dependency ontf_keraspackage (i.e Keras2). Since from TensorFlow versions (2.16+), it defaults to keras 3, causing the value error. To resolve this, install thetf_kerasand set the environment variableTF_USE_LEGACY_KERAS=1to force the use of legacy Keras 2. Or, Consider usingtensorflow==2.15andtensorflow_hub==0.16.1. Thanks!