Complete worked example
python
from bootstrap_lab import torch_setup
torch = torch_setup()
from torch import nn
def classification_loss(logits, labels):
scores = torch.tensor(logits, dtype=torch.float32)
target = torch.tensor(labels, dtype=torch.long)
if scores.ndim != 2 or target.ndim != 1 or scores.shape[0] != target.shape[0]:
raise ValueError('batch and class axes required')
loss = nn.CrossEntropyLoss()(scores, target)
return {'loss': loss.item(), 'predictions': scores.argmax(dim=1).tolist()}- Reasoning
- The helper creates float32 score tensors and long integer labels, checks the batch axes and computes cross-entropy directly from logits. Argmax over dimension one yields one predicted class per example.