How to handle imbalanced classes

Hi ptrblck, thanks for your kind explanation on WeightedRandomSampler. I am trying to use it to resample the unbalanced dataset, but the dataloader output the most frequent class without any improvement. My dataset loads a dict-like batch (e.g., data[‘image’]) and it does not include label information. here’s my snippets for weights:

  weight_list = [1./len(np.where(submeta['commands']==i)[0]) for i in range(3)]
  # weight_list = [1, 1, 1]
  # submeta['commands'] is a sequence of labels of each index
  submeta['weights'] = torch.from_numpy(np.array([weight_list[i] for i in submeta['commands']]))

How do you measure the imbalance if the DataLoader doesn’t output any label information?

I have a separable variable that stores the label. There are three classes 0, 1, 2 stored in submeta['commands']=[0,1,0,...,2]. So I want to know if it should be included in the dataloader for sampler to work? Or it is ok as long as the weights calculated from the label have shared index
with data? Hope I get myself across, and thanks for your kind reply!

You don’t need to return these labels, since you already created sample weights for each index.
If weight_list is [1, 1, 1] before you are assigning it to each sample index, the weight calculation is wrong or your dataset is perfectly balanced.

Really thank you ptrblck! A late update: there is some problem in my weight index (relative vs absolute index), I followed your advice from another similar topic and check the index carefully and bang! Thanks :smile:

As a follow-up question, I wonder how to implement class-balanced sampling when using BCELoss for minibatch updates. The first challenge is the shuffling of classes VS fixed weight, but reimplementing the DataLoader can fix it. I am more uncertain about the second challenge, if I do not set drop_last=True, is there a way to keep the class weights for the last batch which might have fewer samples? (Same problem for CrossEntropyLoss)

BCEWithLogitsLoss seems to be better because it allows for class weights rather than sample weights.

I guess you’re wrong !
defining :

sampler = WeightedRandomSampler(samples_weight, len(samples_weight))
train_dataset = torch.utils.data.TensorDataset(data, target)
train_loader = DataLoader(
    train_dataset, batch_size=bs, num_workers=1, sampler=sampler)

without replacement = True , acts same as :

train_loader = DataLoader(
    train_dataset, batch_size=bs, num_workers=1, shuffle=True)

and I cannot figure out how you actually handled unbalanced dataset ?!

No, a weighted sampler without replacement will not act as a random sampler which just shuffles.
It will still use the weights to draw the samples and will thus select samples with a higher weight earlier. However, it will not be able to “oversample” since it cannot re-draw the same sample is replacement=False is used.

I have posted several code snippets in this thread or have linked to other threads which give you a minimal, executable code. E.g. you can run this one and will see that each batch will be balanced when replacement=True. I don’t know where I claimed otherwise.

I also see that you’ve actually responded to the post sharing the code snippet, so did you actually run it?

(I’m @dieas93 with different account )
Here is the output of your code with replacement = False :

target train 0/1: 900/100
batch index 0, 0/1: 56/44
batch index 1, 0/1: 68/32
batch index 2, 0/1: 83/17
batch index 3, 0/1: 95/5
batch index 4, 0/1: 98/2
batch index 5, 0/1: 100/0
batch index 6, 0/1: 100/0
batch index 7, 0/1: 100/0
batch index 8, 0/1: 100/0
batch index 9, 0/1: 100/0

and with replacement = True :

target train 0/1: 900/100
batch index 0, 0/1: 47/53
batch index 1, 0/1: 47/53
batch index 2, 0/1: 53/47
batch index 3, 0/1: 51/49
batch index 4, 0/1: 44/56
batch index 5, 0/1: 59/41
batch index 6, 0/1: 50/50
batch index 7, 0/1: 49/51
batch index 8, 0/1: 45/55
batch index 9, 0/1: 47/53

with no replacement as you said , the network sees samples with higher weight earlier but does it really affect accuracy ? model sees all samples anyway which means samples with lower weight will have more impact on accuracy ( as we can see from outputs ).
even with replacement there is no guarantee that all samples come to play ! based on mathematical view point , higher epochs is needed to make sure model sees all samples at least once.
I think to be 100% sure that the data is balanced in each batch one should define custom Batch Sampler and of course there is no good docs on how to define one !
correct me if I’m wrong

I would guess the order of samples will have an effect on the accuracy, but it’s not creating balanced samples via oversampling and I haven’t seen results on using this approach on tackling an imbalanced dataset issue. The standard approach to create balanced batches is to use a weighted sampler with replacement=True as used in my code snippets.

That is correct and is a shortcoming from the replacement strategy or generally from oversampling minority classes. However, in practice it can still be useful to counter overfitting to the majority class(es) even if more epochs might be needed.

Sure, manually specifying the (balanced) batch indices is also a valid approach. I don’t know if any advantage would be expected and please share results in case you are comparing the custom sampler approach to the standard WeightedRandomSampler balancing approach.

1 Like

If I find a good docs on how to implement such sampler I would definitely try that as well :crossed_fingers:. I have strong feelings that custom sampler approach yields a better result since you can freely define batches containing samples from all categories with same frequency and even use all samples in an epoch.
by the way thanks for the immediate response :+1:

That sounds like a plan and I would be interested in the results to see if the “randomness” of a WeightedRandomSampler would help or if a defined balancing via a custom sampler would yield better results.

I think the best resource are the already implemented samplers from here.
E.g. take a look at the RandomSampler. You would derive your custom sampler from the Sampler base class and implement the __init__, __iter__ and __len__ methods.
In the __init__ you could already create the indices using a custom strategy or just store some arguments (e.g. the generator to seed your code etc.). The __iter__ should yield the indices and the __len__ would return the number of samples.

Also, check BatchSampler which can yield a batch of indices to the Dataset.__getitem__ and might fit your use case better.

1 Like

Check this out :

from itertools import cycle, zip_longest
from random import shuffle

class BalancedSampler(Sampler):

    def __init__(self, dataset):
        class_idxs = {}
        for idx , item in enumerate(dataset):
            if not int(item[1]) in class_idxs.keys():
                class_idxs[int(item[1])] = [idx]
            else:
                class_idxs[int(item[1])] += [idx]

        for key in class_idxs.keys():
            shuffle(class_idxs[key])


        self.seq = []
        for i in self.zip_cycle(*class_idxs.values()):
            self.seq += list(i)

    def __iter__(self) :
        for i in self.seq:
            yield i

    @staticmethod
    def zip_cycle(*iterables, empty_default=None):
        cycles = [cycle(i) for i in iterables]
        for _ in zip_longest(*iterables):
            yield tuple(next(i, empty_default) for i in$

    def __len__(self):
        return len(self.seq)