Evaluation

Scoring is two verbs with one noun between them. soma.predict() runs a model over a loader and returns Predictions: one row per sample, with the columns the task head declares. soma.evaluate() joins those predictions with the cohort’s targets by sample_id and returns an Evaluation. Targets never travel inside predictions: they come from soma.data.Cohort.targets(), so predictions saved by a run, or made outside soma, are scored the same way.

soma.predict() runs the model where its parameters live, or on the device it is given ("auto", "cpu", "cuda:1"). A model with no parameter runs on the GPU when there is one. A run predicts on its trainer.device.

Score predictions

import soma

cohort = soma.Cohort.from_csv("dataset.csv", "splits.csv", targets=["label"])
predictions = soma.Predictions.from_parquet("run/predictions_test.parquet")
# or, after soma.fit: predictions = soma.predict(result.learner, fold.tests["test"])
evaluation = soma.evaluate(
    predictions,
    cohort.targets("test"),
    metrics=["auroc", "balanced_accuracy"],
    subgroups=["center"],
)
evaluation.to_json("evaluation.json")

evaluate scores exactly the ids it is given. It refuses a prediction without a target and duplicate ids. For a target without a prediction, the unpredicted policy decides:

  • "error" (the default) refuses to score. The error names the samples and the two ways forward: remove them from the cohort or the splits (or filter the targets), or set unpredicted="exclude".

  • "exclude" scores the predicted samples only.

The metrics always hold three counts: num_samples (the targets), num_predicted and coverage (num_predicted / num_samples). A coverage below 1 means the metrics leave samples out, so two evaluations with different coverage may not score the same samples.

soma evaluate does the same from the command line, with --unpredicted (see CLI), without a run directory.

predict writes side artefacts through callbacks (see Callbacks on fit and on predict): soma.evaluation.heatmaps.SaveAttention(dir) writes each bag’s normalised tile attention to <dir>/<sample_id>.npz.

Samples without features

A slide whose tiling kept no tile has no features, so the model cannot predict it. The feature manifest records it as empty. Neither has a sample of any other status but success, such as an extraction error. A run never invents a prediction for such a sample:

  • In the train split, the sample is left out of training, and the fold’s log line counts it. The policy below does not apply to train samples.

  • In a tune or test split, the sample is a target without a prediction. evaluation.unpredicted decides what happens. It takes the same values as soma.evaluate:

    evaluation:
      unpredicted: exclude   # the default is error
    

    With error, the run stops at fold setup, after feature extraction and before any training. The error names the samples of every fold. With exclude, each split is scored over the samples the model predicted. At the end of the run, a warning names each split whose coverage is below 1. The run-summary panel shows the coverage of the splits in the run summary, and soma leaderboard shows that of the split it ranks on (see the summary keys).

Next to the predictions of each test split, a slide, patient or tile run writes not_predicted_<split>.parquet: one row per sample the model could not predict, with sample_id and reason: no tiles for an empty sample, else the feature status, such as feature status 'error'. The file is written even when it has no row. Segmentation and detection runs have no such file: their predictions cover every sample of their targets, so they refuse unpredicted: exclude.

soma.evaluation.compare() takes no policy: every prediction set must predict every target. To compare sets that miss different samples, filter the targets and the sets to the ids that every set predicts.

Migration

Earlier versions filled each sample without features with a constant fitted on the train split (the class prior, the mean value, or a risk of 0.0), and scored these rows with the real predictions. This fill is removed, with soma.evaluation.Baseline, the is_placeholder column of the predictions, and the num_real_samples and num_placeholder_samples metric keys:

  • A run with a tune or test sample without features now stops by default. Remove the sample from the cohort or the splits, or set evaluation.unpredicted: exclude.

  • With exclude, the metrics of such a run change: the filled rows no longer count. Read num_predicted where you read num_real_samples.

  • Code that filled predictions before soma.evaluate() passes unpredicted="exclude" instead, or filters the targets.

  • A predictions file an earlier version wrote with filled rows is refused: drop the rows flagged is_placeholder, then score the rest.

Choose metrics

metrics is "default" (the family’s defaults, listed in the task zoo), or a list of registry keys, dotted import paths and (predictions, targets) -> float callables. A callable receives the two frames aligned by sample_id, with labels already mapped to class indices. soma.evaluation.metric_registry lists each metric’s families and direction; a key outside the predictions’ family is refused. In a config, evaluation.metrics takes the built-in names of the head’s family (an empty list means the defaults); score a metric of your own from Python, or with soma evaluate --metrics by its dotted path.

