Per-class and per-sample weighting - PyTorch Forums
discuss.pytorch.org › t › per-class-and-per-sampleSep 19, 2018 · batch_size = 10 nb_classes = 2 model = nn.Linear(10, nb_classes) weight = torch.empty(nb_classes).uniform_(0, 1) criterion = nn.CrossEntropyLoss(weight=weight, reduction='none') # This would be returned from your DataLoader x = torch.randn(batch_size, 10) target = torch.empty(batch_size, dtype=torch.long).random_(nb_classes) sample_weight = torch.empty(batch_size).uniform_(0, 1) output = model(x) loss = criterion(output, target) loss = loss * sample_weight loss.mean().backward()