'ValueError: Shapes (None, 1) and (None, 10) are incompatible - When training CNN with Keras using image_dataset_from_directory

ValueError: Shapes... incompatible is a pretty generic bug when using tensors, but in my case it was when training CNN with Keras using image_dataset_from_directory method.



Solution 1:[1]

The solution was to replace 'categorical_crossentropy' by 'sparse_categorical_crossentropy' in the compilation statement.

Why? According to image_dataset_from_directory documentation, 'int' is the default label encoding. So, by default, 'image_dataset_from_directory' will create a set of labels for the dataset as integer that go from 1 to the number of classes in the dataset.

In this case, the model should be compiled with a 'sparse_categorical_crossentropy' loss, not 'categorical_crossentropy'.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Claude COULOMBE