New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
"ValueError: Layer 'dense' expected 1 input(s). Received 2 instead" on tf.keras.models.load_model #63853
Comments
Hi @AaronEggert , Thank you! |
Thank you for your help. input_shape = (224, 224, 3) Traceback (most recent call last): |
I have the exact same error. Although the platform is different (MacBook Pro w/ M3), the TF version is the same (2.16.1). My models are also really similar to the ones described here (CNN Backbone + GlobalAveragePooling2D + Dense). The proposed fix also did not seem to work properly. Do we have any updates on this issue? |
I found a solution to that: This Code whould help you:
|
Well, it doesn't seem to work properly. Am I missing something?
|
I am having the shape issue on a Windows 10 machine with TF 2.16.1 and similar model. The proposed solution yields the same ValueError as before. |
Have exactly the same issue on Mac. Setting the input shape does't help |
same here with tf 2.16.1, I've also tried tf2.15 with keras 3.0&3.1.1 but with no luck. My trained and saved .keras model (trained with 2.16.1)is not able to load with keras.saving.load_model()
a walkround is to save the trained model with .weights.h5 and build model , load weights(but you need to retrain the model and save weights only which is sometimes not acceptable)
then
|
@squallssck I think that we reached the same workaround. The only thing working for now is saving the weights and loading them to the model:
Not the optimal solution, but it works. |
Any update on this issue? |
есть ли фид бек по тому когда эта ошибка появилась , потому что раньше все работало отлично и никаких проблем не наблюдалось |
Version 2.15.0.post1 is working fine for *.keras extensions. The model should also be trained on this version. It's working fine on 2.15.0.post1 |
Thanks @91Abdullah. It worked for me! |
I am also having the shape issue on a Ubuntu 20.4 machine with TF 2.16.1
here is error
|
Also having the same issue. Windows 10 machine with TF 2.16.1. Here is how I trained my model:
and here is my error:
|
@gmtanner-cord try to use version 2.15 it should work as expected. |
i have solved this problem by lower my tensorflow version to 2.12.0, maybe u can have a try
…------------------ 原始邮件 ------------------
发件人: ***@***.***>;
发送时间: 2024年4月24日(星期三) 上午10:10
收件人: ***@***.***>;
抄送: ***@***.***>; ***@***.***>;
主题: Re: [tensorflow/tensorflow] "ValueError: Layer 'dense' expected 1 input(s). Received 2 instead" on tf.keras.models.load_model (Issue #63853)
Also having the same issue. Windows 10 machine with TF 2.16.1. Here is how I trained my model:
import tensorflow as tf from tensorflow.keras.applications import EfficientNetV2S V2S_model = EfficientNetV2S(weights='imagenet', include_top=False, input_shape=(224, 224, 3)) for layer in V2S_model.layers: layer.trainable = False from tensorflow.keras import layers image_preprocess = tf.keras.Sequential([ tf.keras.Input((None,None,3)), layers.Resizing(224,224, crop_to_aspect_ratio = True), layers.RandomFlip("horizontal_and_vertical"), layers.RandomRotation(0.2) ], name = "image_aug") transfer_model = tf.keras.Sequential([ tf.keras.Input((None,None,3)), image_preprocess, V2S_model, layers.GlobalAveragePooling2D(), layers.Dense(512, activation='relu'), layers.Dropout(0.2), layers.Dense(1, activation = 'sigmoid') ]) transfer_model.summary() metrics = [tf.keras.metrics.BinaryAccuracy(threshold=0.5, name='accuracy'), tf.keras.metrics.AUC(), tf.keras.metrics.TruePositives(), tf.keras.metrics.TrueNegatives(), tf.keras.metrics.FalsePositives(), tf.keras.metrics.FalseNegatives() ] transfer_model.compile(loss=tf.keras.losses.BinaryCrossentropy(), optimizer=tf.keras.optimizers.Adam(learning_rate=0.001), metrics=metrics) BATCH_SIZE = 16 IMAGE_SIZE = (224,224) SEED = 42 # This sets up a training and validation set from our ../data/ directory train_dataset = tf.keras.utils.image_dataset_from_directory( '../data/', class_names = ['not_niblet','niblet'], color_mode='rgb', batch_size=BATCH_SIZE, image_size=IMAGE_SIZE, shuffle=True, validation_split=0.2, subset='training', seed=SEED) # This is the validation set. Notice `shuffle = FALSE` and `subset = validation` val_dataset = tf.keras.utils.image_dataset_from_directory( '../data/', class_names = ['not_niblet','niblet'], color_mode='rgb', batch_size=BATCH_SIZE, image_size=IMAGE_SIZE, shuffle=True, validation_split=0.2, subset='validation', seed=SEED) from tensorflow.keras.callbacks import EarlyStopping es = EarlyStopping(patience=15, monitor='val_loss') history = transfer_model.fit(train_dataset, epochs=100, validation_data=val_dataset, callbacks=[es]) transfer_model.save('../models/transfer_model_gt_2024_04_23.keras') transfer_model_loaded = tf.keras.models.load_model('../models/transfer_model_gt_2024_04_23.keras')
and here is my error:
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[16], line 2 1 input_shape = (None,None,3) ----> 2 transfer_model_loaded = tf.keras.models.load_model('../models/transfer_model_gt_2024_04_23.keras', compile=False, custom_objects={'input_shape': input_shape}) File [~\anaconda3\envs\CS380_final\Lib\site-packages\keras\src\saving\saving_api.py:176](http://localhost:8888/lab/tree/Documents/GitHub/CSC380/scripts/~/anaconda3/envs/CS380_final/Lib/site-packages/keras/src/saving/saving_api.py#line=175), in load_model(filepath, custom_objects, compile, safe_mode) 173 is_keras_zip = True 175 if is_keras_zip: --> 176 return saving_lib.load_model( 177 filepath, 178 custom_objects=custom_objects, 179 compile=compile, 180 safe_mode=safe_mode, 181 ) 182 if str(filepath).endswith((".h5", ".hdf5")): 183 return legacy_h5_format.load_model_from_hdf5(filepath) File [~\anaconda3\envs\CS380_final\Lib\site-packages\keras\src\saving\saving_lib.py:152](http://localhost:8888/lab/tree/Documents/GitHub/CSC380/scripts/~/anaconda3/envs/CS380_final/Lib/site-packages/keras/src/saving/saving_lib.py#line=151), in load_model(filepath, custom_objects, compile, safe_mode) 147 raise ValueError( 148 "Invalid filename: expected a `.keras` extension. " 149 f"Received: filepath={filepath}" 150 ) 151 with open(filepath, "rb") as f: --> 152 return _load_model_from_fileobj( 153 f, custom_objects, compile, safe_mode 154 ) File [~\anaconda3\envs\CS380_final\Lib\site-packages\keras\src\saving\saving_lib.py:170](http://localhost:8888/lab/tree/Documents/GitHub/CSC380/scripts/~/anaconda3/envs/CS380_final/Lib/site-packages/keras/src/saving/saving_lib.py#line=169), in _load_model_from_fileobj(fileobj, custom_objects, compile, safe_mode) 168 # Construct the model from the configuration file in the archive. 169 with ObjectSharingScope(): --> 170 model = deserialize_keras_object( 171 config_dict, custom_objects, safe_mode=safe_mode 172 ) 174 all_filenames = zf.namelist() 175 if _VARS_FNAME + ".h5" in all_filenames: File [~\anaconda3\envs\CS380_final\Lib\site-packages\keras\src\saving\serialization_lib.py:711](http://localhost:8888/lab/tree/Documents/GitHub/CSC380/scripts/~/anaconda3/envs/CS380_final/Lib/site-packages/keras/src/saving/serialization_lib.py#line=710), in deserialize_keras_object(config, custom_objects, safe_mode, **kwargs) 709 with custom_obj_scope, safe_mode_scope: 710 try: --> 711 instance = cls.from_config(inner_config) 712 except TypeError as e: 713 raise TypeError( 714 f"{cls} could not be deserialized properly. Please" 715 " ensure that components that are Python object" (...) 719 f"\n\nconfig={config}[.\n\nException](http://localhost:8888/lab/tree/Documents/GitHub/CSC380/scripts/n/nException) encountered: {e}" 720 ) File [~\anaconda3\envs\CS380_final\Lib\site-packages\keras\src\models\sequential.py:339](http://localhost:8888/lab/tree/Documents/GitHub/CSC380/scripts/~/anaconda3/envs/CS380_final/Lib/site-packages/keras/src/models/sequential.py#line=338), in Sequential.from_config(cls, config, custom_objects) 334 else: 335 layer = serialization_lib.deserialize_keras_object( 336 layer_config, 337 custom_objects=custom_objects, 338 ) --> 339 model.add(layer) 340 if ( 341 not model._functional 342 and build_input_shape 343 and isinstance(build_input_shape, (tuple, list)) 344 ): 345 model.build(build_input_shape) File [~\anaconda3\envs\CS380_final\Lib\site-packages\keras\src\models\sequential.py:120](http://localhost:8888/lab/tree/Documents/GitHub/CSC380/scripts/~/anaconda3/envs/CS380_final/Lib/site-packages/keras/src/models/sequential.py#line=119), in Sequential.add(self, layer, rebuild) 118 self._layers.append(layer) 119 if rebuild: --> 120 self._maybe_rebuild() 121 else: 122 self.built = False File [~\anaconda3\envs\CS380_final\Lib\site-packages\keras\src\models\sequential.py:139](http://localhost:8888/lab/tree/Documents/GitHub/CSC380/scripts/~/anaconda3/envs/CS380_final/Lib/site-packages/keras/src/models/sequential.py#line=138), in Sequential._maybe_rebuild(self) 137 if isinstance(self._layers[0], InputLayer) and len(self._layers) > 1: 138 input_shape = self._layers[0].batch_shape --> 139 self.build(input_shape) File [~\anaconda3\envs\CS380_final\Lib\site-packages\keras\src\layers\layer.py:222](http://localhost:8888/lab/tree/Documents/GitHub/CSC380/scripts/~/anaconda3/envs/CS380_final/Lib/site-packages/keras/src/layers/layer.py#line=221), in Layer.__new__.<locals>.build_wrapper(*args, **kwargs) 219 @wraps(original_build_method) 220 def build_wrapper(*args, **kwargs): 221 with obj._open_name_scope(): --> 222 original_build_method(*args, **kwargs) 223 # Record build config. 224 signature = inspect.signature(original_build_method) File [~\anaconda3\envs\CS380_final\Lib\site-packages\keras\src\models\sequential.py:180](http://localhost:8888/lab/tree/Documents/GitHub/CSC380/scripts/~/anaconda3/envs/CS380_final/Lib/site-packages/keras/src/models/sequential.py#line=179), in Sequential.build(self, input_shape) 178 for layer in self._layers[1:]: 179 try: --> 180 x = layer(x) 181 except NotImplementedError: 182 # Can happen if shape inference is not implemented. 183 # TODO: consider reverting inbound nodes on layers processed. 184 return File [~\anaconda3\envs\CS380_final\Lib\site-packages\keras\src\utils\traceback_utils.py:122](http://localhost:8888/lab/tree/Documents/GitHub/CSC380/scripts/~/anaconda3/envs/CS380_final/Lib/site-packages/keras/src/utils/traceback_utils.py#line=121), in filter_traceback.<locals>.error_handler(*args, **kwargs) 119 filtered_tb = _process_traceback_frames(e.__traceback__) 120 # To get the full stack trace, call: 121 # `keras.config.disable_traceback_filtering()` --> 122 raise e.with_traceback(filtered_tb) from None 123 finally: 124 del filtered_tb File [~\anaconda3\envs\CS380_final\Lib\site-packages\keras\src\layers\input_spec.py:156](http://localhost:8888/lab/tree/Documents/GitHub/CSC380/scripts/~/anaconda3/envs/CS380_final/Lib/site-packages/keras/src/layers/input_spec.py#line=155), in assert_input_compatibility(input_spec, inputs, layer_name) 154 inputs = tree.flatten(inputs) 155 if len(input_spec) != len(inputs): --> 156 raise ValueError( 157 f"Layer '{layer_name}' expected {len(input_spec)} input(s). " 158 f"Received {len(inputs)} instead." 159 ) 160 for x in inputs: 161 # Having a shape/dtype is the only commonality of the various 162 # tensor-like objects that may be passed. The most common kind of 163 # invalid type we are guarding for is a Layer instance (Functional API), 164 # which does not have a `shape` attribute. 165 if not hasattr(x, "shape"): ValueError: Layer 'dense' expected 1 input(s). Received 2 instead.
—
Reply to this email directly, view it on GitHub, or unsubscribe.
You are receiving this because you commented.Message ID: ***@***.***>
|
Issue type
Bug
Have you reproduced the bug with TensorFlow Nightly?
No
Source
source
TensorFlow version
v2.16.0-rc0-18-g5bc9d26649c 2.16.1
Custom code
Yes
OS platform and distribution
Windows 11 (KB5035853)
Mobile device
No response
Python version
3.11.8
Bazel version
No response
GCC/compiler version
No response
CUDA/cuDNN version
No response
GPU model and memory
No response
Current behavior?
I want to load a saved model directly after training. But when it executes tf.keras.models.load_model it says
ValueError: Layer 'dense' expected 1 input(s). Received 2 instead.
Standalone code to reproduce the issue
Relevant log output
The text was updated successfully, but these errors were encountered: