InvalidArgumentError with model.fit in Tensorflow

Issue

Image classification with CNN. When the model.fit() is called, it starts to train the model for a while and is interrupted in the middle of execution and returns an error message.

Error message as below

InvalidArgumentError: 2 root error(s) found.
  (0) Invalid argument:  Input size should match (header_size + row_size * abs_height) but they differ by 2
     [[{{node decode_image/DecodeImage}}]]
     [[IteratorGetNext]]
     [[IteratorGetNext/_4]]
  (1) Invalid argument:  Input size should match (header_size + row_size * abs_height) but they differ by 2
     [[{{node decode_image/DecodeImage}}]]
     [[IteratorGetNext]]
0 successful operations.
0 derived errors ignored. [Op:__inference_train_function_8873]

Function call stack:
train_function -> train_function

Update: My suggestion is to check the metadata of the dataset. It helped to fix my problem.

Solution

You have not to specified the parameter label_mode . In order to use SparseCategoricalCrossentropy as the loss function you need to set it to int.
If you do not specify it then it is set to None as per the documentation.

You need to also specify the parameter labels to be the inferred based on the structure of the directory that you read the images from.

train_ds = tf.keras.preprocessing.image_dataset_from_directory(
  data_dir,
  labels="inferred",
  label_mode="int",
  validation_split=0.2,
  subset="training",
  seed=123,
  image_size=(img_height, img_width),
  batch_size=batch_size)
  
val_ds = tf.keras.preprocessing.image_dataset_from_directory(
  data_dir,
  labels="inferred",
  label_mode="int",
  validation_split=0.2,
  subset="validation",
  seed=123,
  image_size=(img_height, img_width),
  batch_size=batch_size)

Answered By – yudhiesh

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published