XifengGuo / CapsNet-Keras

A Keras implementation of CapsNet in NIPS2017 paper "Dynamic Routing Between Capsules". Now test error = 0.34%.
MIT License
2.47k stars 651 forks source link

ValueError: Layer model expects 2 input(s), but it received 4 input tensors. #126

Closed RawanRadi closed 2 years ago

RawanRadi commented 3 years ago

At the end of the first epoch the following error raised :

ValueError: Layer model expects 2 input(s), but it received 4 input tensors. The code also raise warnings:

Epoch 1/50
/Users/x/.local/lib/python3.7/site-packages/keras/callbacks/tensorboard_v2.py:92: UserWarning: The TensorBoard callback `batch_size` argument (for histogram computation) is deprecated with TensorFlow 2.0. It will be ignored.
  warnings.warn('The TensorBoard callback `batch_size` argument '
/Users/x/.local/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py:1844: UserWarning: `Model.fit_generator` is deprecated and will be removed in a future version. Please use `Model.fit`, which supports generators.
  warnings.warn('`Model.fit_generator` is deprecated and '
600/600 [==============================] - ETA: 0s - loss: 0.8437 - capsnet_loss: 0.8094 - decoder_loss: 0.0874 - capsnet_accuracy: 0.0987
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-10-fe0191a502ba> in <module>
     48         model.load_weights(args.weights)
     49     if not args.testing:
---> 50         train(model=model, data=((x_train, y_train), (x_test, y_test)), args=args)
     51     else:  # as long as weights are given, will run testing
     52         if args.weights is None:

<ipython-input-9-87ada1294ceb> in train(model, data, args)
     45                         epochs=args.epochs,
     46                         validation_data=[[x_test, y_test], [y_test, x_test]],
---> 47                         callbacks=[log, tb, checkpoint, lr_decay])
     48     # End: Training with data augmentation -----------------------------------------------------------------------#
     49 

~/.local/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py in fit_generator(self, generator, steps_per_epoch, epochs, verbose, callbacks, validation_data, validation_steps, validation_freq, class_weight, max_queue_size, workers, use_multiprocessing, shuffle, initial_epoch)
   1859         use_multiprocessing=use_multiprocessing,
   1860         shuffle=shuffle,
-> 1861         initial_epoch=initial_epoch)
   1862 
   1863   def evaluate_generator(self,

~/.local/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_batch_size, validation_freq, max_queue_size, workers, use_multiprocessing)
   1139               workers=workers,
   1140               use_multiprocessing=use_multiprocessing,
-> 1141               return_dict=True)
   1142           val_logs = {'val_' + name: val for name, val in val_logs.items()}
   1143           epoch_logs.update(val_logs)

~/.local/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py in evaluate(self, x, y, batch_size, verbose, sample_weight, steps, callbacks, max_queue_size, workers, use_multiprocessing, return_dict)
   1387             with trace.Trace('test', step_num=step, _r=1):
   1388               callbacks.on_test_batch_begin(step)
-> 1389               tmp_logs = self.test_function(iterator)
   1390               if data_handler.should_sync:
   1391                 context.async_wait()

~/.local/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)
    826     tracing_count = self.experimental_get_tracing_count()
    827     with trace.Trace(self._name) as tm:
--> 828       result = self._call(*args, **kwds)
    829       compiler = "xla" if self._experimental_compile else "nonXla"
    830       new_tracing_count = self.experimental_get_tracing_count()

~/.local/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py in _call(self, *args, **kwds)
    869       # This is the first call of __call__, so we have to initialize.
    870       initializers = []
--> 871       self._initialize(args, kwds, add_initializers_to=initializers)
    872     finally:
    873       # At this point we know that the initialization is complete (or less

~/.local/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to)
    724     self._concrete_stateful_fn = (
    725         self._stateful_fn._get_concrete_function_internal_garbage_collected(  # pylint: disable=protected-access
--> 726             *args, **kwds))
    727 
    728     def invalid_creator_scope(*unused_args, **unused_kwds):

~/.local/lib/python3.7/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args, **kwargs)
   2967       args, kwargs = None, None
   2968     with self._lock:
