tensorflow / hub

A library for transfer learning by reusing parts of TensorFlow models.
https://tensorflow.org/hub
Apache License 2.0
3.49k stars 1.67k forks source link

Bug: TF Hub is not compatible with Keras 3 and TensorFlow 2.16+ #903

Open rkazants opened 8 months ago

rkazants commented 8 months ago

What happened?

When I try to create Keras model using TF 2.16+ I've got an error: ValueError: Exception encountered when calling layer 'keras_layer' (type KerasLayer). A KerasTensor is symbolic: it's a placeholder for a shape an a dtype. It doesn't have any actual numerical value. You cannot convert it to a NumPy array.

Relevant code

import tensorflow as tf
import tensorflow_hub as hub

image = tf.keras.layers.Input(shape=(224, 224, 3), dtype=tf.float32, name="image")
feature_vector = hub.KerasLayer("https://www.kaggle.com/models/google/mobilenet-v2/frameworks/tensorFlow2/variations/100-224-feature-vector/versions/2", trainable=False)(image)
softmax = tf.keras.layers.Dense(20, activation='softmax')(feature_vector)
classification_model = tf.keras.Model(inputs={'image': image}, outputs={'softmax': softmax})

Relevant log output

ValueError: Exception encountered when calling layer 'keras_layer' (type KerasLayer).
           A KerasTensor is symbolic: it's a placeholder for a shape an a dtype. It doesn't have any actual numerical value. You cannot convert it to a NumPy array.

tensorflow_hub Version

0.12.0 (latest stable release)

TensorFlow Version

other (please specify)

Other libraries

TF 2.16

Python Version

3.x

OS

Linux

KeijiBranshi commented 8 months ago

Hi @rkazants. Thanks for posting.

Can you try upgrading to the latest tensorflow_hub version 0.16.1 and installing tf-keras as a peer dependency?

Some extra context:

TensorFlow v2.16 points tf.keras to Keras 3, which unfortunately breaks a number of workflows with tensorflow_hub. We're working to make tensorflow_hub compatible with Keras 3 but in the meantime the recommendation is to use Keras 2 via tf-keras.

YamatoDX commented 3 months ago

@KeijiBranshi Thanks. It worked

MohammadH8086 commented 2 months ago

Now your code should work properly with using keras 2

Aarushi16V commented 2 months ago

Done with the above installation still getting the error can anyone help with it

rabyunghwa commented 2 weeks ago

@Aarushi16V The following is what worked for me.

!pip3 install tf_keras==2.16 !pip3 install --upgrade tensorflow-hub

import os os.environ['TF_USE_LEGACY_KERAS']='1'