[Python] error : Only instances of `keras.Layer` can be added to a Sequential model

Discussão em 'Python' iniciado por Stack, Março 29, 2025.

  1. Stack

    Stack Membro Participativo

    I simply want to wrap the model as a keras layer but it simply is not happening ans keeps showing this error to me, i don't know if it's the keras or tensorflow version but i don't want to change them so is there an alternative?

    This is the code I used:

    mobilenet_v2 ="https://tfhub.dev/google/tf2-preview/mobilenet_v2/classification/4"

    classifier_model = mobilenet_v2

    IMAGE_SHAPE = (224, 224)

    classifier = tf.keras.Sequential([
    hub.KerasLayer(classifier_model, input_shape=IMAGE_SHAPE+(3,))
    ])


    and this is the complete error:

    ValueError Traceback (most recent call last)
    Cell In[8], line 3
    1 IMAGE_SHAPE = (224, 224)
    ----> 3 classifier = tf.keras.Sequential([
    4 hub.KerasLayer(classifier_model, input_shape=IMAGE_SHAPE+(3,))
    5 ])

    File ~\Desktop\TFproj\tfvenv\Lib\site-packages\keras\src\models\sequential.py:73, in Sequential.__init__(self, layers, trainable, name)
    71 if layers:
    72 for layer in layers:
    ---> 73 self.add(layer, rebuild=False)
    74 self._maybe_rebuild()

    File ~\Desktop\TFproj\tfvenv\Lib\site-packages\keras\src\models\sequential.py:95, in Sequential.add(self, layer, rebuild)
    93 layer = origin_layer
    94 if not isinstance(layer, Layer):
    ---> 95 raise ValueError(
    96 "Only instances of `keras.Layer` can be "
    97 f"added to a Sequential model. Received: {layer} "
    98 f"(of type {type(layer)})"
    99 )
    100 if not self._is_layer_name_unique(layer):
    101 raise ValueError(
    102 "All layers added to a Sequential model "
    103 f"should have unique names. Name '{layer.name}' is already "
    104 "the name of a layer in this model. Update the `name` argument "
    105 "to pass a unique name."
    106 )

    ValueError: Only instances of `keras.Layer` can be added to a Sequential model. Received: <tensorflow_hub.keras_layer.KerasLayer object at 0x0000021DD8434FB0> (of type <class 'tensorflow_hub.keras_layer.KerasLayer'>)

    Continue reading...

Compartilhe esta Página