-> 2969       graph_function, _ = self._maybe_define_function(args, kwargs)
   2970     return graph_function
   2971 

~/.local/lib/python3.7/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs)
   3359 
   3360           self._function_cache.missed.add(call_context_key)
-> 3361           graph_function = self._create_graph_function(args, kwargs)
   3362           self._function_cache.primary[cache_key] = graph_function
   3363 

~/.local/lib/python3.7/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)
   3204             arg_names=arg_names,
   3205             override_flat_arg_shapes=override_flat_arg_shapes,
-> 3206             capture_by_value=self._capture_by_value),
   3207         self._function_attributes,
   3208         function_spec=self.function_spec,

~/.local/lib/python3.7/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes)
    988         _, original_func = tf_decorator.unwrap(python_func)
    989 
--> 990       func_outputs = python_func(*func_args, **func_kwargs)
    991 
    992       # invariant: `func_outputs` contains only Tensors, CompositeTensors,

~/.local/lib/python3.7/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds)
    632             xla_context.Exit()
    633         else:
--> 634           out = weak_wrapped_fn().__wrapped__(*args, **kwds)
    635         return out
    636 

~/.local/lib/python3.7/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)
    975           except Exception as e:  # pylint:disable=broad-except
    976             if hasattr(e, "ag_error_metadata"):
--> 977               raise e.ag_error_metadata.to_exception(e)
    978             else:
    979               raise

ValueError: in user code:

    /Users/x/.local/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py:1233 test_function  *
        return step_function(self, iterator)
    /Users/x/.local/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py:1224 step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    /Users/x/.local/lib/python3.7/site-packages/tensorflow/python/distribute/distribute_lib.py:1259 run
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    /Users/x/.local/lib/python3.7/site-packages/tensorflow/python/distribute/distribute_lib.py:2730 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    /Users/x/.local/lib/python3.7/site-packages/tensorflow/python/distribute/distribute_lib.py:3417 _call_for_each_replica
        return fn(*args, **kwargs)
    /Users/x/.local/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py:1217 run_step  **
        outputs = model.test_step(data)
    /Users/x/.local/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py:1183 test_step
        y_pred = self(x, training=False)
    /Users/x/.local/lib/python3.7/site-packages/tensorflow/python/keras/engine/base_layer.py:998 __call__
        input_spec.assert_input_compatibility(self.input_spec, inputs, self.name)
    /Users/x/.local/lib/python3.7/site-packages/tensorflow/python/keras/engine/input_spec.py:207 assert_input_compatibility
        ' input tensors. Inputs received: ' + str(inputs))

    ValueError: Layer model expects 2 input(s), but it received 4 input tensors. Inputs received: [<tf.Tensor 'IteratorGetNext:0' shape=(None, 28, 28, 1) dtype=float32>, <tf.Tensor 'IteratorGetNext:1' shape=(None, 10) dtype=float32>, <tf.Tensor 'IteratorGetNext:2' shape=(None, 10) dtype=float32>, <tf.Tensor 'IteratorGetNext:3' shape=(None, 28, 28, 1) dtype=float32>]
RawanRadi commented 3 years ago

changing from list to tuple in model.fit solving the error!

#before 
model.fit([x_train, y_train], [y_train, x_train], batch_size=args.batch_size, epochs=args.epochs,
              validation_data=[[x_test, y_test], [y_test, x_test]], callbacks=[log, tb, checkpoint, lr_decay])
#after 
model.fit([x_train, y_train], [y_train, x_train], batch_size=args.batch_size, epochs=args.epochs,
              validation_data=([x_test, y_test], [y_test, x_test]), callbacks=[log, tb, checkpoint, lr_decay])
mathshangw commented 2 years ago

excuse me , what is the difference between before and after .. i couldn't see changes ?

khuberbista commented 2 years ago
**ValueError: Layer model expects 2 input(s), but it received 3 input tensors. Inputs received: [<tf.Tensor 'IteratorGetNext:0' shape=(None, None) dtype=float32>, <tf.Tensor 'IteratorGetNext:1' shape=(None, None) dtype=int32>, <tf.Tensor 'IteratorGetNext:2' shape=(None, None) dtype=float32>]**

