Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix ValueError: Only instances of keras.Layer can be added to a Sequential model when adding tensorflow_hub.KerasLayer?

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?

like image 603
Sanjay Jithesh Avatar asked Dec 17 '25 11:12

Sanjay Jithesh


1 Answers

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.

like image 150
Dmitry543 Avatar answered Dec 19 '25 00:12

Dmitry543