Skip to main content
edited tags
Link
Cow
  • 3.1k
  • 6
  • 24
  • 45
Source Link

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?

created from staging ground