I am Getting this Error Everytime. I tried different model and Rnn Networks but still getting this error .

`ile "F:\Major Project\Finsl Offline\Hj88\Trying\Image-Caption-Generator\train_val.py", line 81, in model.fit_generator(generator_train, File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\keras\engine\training.py", line 1918, in fit_generator return self.fit( File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\keras\engine\training.py", line 1158, in fit tmp_logs = self.train_function(iterator) File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\eager\def_function.py", line 889, in call result = self._call(*args, kwds) File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\eager\def_function.py", line 933, in _call self._initialize(args, kwds, add_initializers_to=initializers) File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\eager\def_function.py", line 763, in _initialize self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\eager\function.py", line 3050, in _get_concrete_function_internal_garbage_collected graphfunction, = self._maybe_define_function(args, kwargs) File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\eager\function.py", line 3444, in _maybe_define_function graph_function = self._create_graph_function(args, kwargs) File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\eager\function.py", line 3279, in _create_graph_function func_graph_module.func_graph_from_py_func( File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\framework\func_graph.py", line 999, in func_graph_from_py_func func_outputs = python_func(*func_args, *func_kwargs) File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\eager\def_function.py", line 672, in wrapped_fn out = weak_wrapped_fn().wrapped(args, kwds) File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\framework\func_graph.py", line 986, in wrapper raise e.ag_error_metadata.to_exception(e) ValueError: in user code:

C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\keras\engine\training.py:830 train_function  *
    return step_function(self, iterator)
C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\keras\engine\training.py:813 run_step  *
    outputs = model.train_step(data)
C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\keras\engine\training.py:770 train_step  *
    y_pred = self(x, training=True)
C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\keras\engine\base_layer.py:989 __call__  *
    input_spec.assert_input_compatibility(self.input_spec, inputs, self.name)
C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\keras\engine\input_spec.py:197 assert_input_compatibility  *
    raise ValueError('Layer ' + layer_name + ' expects ' +`
RawanRadi commented 2 years ago

excuse me , what is the difference between before and after .. i couldn't see changes ?

The difference is in "validation_data" type, change it from tuple [[x_test, y_test], [y_test, x_test]], to list ([x_test, y_test], [y_test, x_test]).

before

model.fit([x_train, y_train], [y_train, x_train], batch_size=args.batch_size, epochs=args.epochs, validation_data=[[x_test, y_test], [y_test, x_test]], callbacks=[log, tb, checkpoint, lr_decay])

after

model.fit([x_train, y_train], [y_train, x_train], batch_size=args.batch_size, epochs=args.epochs, validation_data=([x_test, y_test], [y_test, x_test]), callbacks=[log, tb, checkpoint, lr_decay])

The syntax for list and tuple are different. For example: list_num = [10, 20, 30, 40] tup_num = (10, 20, 30, 40)

see more here https://www.upgrad.com/blog/list-vs-tuple/

RawanRadi commented 2 years ago
**ValueError: Layer model expects 2 input(s), but it received 3 input tensors. Inputs received: [<tf.Tensor 'IteratorGetNext:0' shape=(None, None) dtype=float32>, <tf.Tensor 'IteratorGetNext:1' shape=(None, None) dtype=int32>, <tf.Tensor 'IteratorGetNext:2' shape=(None, None) dtype=float32>]**

I am Getting this Error Everytime. I tried different model and Rnn Networks but still getting this error .