soma.evaluation.compare() runs a paired permutation test of several prediction sets against the best one.

Subgroup metrics

evaluation.subgroups names dataset.csv columns whose distinct values receive their own metrics:

evaluation:
  subgroups: [center, grade]

Each distinct value of a column is a group. A run scores the groups after the fit, on tune and on each test split, and at every evaluated epoch during training. Subgroups are for the set shape; the grid shape refuses them. The plan also refuses a column name or a value that contains / or =, because the names below cannot hold it: rename it. It also refuses a column with the name of one of the head’s target keys (label, time, event, …), even if the head reads that target from another column: rename the metadata column.

After the fit

For each column, every group with at least two samples gets the run’s metrics and its sample count, and the column gets the unweighted mean of each metric over its groups. A significance test then compares each group with the rest of the split by permuting group membership 1,000 times; it needs at least 10 samples in the group and two in the remainder. Patient-level runs read each patient’s metadata from its first slide. Each fold writes the results to subgroup_metrics_<split>.json for tune, with or without holdout_test, and for each test split the run scores:

{
  "metrics": {"center": {"A": {"auroc": 0.812, "n": 40}, "B": {"auroc": 0.706, "n": 35}}},
  "mean_over": {"center": {"auroc": 0.759, "auroc_groups": 2}},
  "stats": {"center": {"A": {"auroc": 0.214}, "B": {"auroc": 0.221}}}
}

stats holds the p-values of the significance test. A group whose metric is NaN, such as an AUROC over one class or a C-index without comparable pairs, is left out of the mean, and <metric>_groups counts the groups that are in it. With no finite group, the mean is NaN.

summary.json holds the same values under the split’s name: test/center=A/auroc for one group and test/mean_over_center/auroc for the mean, with _mean, _std and _nan_folds over several folds (see the summary keys). The sample counts, the _groups counts and the p-values stay in the file.

During training

At every evaluated epoch, the trainer also scores each group of the tune split, and of the train split when trainer.eval_train is on (see The train pass). For each column it logs the loss and the metrics of each group, and their unweighted mean over the column’s groups:

  • tune/<column>=<group>/loss and tune/<column>=<group>/<metric>;

  • tune/mean_over_<column>/loss and tune/mean_over_<column>/<metric>, with <name>_groups counting the groups in each mean;

  • the same names under train/ with the train pass.

The rules are the same as after the fit: a group needs two samples, and a NaN group is left out of the mean. These values go to training_history.json (see Logged values); the progress panel shows only the pooled values and the monitors. They cover the samples with features, as the scores after the fit do (see Samples without features).

A tune mean over groups can be the monitor (see Monitors), but the value of one group cannot: a fold’s tune split can lack the group.

evaluation:
  subgroups: [center]
trainer:
  callbacks:
    - {name: checkpoint, params: {monitor: tune/mean_over_center/auroc, mode: max}}
    - {name: early_stopping, params: {monitor: tune/mean_over_center/auroc, mode: max}}

A group’s loss is the head’s loss over the samples of the group alone, as tune/loss is the loss over the whole split. For a loss that is a mean over samples, it is the mean of the group’s per-sample losses. For a Cox head, it is the partial-likelihood loss over the group’s own risk sets: each group is a stratum. The groups’ losses then do not average to tune/loss, whose risk sets span the whole split. The loss of a group without an event is NaN, and the mean over groups leaves it out.

A learner needs the subgroup_summary hook to run with subgroups. The mil learner has it; a custom learner may need to add it (see A custom learner).

Holding out test data

Set evaluation.holdout_test: true to train and report tune results without test inference or test artifacts. Checkpoint selection and tune evaluation continue normally. This supports selecting a candidate on tune results before evaluating it on the held-out test cohort. summary.json then holds the tune metrics, subgroups included, under tune/. Without holdout_test, it holds the test splits only.

Test identities are recorded in test_results.json. Re-scoring an already recorded test identity is skipped unless evaluation.overwrite_test: true; resuming unfinished folds is allowed. See Run outputs for experiment identity.

Segmentation and detection predictions

For a segmentation or detection head, soma.predict() runs the head’s postprocess and returns one of two prediction types instead of a table, and soma.evaluate() scores it against a target source rather than a targets frame:

