Skip to content Skip to sidebar Skip to footer

Keras Image Data Generator .flow_from_directory(directory) Unify/combine Classes

I am using Python with Keras and ImageDataGenerator to generate images from directory. I have about 20 classes, and I would like to unify them in some way. For instance, classes 1-

Solution 1:

I don't think there is a built-in way to do so. However, one alternative way is to wrap the generator inside another generator and modify the labels in it (for the sake of demonstration, here I have assumed we have four classes initially, and we want the classes one and two to be considered as the new class one and the classes three and four to be considered as the new class two):

# define the generator
datagen = ImageDataGenerator(...)

# assign class_mode to 'sparse' to make our work easier
gen = datagen.flow_from_directory(..., class_mode= 'sparse')

# define a mapping from old classes to new classes (i.e. 0,1 -> 0 and 2,3 -> 1)
old_to_new = np.array([0, 0, 1, 1])

# the wrapping generator
def new_gen(gen):
    for data, labels in gen:
        labels = old_to_new[labels]
        # now you can call np_utils.to_categorical method 
        # if you would like one-hot encoded labels
        yield data, labels

# ... define your model

# fit the model
model.fit(new_gen(gen), ...)

Post a Comment for "Keras Image Data Generator .flow_from_directory(directory) Unify/combine Classes"