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?
Simplest for learning: use the TF 2.x + Keras 2.x stack that TF Hub is known to work with:
pip install "tensorflow==2.15.*" "keras==2.15.*" "tensorflow-hub>=0.16"
After restarting the kernel, your original code works unchanged:
import tensorflow as tf
import tensorflow_hub as hub
from tensorflow.keras import layers
def create_model(model_url, num_classes=10):
feature_extractor = hub.KerasLayer(
model_url,
input_shape=(224, 224, 3),
trainable=False
)
return tf.keras.Sequential([
feature_extractor,
layers.Dense(num_classes, activation="softmax")
])
If you must stay on newer TF/Keras where both keras and tf.keras coexist, make sure everything uses the same backend (for example via the tf-keras compatibility shim), or use an environment (like Colab with TF 2.15) where TF Hub + Keras are already version-aligned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With