Search code examples
pythontensorflowdatasetmultilabel-classification

How to show the class distribution in Dataset object in Tensorflow


I am working on a multi-class classification task using my own images.

filenames = [] # a list of filenames
labels = [] # a list of labels corresponding to the filenames
full_ds = tf.data.Dataset.from_tensor_slices((filenames, labels))

This full dataset will be shuffled and split into train, valid and test dataset

full_ds_size = len(filenames)
full_ds = full_ds.shuffle(buffer_size=full_ds_size*2, seed=128) # seed is used for reproducibility

train_ds_size = int(0.64 * full_ds_size)
valid_ds_size = int(0.16 * full_ds_size)

train_ds = full_ds.take(train_ds_size)
remaining = full_ds.skip(train_ds_size)  
valid_ds = remaining.take(valid_ds_size)
test_ds = remaining.skip(valid_ds_size)

Now I am struggling to understand how each class is distributed in train_ds, valid_ds and test_ds. An ugly solution is to iterate all the element in the dataset and count the occurrence of each class. Is there any better way to solve it?

My ugly solution:

def get_class_distribution(dataset):
    class_distribution = {}
    for element in dataset.as_numpy_iterator():
        label = element[1]

        if label in class_distribution.keys():
            class_distribution[label] += 1
        else:
            class_distribution[label] = 0

    # sort dict by key
    class_distribution = collections.OrderedDict(sorted(class_distribution.items())) 
    return class_distribution


train_ds_class_dist = get_class_distribution(train_ds)
valid_ds_class_dist = get_class_distribution(valid_ds)
test_ds_class_dist = get_class_distribution(test_ds)

print(train_ds_class_dist)
print(valid_ds_class_dist)
print(test_ds_class_dist)

Solution

  • The answer below assumes:

    • there are five classes.
    • labels are integers from 0 to 4.

    It can be modified to suit your needs.

    Define a counter function:

    def count_class(counts, batch, num_classes=5):
        labels = batch['label']
        for i in range(num_classes):
            cc = tf.cast(labels == i, tf.int32)
            counts[i] += tf.reduce_sum(cc)
        return counts
    

    Use the reduce operation:

    initial_state = dict((i, 0) for i in range(5))
    counts = train_ds.reduce(initial_state=initial_state,
                             reduce_func=count_class)
    
    print([(k, v.numpy()) for k, v in counts.items()])