3

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?

2
  • I am using Colab for learning, and this is where I encountered the issue. Any guidance on how to resolve it in Colab. Commented Nov 20, 2025 at 13:54
  • Hi @Sanjay Jithesh, The error typically caused by version conflicts between TensorFlow/Keras and TensorFlow Hub. TFHub has dependency on tf_keras package (i.e Keras2). Since from TensorFlow versions (2.16+), it defaults to keras 3, causing the value error. To resolve this, install the tf_keras and set the environment variable TF_USE_LEGACY_KERAS=1 to force the use of legacy Keras 2. Or, Consider usingtensorflow==2.15 and tensorflow_hub==0.16.1. Thanks! Commented Dec 29, 2025 at 7:12

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.