Keras
class_mode
image_gen
flow_from_directory
deep learning

what does class_mode parameter in Keras image_gen.flow_from_directory signify?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

The class_mode parameter in Keras's flow_from_directory() function is a pivotal aspect of configuring data generators for image data in deep learning applications. Understanding this parameter is crucial as it determines the nature of the labels that accompany the image data. Let’s delve into its technical intricacies, real-world applications, and various usage scenarios.

Understanding class_mode

The class_mode argument specifies the format of the label arrays to be returned by the generator, which directly influences how the model interprets the target data. This impacts how the data is fed into models and plays a critical role in training configurations.

Available Options for class_mode

  • categorical: This is the default setting when working with a dataset with multiple categories for a single label. It indicates that labels are to be returned as a 2D one-hot encoded array. This is used in multi-class classification problems, such as when a model needs to distinguish among more than two classes.
  • binary: Here, the labels are returned as 1D binary labels (0s and 1s). This mode is suitable for binary classification problems where there are only two classes.
  • sparse: Similar to categorical, but instead of a one-hot encoded vector, integer labels are used. This is useful when dealing with multi-class classification without the overhead of transforming labels to one-hot vectors.
  • input: The generator will output only the images array. This mode is typically used with autoencoders, where the input and output are identical.
  • None: No labels will be returned by the generator. This can be used when working with unsupervised learning tasks where labels aren’t necessary.

Technical Explanation and Examples

1. Categorical Classification

When using class_mode='categorical', the generator converts class indices into one-hot vectors. For a dataset with three classes: 'dog', 'cat', and 'rabbit', the labels for the images would be represented as follows:

  • dog: [1, 0, 0]
  • cat: [0, 1, 0]
  • rabbit: [0, 0, 1]

This approach is optimal for models that output probabilities across multiple classes, such as the softmax layer in neural networks.

  • cat: 0
  • dog: 1
  • dog: 0
  • cat: 1
  • rabbit: 2
  • categorical: Use CategoricalCrossentropy loss.
  • binary: Use BinaryCrossentropy loss.
  • sparse: Use SparseCategoricalCrossentropy loss.

Course illustration
Course illustration

All Rights Reserved.