`ile "F:\Major Project\Finsl Offline\Hj88\Trying\Image-Caption-Generator\train_val.py", line 81, in model.fit_generator(generator_train, File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\keras\engine\training.py", line 1918, in fit_generator return self.fit( File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\keras\engine\training.py", line 1158, in fit tmp_logs = self.train_function(iterator) File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\eager\def_function.py", line 889, in call result = self._call(*args, kwds) File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\eager\def_function.py", line 933, in _call self._initialize(args, kwds, add_initializers_to=initializers) File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\eager\def_function.py", line 763, in _initialize self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\eager\function.py", line 3050, in _get_concrete_function_internal_garbage_collected graphfunction, = self._maybe_define_function(args, kwargs) File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\eager\function.py", line 3444, in _maybe_define_function graph_function = self._create_graph_function(args, kwargs) File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\eager\function.py", line 3279, in _create_graph_function func_graph_module.func_graph_from_py_func( File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\framework\func_graph.py", line 999, in func_graph_from_py_func func_outputs = python_func(*func_args, func_kwargs) File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\eager\def_function.py", line 672, in wrapped_fn out = weak_wrapped_fn().wrapped*(args, kwds) File "C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\framework\func_graph.py", line 986, in wrapper raise e.ag_error_metadata.to_exception(e) ValueError: in user code:

C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\keras\engine\training.py:830 train_function  *
    return step_function(self, iterator)
C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\keras\engine\training.py:813 run_step  *
    outputs = model.train_step(data)
C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\keras\engine\training.py:770 train_step  *
    y_pred = self(x, training=True)
C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\keras\engine\base_layer.py:989 __call__  *
    input_spec.assert_input_compatibility(self.input_spec, inputs, self.name)
C:\Users\Lenovo\AppData\Roaming\Python\Python39\site-packages\keras\engine\input_spec.py:197 assert_input_compatibility  *
    raise ValueError('Layer ' + layer_name + ' expects ' +`

Show me your code please

Coder-Vishali commented 2 years ago

for i in range(epochs): generator = data_generator(train_descriptions , train_features , tokenizer , max_length) model.fit_generator(generator , epochs = 1 , steps_perepoch = steps , verbose = 1) model.save('model'+ str(i+1) + '.h5')

I am facing the error at this step model.fit()

ValueError: Layer model_3 expects 2 input(s), but it received 3 input tensors
Durgance-solytics commented 2 years ago

@Coder-Vishali i am facing the same issue, but why is this issue closed its not resolved?

Coder-Vishali commented 2 years ago

Hi Durgance

It works fine in google colab. I faced this issue in a Jupyter notebook. I am not sure why it occurs.

Thank you Vishali

On Sat, Mar 19, 2022 at 11:41 PM Durgance-solytics @.***> wrote:

@Coder-Vishali https://github.com/Coder-Vishali i am facing the same issue, but whu is this issue closed ?

— Reply to this email directly, view it on GitHub https://github.com/XifengGuo/CapsNet-Keras/issues/126#issuecomment-1073056106, or unsubscribe https://github.com/notifications/unsubscribe-auth/AOPK5S4C3DOHG2OBE2WKVCDVAYKGJANCNFSM4ZFP5BJA . Triage notifications on the go with GitHub Mobile for iOS https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675 or Android https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub.

You are receiving this because you were mentioned.Message ID: @.***>

suuny-wu commented 2 years ago

de133de5e901f4cf29ddd86b1db429c 怎么解决这个问题

amir-ghz commented 2 years ago

changing from list to tuple in model.fit solving the error!

#before 
model.fit([x_train, y_train], [y_train, x_train], batch_size=args.batch_size, epochs=args.epochs,
              validation_data=[[x_test, y_test], [y_test, x_test]], callbacks=[log, tb, checkpoint, lr_decay])
#after 
model.fit([x_train, y_train], [y_train, x_train], batch_size=args.batch_size, epochs=args.epochs,
              validation_data=([x_test, y_test], [y_test, x_test]), callbacks=[log, tb, checkpoint, lr_decay])

This solved the problem. Thanks

Yeh-Al commented 1 year ago

Excuse me, if anyone can help Here's my code:

################################

Modelcheckpoint

checkpointer = tf.keras.callbacks.ModelCheckpoint('model.h5', verbose=1, save_best_only=True)

callbacks = [ tf.keras.callbacks.EarlyStopping(patience=2, monitor='val_loss'), tf.keras.callbacks.TensorBoard(log_dir='logs')]

results = model.fit(x_train, y_train, validation_split=0.1, batch_size=16, epochs=25, callbacks=callbacks)

and unfortunately the previous solution didn't work out with me