wrapper for cross entropy loss in pytorch. Args logits: logit values, shape=[Batch size, # of classes] targets: integer or vector, shape=[Batch size] or [Batch size, # of classes] use_hard_labels: If True, targets have [Batch size] shape with int values. If Fals
(logits, targets, use_hard_labels=True, reduction='none')
| 293 | |
| 294 | |
| 295 | def ce_loss(logits, targets, use_hard_labels=True, reduction='none'): |
| 296 | """ |
| 297 | wrapper for cross entropy loss in pytorch. |
| 298 | |
| 299 | Args |
| 300 | logits: logit values, shape=[Batch size, # of classes] |
| 301 | targets: integer or vector, shape=[Batch size] or [Batch size, # of classes] |
| 302 | use_hard_labels: If True, targets have [Batch size] shape with int values. If False, the target is vector (default True) |
| 303 | """ |
| 304 | if use_hard_labels: |
| 305 | log_pred = F.log_softmax(logits, dim=-1) |
| 306 | return F.nll_loss(log_pred, targets, reduction=reduction) |
| 307 | # return F.cross_entropy(logits, targets, reduction=reduction) this is unstable |
| 308 | else: |
| 309 | assert logits.shape == targets.shape |
| 310 | log_pred = F.log_softmax(logits, dim=-1) |
| 311 | nll_loss = torch.sum(-targets * log_pred, dim=1) |
| 312 | return nll_loss |
| 313 | |
| 314 | |
| 315 | # class EMA: |
no outgoing calls
no test coverage detected