LabelMapPredictions

PointPredictions

Holds

One (H, W) uint8 label map per sample

A frame sample_id, x, y, class, score in level-0 pixels, plus every sample id (a sample with no detection is still scored)

Saved as

save(dir): one PNG per sample and index.parquet; load(dir) reads it back

to_parquet(path) / from_parquet(path)

Scored against

LabelMapSource or CachedLabelMapSource

PointSource

Metrics

mean_dice, mean_iou, dataset_global_mean_dice, foreground_mean_dice, dice_per_class

mean_f1, f1_per_class, precision, recall, mean_f1_per_image

Label maps are scored from per-sample confusion counts. Points are matched to the annotations per class within the matching distance δ, with Hungarian assignment by default. A metric given as a {name, params} leaf can change the matching: matching: greedy matches by descending score, and match_distance overrides δ (in level-0 pixels).

Point predictions keep every peak above the head’s min_score. Choosing an operating point is a separate step: with_threshold takes one threshold or a {class: threshold} mapping, and sweep_threshold() picks the threshold that maximises a metric on the given targets (one per class with per_class=True). Sweep on tune and apply the result to test:

import soma
from soma.evaluation import PointPredictions, sweep_threshold

targets = soma.data.PointSource.from_manifest(soma.AnnotationManifest.from_csv("dataset.csv"))
tune = PointPredictions.from_parquet("run/predictions_tune.parquet")
test = PointPredictions.from_parquet("run/predictions_test.parquet")

threshold, _ = sweep_threshold(tune, targets.subset(tune.sample_ids), per_class=True)
evaluation = soma.evaluate(
    test.with_threshold(threshold),
    targets.subset(test.sample_ids),
    metrics=[{"name": "mean_f1", "params": {"matching": "greedy"}}],
)

Grid predict callbacks write side artefacts: SaveOverlays (predictions and supervision drawn over the tile), SaveProbabilities (per-sample float16 softmax, segmentation) and SaveHeatmaps (per-sample float16 heatmaps, detection), for example soma.predict(learner, loader, [SaveOverlays("overlays/test", images=images)]).

Per-sample confusion matrices are recomputable from saved label maps with soma.evaluation.confusion_records().

soma evaluate also accepts a label-map directory or a points parquet. It scores label maps against the masks in the cohort CSV’s label_mask_path column and points against the files in its points_path column; both must already hold class indices. --threshold keeps the points scoring at least that value.

soma evaluate also scores the label TIFFs and points files that soma predict writes over whole slides. See Whole-slide inference for the rules: pixels that were not predicted, ignore masks, thresholds, and why slide scores are not comparable to a run’s test metrics.

Reference

class soma.config.EvaluationConfig(metrics=<factory>, subgroups=<factory>, unpredicted='error', holdout_test=False, overwrite_test=False, save_overlays=True, save_probabilities=False, save_heatmaps=False, attention_heatmaps=None, representation=None)

Bases: Editable

evaluation: soma.evaluate()’s metrics, subgroups (columns) and unpredicted policy, and what a run scores and saves. unpredicted decides what a tune or test sample without features does (set shape): error stops the run before any fold trains, exclude scores the predicted samples only. holdout_test skips test work; overwrite_test re-scores a test set. The grid shape saves overlays, the segmentation softmax and the detection heatmaps; attention_heatmaps (cmap, alpha, blur_sigma) renders tile attention; representation makes the run a task-free CRoMa evaluation.

soma.evaluation.predict(learner_or_model, loader, callbacks=(), *, device=None)

Predict every sample of loader.

A bare model is wrapped in its shape’s learner (soma.learn.learner_for()). The learner runs in eval mode under torch.inference_mode on device ("auto", "cpu", "cuda:1"…), moved there first. Without one it runs where its parameters live, and a learner with no parameter runs as "auto": on the GPU when there is one. Each batch goes through transfer_batch and predict_step. For the set shape the frame is built from the step’s columns only, in loader order, and the head’s task_family, prediction_columns and classes describe it: a Predictions. A grid head (one declaring target_kind) assembles its own noun from the per-sample outputs (assemble_predictions): LabelMapPredictions or PointPredictions, covering every sample of the loader.

soma.evaluation.evaluate(predictions, targets, metrics='default', subgroups=(), *, unpredicted='error')

