Weighted Random Sampler still unbalanced

I would like to know the original class distribution to check, if your current sampler is changing this distribution at all or not.
Assuming your original imbalance is 9:1, you could compare your code to this one (updated from my previous example for Python3):

numDataPoints = 1000
data_dim = 5
bs = 100

# Create dummy data with class imbalance 9 to 1
data = torch.FloatTensor(numDataPoints, data_dim)
target = np.hstack((np.zeros(int(numDataPoints * 0.9), dtype=np.int32),
                    np.ones(int(numDataPoints * 0.1), dtype=np.int32)))

print('target train 0/1: {}/{}'.format(
    len(np.where(target == 0)[0]), len(np.where(target == 1)[0])))

class_sample_count = np.array(
    [len(np.where(target == t)[0]) for t in np.unique(target)])
weight = 1. / class_sample_count
samples_weight = np.array([weight[t] for t in target])

samples_weight = torch.from_numpy(samples_weight)
samples_weigth = samples_weight.double()
sampler = torch.utils.data.sampler.WeightedRandomSampler(samples_weight, len(samples_weight))

target = torch.from_numpy(target).long()
train_dataset = torch.utils.data.TensorDataset(data, target)

train_loader = torch.utils.data.DataLoader(
    train_dataset, batch_size=bs, num_workers=1, sampler=sampler)

for i, (data, target) in enumerate(train_loader):
    print("batch index {}, 0/1: {}/{}".format(
        i,
        len(np.where(target.numpy() == 0)[0]),
        len(np.where(target.numpy() == 1)[0])))

Which creates 1000 samples, where 900 belong to class0 and 100 to class1.
The output is:

target train 0/1: 900/100
batch index 0, 0/1: 46/54
batch index 1, 0/1: 52/48
batch index 2, 0/1: 49/51
batch index 3, 0/1: 40/60
batch index 4, 0/1: 40/60
batch index 5, 0/1: 54/46
batch index 6, 0/1: 52/48
batch index 7, 0/1: 56/44
batch index 8, 0/1: 61/39
batch index 9, 0/1: 48/52

which shows that each batch is approx. balanced now.

1 Like