Complete worked example
python
from bootstrap_lab import torch_setup
torch = torch_setup()
def binary_metrics(predictions, targets):
if len(predictions) != len(targets) or not targets:
raise ValueError('matching nonempty batches required')
if any(type(v) is not int or v not in (0, 1) for v in predictions + targets):
raise ValueError('binary integer classes required')
predicted = torch.tensor(predictions)
actual = torch.tensor(targets)
tp = ((predicted == 1) & (actual == 1)).sum().item()
fn = ((predicted == 0) & (actual == 1)).sum().item()
return {'accuracy': (predicted == actual).float().mean().item(),
'recall': tp / (tp + fn) if tp + fn else None,
'tp': tp, 'fn': fn}- Reasoning
- The helper validates matching nonempty binary integer lists, builds owned tensors and computes accuracy, true positives, false negatives and positive-class recall.