Score predictions against targets; the prediction noun picks the scoring.

  • Predictions (set shape) against a targets frame such as soma.data.Cohort.targets(), joined by sample_id.

  • PointPredictions against a PointSource: class-aware point matching within the predictions’ match_distance_px (Hungarian by default; a metric leaf with params matching="greedy" / match_distance in level-0 px overrides).

  • LabelMapPredictions against a LabelMapSource: per-image confusion counts reduced to Dice, IoU and the per-class scores.

  • SlideLabelMaps (the label TIFFs of soma.predict_slides()) against a LabelMapSource of the slides’ annotation rasters: both read window by window (the map only where the window holds an annotated pixel), one row of counts per slide in Evaluation.per_sample, then the same reducers.

  • SlidePoints (the points parquets of soma.predict_slides()) against a PointSource of the slides’ annotated points: the class scheme and the threshold the points record, matching within the bundle’s distance in µm (a match_distance param is in µm too), one row of counts per slide in Evaluation.per_sample. The rows use the matching and match_distance every metric names; the default (Hungarian, at the bundle’s distance) when the metrics name none, or name different ones.

A prediction without a target and a duplicate id are refused. unpredicted says what a target without a prediction does (set shape): "error" refuses to score and names the samples, "exclude" scores the predicted samples only. Set-shape metrics always hold num_samples (the targets), num_predicted and coverage (their ratio, 1.0 for no target). Grid predictions must cover their target source: restrict it with subset.

Parameters:
  • predictions – What the model said.

  • targets – One row per sample, indexed by sample_id (or with a sample_id column), holding the target columns of the predictions’ family and any metadata columns subgroups names; a target source for grid nouns.

  • metrics (str | Sequence[str | Callable[[DataFrame, DataFrame], float]] | None) – "default" (the family’s catalogue defaults; mean_pearson for a multi-output regression’s value_<k> columns) or a list of registry keys, {name, params} leaves (grid), dotted paths and callables.

  • subgroups (Sequence[str]) – Target columns to break the metrics down by (set shape only).

  • unpredicted (str) – "error" (default) or "exclude", for targets without a prediction (set shape only).

Return type:

Evaluation

class soma.evaluation.Predictions(frame, *, task_family, prediction_columns=None, classes=None)

Bases: object

A frame of per-sample predictions keyed by sample_id.

Parameters:
  • frame (DataFrame) – One row per predicted sample: a sample_id column, the declared prediction columns, and any extra columns a custom learner adds.

  • task_family (str) – The head’s task_family; it selects the metrics that apply.

  • prediction_columns (Sequence[str] | None) – The columns the head declares. Defaults to every column of frame except sample_id.

  • classes (Sequence[Any] | None) – The raw label of each class index, in prob_<i> order. With it, evaluate() maps the cohort’s raw labels onto class indices; without it, labels must already be integer class indices.

class soma.evaluation.Evaluation(metrics, task_family, num_samples, subgroups=<factory>, per_sample=<factory>)

Bases: object

The scores of one set of predictions.

metrics maps each metric to its value; set-shape metrics also hold num_samples (the targets, as the num_samples field), num_predicted and coverage. subgroups holds the per-column, per-group metrics, their mean over each column’s groups and the permutation p-values ({"metrics": ..., "mean_over": ..., "stats": ...}, empty without subgroup columns). per_sample holds one row of counts per slide for SlideLabelMaps and SlidePoints, and is empty otherwise.

soma.evaluation.compare(predictions_list, targets, metric, *, n_permutations=1000, seed=42)

Paired permutation test of each prediction set against the best one.

Every set is aligned to targets as in evaluate(), strictly: a set that misses a target is refused, so filter the targets and the sets to the ids every set predicts. Sets declaring different classes (including a set without classes next to one with) are refused. For each permutation the prediction columns of the best set and another are swapped on a random half of the samples and the metric delta recomputed. The best set gets 1.0; a set whose metric cannot be computed, or that lacks one of the best set’s prediction columns, gets None.

Return type:

list[float | None]

class soma.evaluation.LabelMapPredictions(label_maps, *, classes, ignore_index=255, geometry=None)

Bases: object

One predicted (H, W) uint8 label map per sample, held in memory.

