exacta
Metrics and differentiable losses for 2D and 3D medical-image segmentation, on CPU and GPU.
Exacta provides reusable implementations of Dice, HD95, surface distances, lesion scores,
probability metrics and training objectives, with explicit mathematical conventions.
Version 0.0.1a6 adds general classification and regression APIs, instance-map evaluation,
Betti errors, dataset-pooled overlap and further segmentation losses.
CPU operations use C++ kernels where implemented; CUDA paths use Triton or native PyTorch.
Definitions are checked against independent references such as SciPy, MONAI, MedPy,
DeepMind's surface-distance, MeshMetrics, SimpleITK, Panoptica and the BraTS 2023 evaluation
code. Where conventions differ, parameters select the intended definition.
Published version: 0.0.1a6 (alpha).
Documentation ·
Source ·
Issues
Installation
Exacta requires Python 3.10+, PyTorch 2.4+ and NumPy 1.22+. Install PyTorch for
your CPU or CUDA environment, then install Exacta:
python -m pip install exacta==0.0.1a6
Binary wheels target Linux x86-64 with glibc 2.28 or newer: Python 3.10 and 3.11 wheels,
plus a Python 3.12 stable-ABI wheel for Python 3.12 and newer. Other platforms install
from source and require a C++17 compiler and Python development headers; OpenMP is optional.
SciPy is an optional dependency for Hungarian lesion matching.
For distributed CPU evaluation with Gloo, use PyTorch 2.8+ to avoid an older
process-group teardown deadlock. Multi-GPU NCCL support remains experimental.
Quickstart
Train with logits and evaluate hard labels. This synthetic 3D example runs on the available
CPU or CUDA device; it demonstrates the API, not model accuracy:
import torch
import exacta.functional as EF
from exacta.losses import DiceCELoss
rng = torch.Generator().manual_seed(7)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
logits = torch.randn((2, 3, 16, 24, 24), generator=rng).to(device).requires_grad_()
target = torch.zeros((2, 16, 24, 24), dtype=torch.long, device=device)
target[:, 3:8, 4:12, 5:13] = 1
target[:, 9:13, 12:20, 12:20] = 2
loss = DiceCELoss(include_background=False)(logits, target)
loss.backward()
prediction = logits.detach().argmax(dim=1)
scores = EF.evaluate(
prediction, target, num_classes=3, include_background=False,
spacing=(1.5, 0.8, 0.8), # spatial-axis order, in mm
metrics={"dice": {}, "hd95": {}, "nsd": {"tolerance": 1.0}},
)
print("Loss:", loss.item())
print("Dice per case/class:", scores["dice"]) # shape (2, 2)
print("HD95 in mm:", scores["hd95"])
For 2D images, use logits (B,C,H,W), integer targets (B,H,W) and two-axis spacing.
For independent overlapping labels, supported losses use activation="sigmoid" and
target_format="one-hot" with same-shaped binary targets. The
2D medical-segmentation guide
includes binary, multiclass and multilabel examples.
Metrics
Stateless functions live in exacta.functional. Their stateful counterparts in
exacta.metrics accumulate across batches and support distributed evaluation.
| Category |
Metrics |
| Overlap |
Dice / voxel F1; IoU / Jaccard |
| Classification rates |
Sensitivity / recall; precision; specificity |
| Relative size |
Volume similarity; signed or absolute relative volume difference |
| Physical size |
Predicted/target 3D volume and error in mm³ or mL; 2D area and error in mm² or cm² |
| Boundaries |
Hausdorff distance with configurable percentile; HD95; ASSD; normalized surface Dice (NSD) |
| Centreline |
Hard-skeleton clDice |
| Probability quality |
Brier score; negative log-likelihood (NLL) |
| Calibration |
Expected calibration error (ECE); reliability diagrams |
| Voxel ranking |
Average precision (AP); AUROC; precision–recall and ROC curves, exact or approximately binned |
| Lesion matching |
Lesion TP/FP/FN, precision, recall, F1, segmentation quality and panoptic quality |
| Lesion segmentation |
Lesion-wise Dice and HD95; BraTS 2023 evaluation conventions |
| Confidence-ranked detection |
Lesion AP and FROC curves |
Use exacta.lesions.evaluate for lesion matching and exacta.detection.LesionDetection
for confidence-ranked detection. Connected-component labeling, largest-component selection
and small-component removal are available in exacta.components.
functional.evaluate and MetricCollection share confusion counts and compatible surface
distances when evaluating multiple metrics. For accumulation across validation batches:
from exacta.metrics import MetricCollection
metrics = MetricCollection(
metrics={"dice": {}, "hd95": {}}, num_classes=3, include_background=False,
)
metrics.update(prediction, target, spacing=(1.5, 0.8, 0.8))
result = metrics.compute()["dice"]
print(result.per_case, result.per_class, result.mean)
metrics.reset()
Functional APIs accept PyTorch, NumPy, CuPy and JAX arrays and return the prediction's array
type. Stateful APIs use PyTorch. See Metrics
and Lesion evaluation for
arguments, formulas and matching protocols.
Training losses
Losses are PyTorch modules in exacta.losses. Choose the objective and target representation
explicitly; different loss definitions produce different gradients.
| Category |
Classes |
| Overlap |
DiceLoss, GeneralizedDiceLoss, TverskyLoss, FocalTverskyLoss |
| Class-confusion costs |
GeneralizedWassersteinDiceLoss |
| Voxel classification |
FocalLoss, TopKCELoss |
| Combined objectives |
DiceCELoss, DiceFocalLoss, GeneralizedDiceCELoss, DiceTopKCELoss |
| IoU surrogates |
LovaszSoftmaxLoss, LovaszHingeLoss |
| Boundary objectives |
BoundaryLoss, HausdorffDTLoss |
| Soft centreline objective |
SoftClDiceLoss |
DeepSupervisionLoss combines a loss across explicitly paired prediction/target resolutions.
DiceLoss(squared_pred=True) uses a squared denominator; Dice–CE, Dice–focal and Dice–top-k CE
support the same option. Generalized Dice supports inverse-square, inverse-volume and uniform
class weights. Standard cross-entropy and binary cross-entropy remain available in PyTorch.
Wasserstein Dice accepts integer labels and a symmetric, nonnegative class-cost matrix with
zero diagonal and a positive maximum. The matrix is normalized by that maximum. Default
weighting requires maximal background/foreground costs; weighting_mode="GDL" uses inverse
observed class counts. These costs describe label confusion, not spatial distance.
HausdorffDTLoss is a distance-transform training surrogate, not HD95. Soft-clDice uses a
finite-iteration soft skeleton and differs from the hard clDice evaluation metric. Geometry
and topology objectives require complete target geometry; combine them with regional
supervision where appropriate. See Losses
for equations, smoothing, reductions, target formats and derivative support.
Instances, topology and pooled overlap
Version 0.0.1a6 adds the following segmentation APIs.
| API |
Purpose |
aggregate="pooled" in Dice, IoU, FBeta, Sensitivity, Precision, Specificity and MetricCollection |
Dataset-pooled counts: global Dice, per-class IoU and mIoU (mmsegmentation convention) |
functional.fbeta, metrics.FBeta |
F-beta per case and class; beta=1 is Dice |
functional.confusion_counts |
Per-case TP/FP/FN/TN for custom definitions and pooling |
exacta.instances |
Instance label maps with touching instances: PQ/SQ/F1, AJI, AJI+, Cell Tracking Challenge SEG, Data Science Bowl 2018 score; per-case or pooled accumulation |
functional.betti_numbers, betti_error, metrics.BettiError |
Betti numbers (components, holes/tunnels, cavities) and Betti errors in 2D/3D |
skeletonize(method=...), cldice(method=...) |
Zhang thinning in C++; 2D clDice now uses it by default, as the clDice authors do (method="lee" reproduces 0.0.1a5) |
losses.SkeletonRecallLoss, skeleton_recall_target |
Skeleton Recall for thin tubular structures, with the authors' tubed skeleton targets |
soft_label=True in Dice, Tversky, generalized Dice and their CE/focal combinations |
Dice semimetric statistics: minimal at the soft target, identical for hard labels |
import torch
from exacta import instances
from exacta.metrics import IoU
pred_instances = torch.tensor([[[1, 1, 0, 2, 2], [1, 1, 0, 2, 2]]])
true_instances = torch.tensor([[[3, 3, 0, 4, 4], [3, 3, 0, 0, 4]]])
scores = instances.evaluate(pred_instances, true_instances) # IoU > 0.5 matching
print(scores.pq, scores.aji, scores.seg)
miou = IoU(num_classes=3, aggregate="pooled")
miou.update(torch.tensor([[[0, 1], [2, 2]]]), torch.tensor([[[0, 1], [2, 1]]]))
print(miou.compute().per_class, miou.compute().mean)
Pooled scores weight every voxel equally and differ from case means. Instance matching above
0.5 IoU is unique; lower thresholds and AJI follow documented reference procedures. See
Metrics,
Instance evaluation,
Losses and
Advanced segmentation
for definitions, empty-input behavior and references.
Classification and regression
These APIs evaluate samples across a dataset, with separate namespaces from the per-image
segmentation metrics.
| Namespace |
Metrics or losses |
functional.classification |
Accuracy, top-k accuracy, confusion matrices, precision, recall, specificity, F1/F-beta, balanced accuracy, MCC, Cohen kappa, Brier, NLL, ECE, AP and AUROC |
functional.regression |
MAE, MSE, RMSE, R², explained variance, Pearson and concordance correlation |
metrics.classification |
ClassificationMetrics for pooled counts; ClassificationRanking for pooled AP/AUROC and PR/ROC curves |
metrics.regression |
RegressionMetrics for pooled weighted errors and centered moments |
losses.classification |
Native PyTorch CrossEntropyLoss, BCEWithLogitsLoss, BCELoss, NLLLoss, KLDivLoss |
losses.regression |
QuantileLoss, LogCoshLoss; native PyTorch L1Loss, MSELoss, HuberLoss, SmoothL1Loss, GaussianNLLLoss, PoissonNLLLoss |
Classification explicitly selects binary, multiclass or multilabel targets. Regression
accepts (N,) or (N,D) arrays. Masks and sample weights are available for hard-decision
classification and regression metrics; probability metrics currently accept masks but
not sample weights. Stateful metrics pool sufficient statistics before computing scores.
They do not average batch F1, R² or RMSE. CPU regression uses fused C++ statistics;
CUDA regression uses native PyTorch. Standard losses are direct PyTorch exports.
import torch
from exacta.functional import classification as C, regression as R
from exacta.metrics.regression import RegressionMetrics
labels = torch.tensor([0, 1, 2, 1])
class_target = torch.tensor([0, 2, 2, 1])
print(C.evaluate(labels, class_target, task="multiclass", num_classes=3))
regression_pred = torch.tensor([1., 2., 4., 5.])
regression_target = torch.tensor([1., 3., 5., 4.])
print(R.evaluate(regression_pred, regression_target))
regression_metrics = RegressionMetrics(metrics=("mae", "rmse", "r2"))
regression_metrics.update(regression_pred[:2], regression_target[:2])
regression_metrics.update(regression_pred[2:], regression_target[2:])
print(regression_metrics.compute())
Undefined classification rates default to NaN; zero_division=0 or 1 is explicit.
Regression R² preserves undefined constant-target cases unless force_finite=True.
See classification
and regression
for formulas, averaging, empty-input behavior and examples.
Partial annotations and probability channels
Overlap, area and volume metrics accept shared boolean voxel masks and index-target
ignore_index. Excluded voxels contribute to none of TP, FP, FN or TN:
partial_target = target.clone()
partial_target[:, :2] = -1
observed_dice = EF.dice(
prediction, partial_target, num_classes=3, include_background=False, ignore_index=-1,
)
Surface and hard-clDice metrics require complete segmentations: removing voxels would change
boundaries or topology. Loss masking follows each objective's documented rules.