'how to obtain the number of classes using tf.keras.preprocessing.image_dataset_from_directory?

img_height,img_width=180,100 batch_size=32 train_ds = tf.keras.preprocessing.image_dataset_from_directory(data_dir1,validation_split=0.01,subset="training",seed=123,image_size=(img_height, img_width),batch_size=batch_size)

Output: Found 1376 files belonging to 4 classes. Using 1363 files for training.

how can I get the total number of classes in a variable?



Solution 1:[1]

label_map = (train.ds.class_indices)

Solution 2:[2]

If you have something like

train_gen=tf.keras.preprocessing.image_dataset_from_directory(etc

then you can use the code below to get the type of information you want

classes=list(train_gen.class_indices.keys())
class_indices=list(train_gen.class_indices.values())
num_of_classes=len(classes)

train_gen.class_indices is a dictionary of the form {class: index}

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 Whereismywall
Solution 2 Mark Rotteveel