Parameters:
  • label_maps (Mapping[str, Any]) – {sample_id: (H, W) uint8}.

  • classes (Sequence[Any]) – The name of each class index.

  • ignore_index (int) – The value targets use for unsupervised pixels.

  • geometry – The producing head’s GridGeometry, if any.

class soma.evaluation.SlideLabelMaps(directory, *, window_px=1024, num_workers=0)

Bases: object

The label TIFFs soma.predict_slides wrote for one bundle, or for one ensemble.

directory is a prediction output directory with the maps of one bundle, or one of its per-bundle directories; either is recognised by the output’s index.parquet. A slide is predicted when its <sample_id>.json record exists and parses.

Pass the handle to soma.evaluate() with a LabelMapSource of the slides’ annotation rasters, aligned to the slides (built with an ImageManifest). Only the source’s rasters, slides and backends are used: the class scheme comes from the maps. window_px is the side of the window both rasters are read in, rounded down to a whole number of tile strides; it bounds the memory a slide takes, not the scores. A window with no annotated pixel is not read from the map.

num_workers is the number of worker processes that score the slides, one slide at a time each; 0 scores them in the main process. Like window_px, it changes the resources scoring takes, not the scores: the counts and the rows keep the order of sample_ids. The workers start with the spawn method and open their own readers, with the source’s backends. A slide that fails stops the other workers, and its error is raised as in the main process.

class soma.evaluation.SlidePoints(directory, *, mask_backend=None)

Bases: object

The points parquets soma.predict_slides wrote for one bundle, or for one ensemble.

directory is a prediction output directory with the points of one bundle, or one of its per-bundle directories; either is recognised by the output’s index.parquet. A slide is predicted when its <sample_id>.json record exists and parses.

Pass the handle to soma.evaluate() with a PointSource of the slides’ annotated points. Only the source’s points files and ignore masks are used: the class scheme comes from the points files. mask_backend is the hs2p reader of the ignore masks; by default the one the prediction’s plan.yaml records.

A bundle’s points are scored at the threshold the bundle recorded on its tune split. An ensemble’s points record none: pick one with sweep_threshold() or set one with with_threshold().

class soma.evaluation.PointPredictions(frame, *, classes, sample_ids, match_distance_px, threshold=None)

Bases: object

Detected points of a set of samples, in level-0 pixels.

Parameters:
  • frame (DataFrame | None) – One row per detection: sample_id, x, y, class, score. None or an empty frame when nothing was detected.

  • classes (Sequence[Any]) – The name of each class index.

  • sample_ids (Sequence[str]) – Every sample the predictions cover, including those without a detection; evaluate holds them to the targets’ id set.

  • match_distance_px (float) – The matching tolerance δ in level-0 pixels (the producing head’s match_distance at its spacing).

  • threshold (float | Mapping[int, float] | None) – The score threshold already applied (informational), or None.

soma.evaluation.sweep_threshold(predictions, targets, metric='mean_f1', grid=None, *, per_class=False, matching='hungarian', match_distance=None)

Pick the score threshold that maximises metric on targets.

Returns (threshold, Evaluation) with the evaluation of the thresholded predictions. per_class=True picks one threshold per class (returned as {class_index: t}) maximising that class’s F1, which also maximises mean_f1 (class-aware matching makes each class’s F1 depend on its own points only); it supports metric="mean_f1". grid lists the candidate thresholds; by default the candidates are score quantiles and a uniform grid over the observed scores, plus (per class) quantiles of the scores of points within δ of a same-class annotation, bracketed by keep-all and drop-all. Ties keep the higher threshold. A per-class sweep with matching="greedy" and no grid is instead exact on the 1 / SCORE_BINS grid over [0, 1] (scores must lie there): one greedy matching pass gives the F1 at every threshold, as in the detection head’s training-time validation.

predictions may also be SlidePoints, against a PointSource of the slides’ annotated points. The sweep ignores the threshold the points record, so it also picks one for an ensemble’s points, which record none. match_distance is then in µm. Set the picked threshold with with_threshold().

soma.evaluation.confusion_records(predictions, targets, *, fold=0)

Per-sample confusion records recomputed from saved label maps.

predictions is a LabelMapPredictions (e.g. a run’s predictions_tune/), targets the label-map source it was scored against. Pixels at the predictions’ ignore_index in the target count nowhere. The class vocabulary is the predictions’ classes; a label outside it on a supervised pixel raises ValueError naming the sample.

Return type:

list[SegmentationConfusionRecord]