Sorry I didn’t explained clearly, I tried WeightedSampler and WeightedLoss respectively, not use them both. Here is my code

WeightedSampler

train_labels = np.array(train_dataset.imgs)[:,1]
count_labels = torch.tensor([(train_labels==i).sum() for i in range(100)]) # 100 classes
weight = 1. / count_labels.float()
samples_weight = torch.tensor([weight[i] for i in train_labels])
weight_sapmler = torch.utils.data.sampler.WeightedRandomSampler(samples_weight, len(train_labels))
train_loader = torch.utils.data.DataLoader(
            train_dataset, batch_size=batch_size,
            sampler=weight_sapmler,
            num_workers=2, pin_memory=pin_memory)


WeightedLoss

labels = np.array(train_loader.dataset.imgs)[:,1]
weight = []
for i in range(100): # 100 classes
    weight.append(1./(labels==str(i)).sum().item())
weight = torch.Tensor(weight).float()
criterion = torch.nn.CrossEntropyLoss(weight=weight).to(device)

Is there any errors in my code?
Best regards,
marsggbo