Implement make_balanced_sampler(labels, num_samples).
labels is a 1-D LongTensor of class labels, one per dataset item. Return a torch.utils.data.WeightedRandomSampler that draws num_samples indices with replacement, giving every class the same expected share.
The weight of item is the inverse frequency of its class:
labels = torch.tensor([0, 0, 0, 1])
sampler = make_balanced_sampler(labels, 4)
sampler.weights # [1/3, 1/3, 1/3, 1]
torch.bincount(labels) gives the count of each class in one call.WeightedRandomSampler(weights, num_samples, replacement=True); weights need not sum to 1.