Moein Nouri
Moein Nouri

Reputation: 1

ValueError: Only instances of 'keras.Layer' can be added to a Sequential model

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

code:

import kagglehub

# Download latest version
path = kagglehub.model_download("google/mobilenet-v2/tensorFlow2/tf2-preview-feature-vector")
mobile_net = hub.KerasLayer("https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4", 
                            input_shape=(224, 224, 3),  # Change as per your input size
                            trainable=False)  # Freeze weights if you don't want to fine-tune

# Define the Sequential model
model = tf.keras.models.Sequential([
    mobile_net,  # Use the pre-trained model as the first layer
    tf.keras.layers.Dense(1, activation='sigmoid')  # Final layer for binary classification
])

i want to solve the problem but i cant and i need help.

Upvotes: -2

Views: 283

Answers (1)

Jenny
Jenny

Reputation: 31

The code is working fine in tensorflow==2.15 and tensorflow_hub==0.16.1. So, the error could be due to compatibility issues arising from the integration of Keras 3.0 in TensorFlow 2.17. Consider using tf-keras (Keras 2.0) may resolve the issue or using a Lambda layer to wrap hub.KerasLayer (mobile_net) ensures compatibility and allows you to build the model using tf.keras.models.Sequential .

Using lambda layer to wrap the hub layer

import tensorflow as tf
import tensorflow_hub as hub
import kagglehub

path = kagglehub.model_download("google/mobilenet-v2/tensorFlow2/tf2-preview-feature-vector")

mobile_net = hub.KerasLayer(
    "https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4")

model = tf.keras.Sequential([
    tf.keras.layers.InputLayer(input_shape=(224, 224, 3)),
    tf.keras.layers.Lambda(lambda x: mobile_net(x)),
    tf.keras.layers.Dense(1, activation='sigmoid')
])
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
model.summary()

output:

Model: "sequential_5"
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┓
┃ Layer (type)                         ┃ Output Shape                ┃         Param # ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━┩
│ lambda_2 (Lambda)                    │ (None, 1280)                │               0 │
├──────────────────────────────────────┼─────────────────────────────┼─────────────────┤
│ dense_5 (Dense)                      │ (None, 1)                   │           1,281 │
└──────────────────────────────────────┴─────────────────────────────┴─────────────────┘
 Total params: 1,281 (5.00 KB)
 Trainable params: 1,281 (5.00 KB)
 Non-trainable params: 0 (0.00 B)

Kindly refer to to this gist, and documentation for more details.

Upvotes: 1

Related Questions