HEvaluate predictions · evaluate.segments
Segmentation quality (IoU, Dice, segment F1)
How well do predicted masks or time segments cover the reference, class by class?
Scores segmentations against a reference. For image masks (COCO run-length strings): pixel accuracy, intersection over union and Dice per class, mean IoU, mean Dice and frequency-weighted IoU, with an optional background class and crowd regions left out of scoring. For time intervals (start and end per segment, as in audio events, diarization or video actions): time-weighted IoU and Dice per class, segment matching at chosen IoU thresholds (precision, recall and segmental F1) and, with confidence scores, average precision per class and threshold. Reads reference and predicted rows stacked in one table, told apart by a source column, or the predictions with the reference in a table of its own.
A real result
Example “Masks background crowd”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
Across 10 images and 5 classes, mean IoU = 0.495, mean Dice = 0.598 and pixel accuracy = 0.773.
- Mean IoU
- 0.4946
- Mean Dice
- 0.5977
- Pixel accuracy
- 0.7735
Plots
View data
| label | Measure | Overlap |
|---|---|---|
| bicycle | IoU | 0.4855 |
| bicycle | Dice | 0.6537 |
| car | IoU | 0.3877 |
| car | Dice | 0.5588 |
| dog | IoU | 0 |
| dog | Dice | 0 |
| person | IoU | 0.8472 |
| person | Dice | 0.9173 |
| (background) | IoU | 0.7525 |
| (background) | Dice | 0.8588 |
Assumptions
- The reference is complete — Regions or segments missing from the reference turn correct predictions into errors.
- Reference classes don't overlap — Where reference regions of two classes overlap, the shared part counts for both; accuracy then divides by more than the scored area.
Per class (pixels summed over images)
| label | Reference pixels | Predicted pixels | Overlap (pixels) | IoU | Dice |
|---|---|---|---|---|---|
| bicycle | 9,844 | 14,196 | 7,857 | 0.4855 | 0.6537 |
| car | 59,682 | 26,067 | 23,959 | 0.3877 | 0.5588 |
| dog | 0 | 3,012 | 0 | 0 | 0 |
| person | 33,581 | 30,231 | 29,266 | 0.8472 | 0.9173 |
| (background) | 102,433 | 125,542 | 97,893 | 0.7525 | 0.8588 |
Mean IoU per image
| media_id | Mean IoU |
|---|---|
| img01 | 0.5896 |
| img02 | 0.6133 |
| img03 | 0.3908 |
| img04 | 0.3639 |
| img05 | 0.6776 |
| img06 | 0.6747 |
| img07 | 0.4281 |
| img08 | 0.8811 |
| img09 | 0.4880 |
| img10 | 0.1023 |
- Reference rows: source = annotation; predictions: source = prediction. Masks are compared on their run lengths (no pixels decoded); unlabeled pixels form a background class; crowd regions are left out of scoring.
Across 10 images and 5 classes, mean IoU = 0.495, mean Dice = 0.598 and pixel accuracy = 0.773.
- Mean IoU
- 0.4946
- Mean Dice
- 0.5977
- Pixel accuracy
- 0.7735
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- The reference is complete — Regions or segments missing from the reference turn correct predictions into errors.
- Reference classes don't overlap — Where reference regions of two classes overlap, the shared part counts for both; accuracy then divides by more than the scored area.
Per class (pixels summed over images)
| label | Reference pixels | Predicted pixels | Overlap (pixels) | IoU | Dice |
|---|---|---|---|---|---|
| bicycle | 9,844 | 14,196 | 7,857 | 0.4855 | 0.6537 |
| car | 59,682 | 26,067 | 23,959 | 0.3877 | 0.5588 |
| dog | 0 | 3,012 | 0 | 0 | 0 |
| person | 33,581 | 30,231 | 29,266 | 0.8472 | 0.9173 |
| (background) | 102,433 | 125,542 | 97,893 | 0.7525 | 0.8588 |
Mean IoU per image
| media_id | Mean IoU |
|---|---|
| img01 | 0.5896 |
| img02 | 0.6133 |
| img03 | 0.3908 |
| img04 | 0.3639 |
| img05 | 0.6776 |
| img06 | 0.6747 |
| img07 | 0.4281 |
| img08 | 0.8811 |
| img09 | 0.4880 |
| img10 | 0.1023 |
- Reference rows: source = annotation; predictions: source = prediction. Masks are compared on their run lengths (no pixels decoded); unlabeled pixels form a background class; crowd regions are left out of scoring.
Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.
Worked examples in the app
- Masks background crowdimg4_boxes · crowd: iscrowd · group: media_id · height: image_height · label: label · mask: mask_rle · source: source · width: image_width
- Masks no backgroundimg4_boxes · group: media_id · height: image_height · label: label · mask: mask_rle · source: source · width: image_width
- Masks perfectimg4_perfect · group: media_id · height: image_height · label: label · mask: mask_rle · source: source · width: image_width
- Intervals scoredimg4_intervals · end: end · group: recording · label: label · score: score · source: source · start: start
- Intervals unscored thresholdsimg4_intervals · end: end · group: recording · label: label · source: source · start: start
- Degenerate constantimg4_intervals · end: end · group: recording · label: label · source: source · start: start
- Degenerate all naimg4_boxes · group: media_id · height: image_height · label: label · mask: mask_rle · source: source · width: image_width
- Degenerate single levelimg4_boxes · group: media_id · height: image_height · label: label · mask: mask_rle · source: source · width: image_width
In the guides
Where it sits in the decision guides
- Type: structured (tabular), unstructured (text, images, audio, video), time series / sequential, graph / relational · DS & ML Decision Guide · Key data characteristics — what influences method choice
- Predict: regression MAE, RMSE, R²; classification accuracy, precision, recall, F1, AUC; calibration, lift, log loss · DS & ML Decision Guide · How to evaluate — common metrics by question type
What you need
- Image or recordingcategorical · 1 column
- Which image (media id) or recording each mask or segment belongs to; overlaps are counted within each.
- Frame (optional)numeric · 0–1 column
- Masks of video frames: the frame number; each image and frame pair is scored as its own picture.
- Classcategorical · 1 column
- The class of each mask or segment; overlaps count only within the same class.
- Reference or predictioncategorical · 0–1 column
- Tells reference rows from predicted rows (annotation or prediction in the boxes table). Needed unless a reference table is set.
- Mask (COCO RLE)categorical · 0–1 column
- Masks: COCO run-length strings (column-major), one region per row; rows of the same class and image are joined.
- Image widthnumeric · 0–1 column
- Masks: the width in pixels the mask was encoded at.
- Image heightnumeric · 0–1 column
- Masks: the height in pixels the mask was encoded at.
- Crowd or void region (optional)boolean / numeric · 0–1 column
- Masks: reference regions marked true are left out of scoring (COCO crowd or a void label).
- Startnumeric · 0–1 column
- Time intervals: where each segment starts (seconds or frames, the same unit for every row).
- Endnumeric · 0–1 column
- Time intervals: where each segment ends, at or after its start.
- Confidence score (optional)numeric · 0–1 column
- Time intervals: the predicted segment's confidence; adds average precision and matches the most confident first.
Choices you make
statistics
- Segments aredefault masks
Masks need the mask, width and height columns; time intervals need start and end.
- Image masks(default) — Pixel overlap of masks, counted on the run lengths.
- Time intervals — Overlap of [start, end] segments on one time axis per recording.
- IoU thresholds for matchingdefault 0.1,0.25,0.5
Time intervals: a predicted segment matches a reference segment when their IoU reaches the threshold.
hypothesis
- Reference rowsdefault —
The source value that marks reference rows; default: annotation, else the first value. The other value marks predictions.
- Reference table (optional)default —
The reference masks or segments as a table of their own. Every row of the analyzed table then counts as a prediction; rows it marks as reference are left out.
options
- Count unlabeled pixels as backgrounddefault on
Masks: pixels outside every mask form a background class that is scored like the others (as in PASCAL VOC).
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
The reference is completeNot checked from data: state why it holds
Regions or segments missing from the reference turn correct predictions into errors.
Reference classes don't overlap
Where reference regions of two classes overlap, the shared part counts for both classes.
What it reports
- kind
- Which kind of segments were scored, how many images or recordings and classes, and how many reference and predicted rows.
- n_groups
- Which kind of segments were scored, how many images or recordings and classes, and how many reference and predicted rows.
- n_classes
- Which kind of segments were scored, how many images or recordings and classes, and how many reference and predicted rows.
- n_reference
- Which kind of segments were scored, how many images or recordings and classes, and how many reference and predicted rows.
- n_predictions
- Which kind of segments were scored, how many images or recordings and classes, and how many reference and predicted rows.
- accuracy
- Share of the labeled pixels (or labeled time) given the right class; large classes such as background dominate it.
- miou
- Per class, the pixels (or time) predicted and labeled alike divided by those either one covers; mIoU averages the classes.
- mean_dice
- Twice the overlap divided by the sum of the predicted and labeled areas; always at least the IoU of the same class.
- fw_iou
- Per class, the pixels (or time) predicted and labeled alike divided by those either one covers; mIoU averages the classes.
- scored
- Share of the labeled pixels (or labeled time) given the right class; large classes such as background dominate it.
- ignored
- Share of the labeled pixels (or labeled time) given the right class; large classes such as background dominate it.
- map
- Average precision of scored segments matched at a time IoU threshold, averaged over classes (the ActivityNet convention).
Per group, level or term: iou[<class>], dice[<class>], f1[<threshold>], precision[<threshold>], recall[<threshold>], ap[<threshold>]
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, codesplash; R uses nanoparquet, codesplashr.
Default traps between the two languages
- Pixel counts and segment matches are identical in both engines (integer run arithmetic; the same greedy order); sums of durations and averages can differ in the last bits (summation order).
The exact script CodeSplash ran for example “Masks background crowd” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Segmentation quality (IoU, Dice, segment F1)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.segments 1.1.0 · spec a232974b1dc8e926
# Dataset: img4_boxes (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.evaluate import detection as det # RLE runs (twin: cs_eval_det_runs)
from codesplash.evaluate import segmentation as seg # twin: codesplashr cs_eval_seg_*
from codesplash.evaluate.stacked import flags, image_keys, stacked # twin: cs_eval_stacked
from codesplash.vision import boxes as vb # COCO RLE strings (twin: cs_rle_*)
# %% Data
GROUP = "media_id"
FRAME = None
LABEL = "label"
SOURCE = "source"
MASK = "mask_rle"
WIDTH = "image_width"
HEIGHT = "image_height"
CROWD = "iscrowd"
START = None
END = None
SCORE = None
KIND = "masks" # masks | intervals
BACKGROUND = True
THRESHOLDS = [float(t) for t in [0.1, 0.25, 0.5]] or [0.5]
THRESHOLDS = sorted(set(THRESHOLDS))
REF_LEVEL = None
SOURCE_LEVELS = ["annotation", "prediction"] # stored order
# Reference rows from a second table (option reference_table): its own column for each role, or None.
REF_ROLES = None
columns = list(dict.fromkeys(c for c in [GROUP, FRAME, LABEL, SOURCE, MASK, WIDTH, HEIGHT, CROWD, START, END, SCORE] if c))
df = pd.read_parquet("tests/parity/fixtures/img4_boxes.parquet", columns=columns)
if KIND == "masks" and not (MASK and WIDTH and HEIGHT):
cs.cs_error("CS_E_INVALID_OPTION", option="Segments are", allowed="time intervals unless the mask, width and height columns are set", value="masks")
if KIND == "intervals" and not (START and END):
cs.cs_error("CS_E_INVALID_OPTION", option="Segments are", allowed="masks unless the start and end columns are set", value="time intervals")
pre_warnings = []
if REF_ROLES is not None:
# The reference table's rows go above this table's rows under an added source column (twin: cs_eval_with_reference).
from codesplash.graph import dataset_option # the table the host wrote for the option
from codesplash.evaluate.stacked import with_reference
w = with_reference(df, dataset_option("target/academy-parity/run-8142/evaluate.segments/masks-background-crowd/out-python", "reference_table"),
{"group": GROUP, "frame": FRAME, "label": LABEL, "mask": MASK, "width": WIDTH, "height": HEIGHT, "crowd": CROWD,
"start": START, "end": END, "score": SCORE}, REF_ROLES,
{"frame": "Frame", **({"mask": "Mask", "width": "Image width", "height": "Image height"} if KIND == "masks" else {"start": "Start", "end": "End"})},
SOURCE, REF_LEVEL, ["group", "label"] + (["mask", "width", "height"] if KIND == "masks" else ["start", "end"]))
df, pre_warnings, wc = w["df"], w["warnings"], w["columns"]
GROUP, FRAME, LABEL, MASK, WIDTH, HEIGHT = wc["group"], wc["frame"], wc["label"], wc["mask"], wc["width"], wc["height"]
CROWD, START, END = wc["crowd"], wc["start"], wc["end"]
SOURCE, REF_LEVEL, SOURCE_LEVELS = w["source"], w["reference"], w["levels"]
elif SOURCE is None:
cs.cs_error("CS_E_INVALID_OPTION", option="Reference table", allowed="a table of reference rows unless the Reference or prediction column is set", value="none")
needed = [GROUP, LABEL, SOURCE] + ([MASK, WIDTH, HEIGHT] if KIND == "masks" else [START, END])
numeric = [WIDTH, HEIGHT] if KIND == "masks" else [c for c in [START, END, SCORE] if c]
st = stacked(df, needed, numeric, SOURCE, REF_LEVEL, SOURCE_LEVELS)
df, is_ref, warnings = st["df"], st["is_ref"], pre_warnings + st["warnings"]
if int(is_ref.sum()) == 0 or int((~is_ref).sum()) == 0:
cs.cs_error("CS_E_GROUP_COUNT", column=SOURCE, expected=2, k=1)
labels_all = np.asarray([str(x) for x in df[LABEL].tolist()], dtype=object)
crowd = flags(df[CROWD]) if (CROWD and KIND == "masks") else np.zeros(len(df), dtype=bool)
crowd[~is_ref] = False
classes = sorted(set(labels_all[~crowd].tolist()))
if KIND == "masks":
# %% Masks → runs, per image
img_idx, images = image_keys(df[GROUP], df[FRAME] if FRAME else None)
ws, hs = df[WIDTH].to_numpy(dtype=float), df[HEIGHT].to_numpy(dtype=float)
runs, n_bad = [], 0
for s, w, h in zip(df[MASK].tolist(), ws, hs):
try:
runs.append(det.runs_from_counts(vb.string_to_counts(str(s)), int(h), int(w)))
except (ValueError, OverflowError):
runs.append(None)
n_bad += 1
if n_bad:
cs.cs_error("CS_E_INVALID_VALUES", column=MASK, requirement="a COCO RLE string that covers width × height pixels", count=n_bad)
ims = [{"n": None, "ref": {}, "pred": {}, "void": []} for _ in images]
for i, r in enumerate(runs):
im = ims[int(img_idx[i])]
n = float(r[2][0]) * float(r[2][1])
if im["n"] is None:
im["n"], im["size"] = n, r[2]
elif im["size"] != r[2]:
cs.cs_error("CS_E_INVALID_VALUES", column=f"{WIDTH} and {HEIGHT}", requirement="the same size for every mask of an image", count=1)
if crowd[i]:
im["void"].append(r[:2])
else:
side = im["ref"] if is_ref[i] else im["pred"]
side.setdefault(labels_all[i], []).append(r[:2])
res = seg.mask_scores(ims, classes, BACKGROUND)
names = res["classes"]
n_ref = int(np.sum(is_ref & ~crowd))
n_pred = int(np.sum(~is_ref))
unit = "pixels"
group_rows = [{"group": m, "frame": None if f == float("-inf") else f, "miou": res["per_image"][i]} for i, (m, f) in enumerate(images)]
n_groups = len(images)
else:
# %% Intervals per recording
s_all, e_all = df[START].to_numpy(dtype=float), df[END].to_numpy(dtype=float)
bad = e_all < s_all
if bad.any():
cs.cs_error("CS_E_INVALID_VALUES", column=END, requirement=f"at least {START}", count=int(bad.sum()))
sc_all = df[SCORE].to_numpy(dtype=float, na_value=np.nan) if SCORE else np.full(len(df), np.nan)
has_score = SCORE is not None
if has_score:
miss = ~is_ref & np.isnan(sc_all)
if miss.any():
warnings.append(f"{int(miss.sum())} predicted segments have no {SCORE} and were left out.")
keep = ~miss
df, is_ref, labels_all, s_all, e_all, sc_all = df.loc[keep].reset_index(drop=True), is_ref[keep], labels_all[keep], s_all[keep], e_all[keep], sc_all[keep]
classes = sorted(set(labels_all.tolist()))
grp = np.asarray([str(x) for x in df[GROUP].tolist()], dtype=object)
groups = sorted(set(grp.tolist()))
recs = []
for g in groups:
rows = np.flatnonzero(grp == g)
recs.append({"ref": [(s_all[i], e_all[i], labels_all[i]) for i in rows if is_ref[i]],
"pred": [(s_all[i], e_all[i], labels_all[i], float(sc_all[i]) if has_score else 0.0, int(i)) for i in rows if not is_ref[i]]})
res = seg.interval_scores(recs, classes, THRESHOLDS, has_score)
names = res["classes"]
n_ref, n_pred = res["n_ref"], res["n_pred"]
unit = "seconds"
n_groups = len(groups)
# %% Assumptions
assumptions = [
{"key": "complete", "label": "The reference is complete", "status": "info",
"detail": "Regions or segments missing from the reference turn correct predictions into errors."},
{"key": "overlap", "label": "Reference classes don't overlap", "status": "info",
"detail": "Where reference regions of two classes overlap, the shared part counts for both; accuracy then divides by more than the scored area."},
]
# %% Result
f3 = lambda v: "—" if v is None else f"{v:.3f}"
tkey = lambda t: "%g" % t
values = {"kind": KIND, "n_groups": n_groups, "n_classes": len(names), "n_reference": n_ref, "n_predictions": n_pred,
"accuracy": res["accuracy"], "miou": res["miou"], "mean_dice": res["mean_dice"], "fw_iou": res["fw_iou"],
"scored": res.get("scored", float(np.sum(res["gsum"]))), "ignored": res.get("ignored"), "map": None}
for j, c in enumerate(names):
values[f"iou[{c}]"] = res["iou"][j]
values[f"dice[{c}]"] = res["dice"][j]
cls_cols = [{"key": "class", "label": LABEL, "type": "string"}, {"key": "ref", "label": f"Reference {unit}", "type": "number"},
{"key": "pred", "label": f"Predicted {unit}", "type": "number"}, {"key": "inter", "label": f"Overlap ({unit})", "type": "number"},
{"key": "iou", "label": "IoU", "type": "number"}, {"key": "dice", "label": "Dice", "type": "number"}]
cls_rows = [{"class": c, "ref": float(res["gsum"][j]), "pred": float(res["psum"][j]), "inter": float(res["inter"][j]),
"iou": res["iou"][j], "dice": res["dice"][j]} for j, c in enumerate(names)]
tables = []
charts = []
if KIND == "intervals":
m_rows = res["matching"]
for r in m_rows:
values[f"f1[{tkey(r['threshold'])}]"] = r["f1"]
values[f"precision[{tkey(r['threshold'])}]"] = r["precision"]
values[f"recall[{tkey(r['threshold'])}]"] = r["recall"]
if has_score:
values[f"ap[{tkey(r['threshold'])}]"] = r["map"]
if has_score:
maps = [r["map"] for r in m_rows if r["map"] is not None]
values["map"] = float(np.mean(maps)) if maps else None
for r in m_rows:
cls_cols.append({"key": f"ap_{tkey(r['threshold'])}", "label": f"AP@{tkey(r['threshold'])}", "type": "number"})
for row in cls_rows:
row[f"ap_{tkey(r['threshold'])}"] = r["ap"].get(row["class"])
tables.append({"key": "classes", "title": "Per class (time overlap)", "columns": cls_cols, "rows": cls_rows})
tables.append({"key": "matching", "title": "Segments matched at each IoU threshold",
"columns": [{"key": "threshold", "label": "IoU threshold", "type": "number"}, {"key": "tp", "label": "Matched", "type": "integer"},
{"key": "fp", "label": "False alarms", "type": "integer"}, {"key": "fn", "label": "Missed", "type": "integer"},
{"key": "precision", "label": "Precision", "type": "number"}, {"key": "recall", "label": "Recall", "type": "number"},
{"key": "f1", "label": "F1", "type": "number"}] + ([{"key": "map", "label": "mAP", "type": "number"}] if has_score else []),
"rows": [{k: r[k] for k in ("threshold", "tp", "fp", "fn", "precision", "recall", "f1", "map")} for r in m_rows]})
pts = [(f"IoU {tkey(r['threshold'])}", lab, r[key]) for r in m_rows for key, lab in (("f1", "F1"), ("precision", "Precision"), ("recall", "Recall")) if r[key] is not None]
if pts:
charts.append(cs.chart("f1-at-iou", "cleveland-dot", "Segment F1, precision and recall by IoU threshold", {
"category": cs.col("IoU threshold", [p[0] for p in pts], "categorical", levels=[f"IoU {tkey(r['threshold'])}" for r in m_rows]),
"value": cs.col("Share", [p[2] for p in pts], "numeric"),
"group": cs.col("Measure", [p[1] for p in pts], "categorical", levels=["F1", "Precision", "Recall"])}))
else:
tables.append({"key": "classes", "title": "Per class (pixels summed over images)", "columns": cls_cols, "rows": cls_rows})
tables.append({"key": "images", "title": "Mean IoU per image", "rows": group_rows[:500],
"columns": [{"key": "group", "label": GROUP, "type": "string"}] + ([{"key": "frame", "label": FRAME, "type": "number"}] if FRAME else [])
+ [{"key": "miou", "label": "Mean IoU", "type": "number"}], "note": "First 500 images." if len(group_rows) > 500 else None})
dots = [(c, m, res[key][j]) for j, c in enumerate(names) for key, m in (("iou", "IoU"), ("dice", "Dice")) if res[key][j] is not None]
if dots:
charts.insert(0, cs.chart("by-class", "cleveland-dot", "IoU and Dice by class", {
"category": cs.col(LABEL, [d[0] for d in dots], "categorical", levels=names),
"value": cs.col("Overlap", [d[2] for d in dots], "numeric"),
"group": cs.col("Measure", [d[1] for d in dots], "categorical", levels=["IoU", "Dice"])}))
what = "pixel accuracy" if KIND == "masks" else "time-weighted accuracy"
summary = (f"Across {n_groups} {'images' if KIND == 'masks' else 'recordings'} and {len(names)} classes, mean IoU = {f3(res['miou'])}, "
f"mean Dice = {f3(res['mean_dice'])} and {what} = {f3(res['accuracy'])}.")
if KIND == "intervals":
summary += " Segment F1: " + ", ".join(f"{f3(r['f1'])} at IoU {tkey(r['threshold'])}" for r in res["matching"]) + "."
if has_score and values["map"] is not None:
summary += f" mAP over the thresholds = {f3(values['map'])}."
cs.publish({
"method": "evaluate.segments",
"methodVersion": "1.1.0",
"title": "Segmentation quality",
"engine": cs.engine_info("pandas", "numpy"),
"n": int(len(df)),
"summary": summary,
"statistics": [{"key": "miou", "label": "Mean IoU", "value": res["miou"]}, {"key": "mean_dice", "label": "Mean Dice", "value": res["mean_dice"]},
{"key": "accuracy", "label": "Pixel accuracy" if KIND == "masks" else "Time-weighted accuracy", "value": res["accuracy"]}],
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": [(f"Reference rows: {SOURCE} = {st['reference']}; predictions: {SOURCE} = {st['prediction']}. " if REF_ROLES is None
else "Reference rows come from the reference table; this table's rows are the predictions. ")
+ ("Masks are compared on their run lengths (no pixels decoded)" + ("; unlabeled pixels form a background class" if BACKGROUND else "")
+ ("; crowd regions are left out of scoring" if CROWD else "") + "." if KIND == "masks"
else "Segments match within a recording and class, " + ("highest score first." if SCORE else "earliest first."))],
"charts": charts,
"values": values,
})
The exact script CodeSplash ran for example “Masks background crowd” · R version 4.5.1 (2025-06-13)
# Segmentation quality (IoU, Dice, segment F1)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.segments 1.1.0 · spec a232974b1dc8e926
# Dataset: img4_boxes (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_eval_seg_* (segmentation scores), cs_eval_det_runs, cs_eval_stacked, cs_rle_* (COCO RLE)
# %% Data
GROUP <- "media_id"
FRAME <- NULL
LABEL <- "label"
SOURCE <- "source"
MASK <- "mask_rle"
WIDTH <- "image_width"
HEIGHT <- "image_height"
CROWD <- "iscrowd"
START <- NULL
END <- NULL
SCORE <- NULL
KIND <- "masks" # masks | intervals
BACKGROUND <- TRUE
THRESHOLDS <- as.numeric(unlist(c(0.1, 0.25, 0.5)))
if (!length(THRESHOLDS)) THRESHOLDS <- 0.5
THRESHOLDS <- sort(unique(THRESHOLDS))
REF_LEVEL <- NULL
SOURCE_LEVELS <- c("annotation", "prediction") # stored order
# Reference rows from a second table (option reference_table): its own column for each role, or NULL.
REF_ROLES <- NULL
columns <- unique(c(GROUP, FRAME, LABEL, SOURCE, MASK, WIDTH, HEIGHT, CROWD, START, END, SCORE))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/img4_boxes.parquet", col_select = columns))
if (KIND == "masks" && (is.null(MASK) || is.null(WIDTH) || is.null(HEIGHT))) {
cs_error("CS_E_INVALID_OPTION", option = "Segments are", allowed = "time intervals unless the mask, width and height columns are set", value = "masks")
}
if (KIND == "intervals" && (is.null(START) || is.null(END))) {
cs_error("CS_E_INVALID_OPTION", option = "Segments are", allowed = "masks unless the start and end columns are set", value = "time intervals")
}
pre_warnings <- list()
if (!is.null(REF_ROLES)) {
# The reference table's rows go above this table's rows under an added source column (twin: with_reference).
w <- cs_eval_with_reference(df, cs_graph_dataset_option("target/academy-parity/run-8142/evaluate.segments/masks-background-crowd/out-r", "reference_table"),
list(group = GROUP, frame = FRAME, label = LABEL, mask = MASK, width = WIDTH, height = HEIGHT, crowd = CROWD,
start = START, end = END, score = SCORE), REF_ROLES,
c(list(frame = "Frame"), if (KIND == "masks") list(mask = "Mask", width = "Image width", height = "Image height") else list(start = "Start", end = "End")),
SOURCE, REF_LEVEL, c("group", "label", if (KIND == "masks") c("mask", "width", "height") else c("start", "end")))
df <- w$df
pre_warnings <- w$warnings
wc <- w$columns
GROUP <- wc$group; FRAME <- wc$frame; LABEL <- wc$label; MASK <- wc$mask; WIDTH <- wc$width; HEIGHT <- wc$height
CROWD <- wc$crowd; START <- wc$start; END <- wc$end
SOURCE <- w$source; REF_LEVEL <- w$reference; SOURCE_LEVELS <- w$levels
} else if (is.null(SOURCE)) {
cs_error("CS_E_INVALID_OPTION", option = "Reference table", allowed = "a table of reference rows unless the Reference or prediction column is set", value = "none")
}
needed <- c(GROUP, LABEL, SOURCE, if (KIND == "masks") c(MASK, WIDTH, HEIGHT) else c(START, END))
numeric_cols <- if (KIND == "masks") c(WIDTH, HEIGHT) else c(START, END, SCORE)
st <- cs_eval_stacked(df, needed, numeric_cols, SOURCE, REF_LEVEL, SOURCE_LEVELS)
df <- st$df
is_ref <- st$is_ref
warnings <- c(pre_warnings, st$warnings)
if (sum(is_ref) == 0L || sum(!is_ref) == 0L) cs_error("CS_E_GROUP_COUNT", column = SOURCE, expected = 2, k = 1)
labels_all <- as.character(df[[LABEL]])
crowd <- if (!is.null(CROWD) && KIND == "masks") cs_eval_flags(df[[CROWD]]) else logical(nrow(df))
crowd[!is_ref] <- FALSE
classes <- sort(unique(labels_all[!crowd]), method = "radix")
if (KIND == "masks") {
# %% Masks -> runs, per image
ik <- cs_eval_image_keys(df[[GROUP]], if (!is.null(FRAME)) df[[FRAME]] else NULL)
img_idx <- ik$index
ws <- as.numeric(df[[WIDTH]])
hs <- as.numeric(df[[HEIGHT]])
runs <- lapply(seq_len(nrow(df)), function(i) {
tryCatch(cs_eval_det_runs(cs_rle_string_to_counts(as.character(df[[MASK]][i])), as.integer(hs[i]), as.integer(ws[i])),
error = function(e) NULL)
})
n_bad <- sum(vapply(runs, is.null, logical(1)))
if (n_bad > 0) cs_error("CS_E_INVALID_VALUES", column = MASK, requirement = "a COCO RLE string that covers width × height pixels", count = n_bad)
ims <- lapply(seq_along(ik$media), function(i) list(n = NULL, size = NULL, ref = list(), pred = list(), void = list()))
for (i in seq_along(runs)) {
q <- img_idx[i] + 1L
r <- runs[[i]]
if (is.null(ims[[q]]$n)) {
ims[[q]]$n <- as.numeric(r$size[1]) * as.numeric(r$size[2])
ims[[q]]$size <- r$size
} else if (!identical(ims[[q]]$size, r$size)) {
cs_error("CS_E_INVALID_VALUES", column = sprintf("%s and %s", WIDTH, HEIGHT), requirement = "the same size for every mask of an image", count = 1)
}
rr <- list(s = r$s, e = r$e)
if (crowd[i]) {
ims[[q]]$void[[length(ims[[q]]$void) + 1L]] <- rr
} else if (is_ref[i]) {
lab <- labels_all[i]
ims[[q]]$ref[[lab]] <- c(if (is.null(ims[[q]]$ref[[lab]])) list() else ims[[q]]$ref[[lab]], list(rr))
} else {
lab <- labels_all[i]
ims[[q]]$pred[[lab]] <- c(if (is.null(ims[[q]]$pred[[lab]])) list() else ims[[q]]$pred[[lab]], list(rr))
}
}
res <- cs_eval_seg_masks(ims, classes, BACKGROUND)
names_ <- res$classes
n_ref <- sum(is_ref & !crowd)
n_pred <- sum(!is_ref)
unit <- "pixels"
group_rows <- lapply(seq_along(ik$media), function(i) list(group = ik$media[i], frame = if (is.infinite(ik$frame[i])) NA_real_ else ik$frame[i],
miou = if (is.null(res$per_image[[i]])) NA_real_ else res$per_image[[i]]))
n_groups <- length(ik$media)
has_score <- FALSE
} else {
# %% Intervals per recording
s_all <- as.numeric(df[[START]])
e_all <- as.numeric(df[[END]])
bad <- e_all < s_all
if (any(bad)) cs_error("CS_E_INVALID_VALUES", column = END, requirement = sprintf("at least %s", START), count = sum(bad))
sc_all <- if (!is.null(SCORE)) as.numeric(df[[SCORE]]) else rep(NA_real_, nrow(df))
has_score <- !is.null(SCORE)
if (has_score) {
miss <- !is_ref & is.na(sc_all)
if (any(miss)) {
warnings <- c(warnings, sprintf("%d predicted segments have no %s and were left out.", sum(miss), SCORE))
keep <- !miss
df <- df[keep, , drop = FALSE]; is_ref <- is_ref[keep]; labels_all <- labels_all[keep]
s_all <- s_all[keep]; e_all <- e_all[keep]; sc_all <- sc_all[keep]
classes <- sort(unique(labels_all), method = "radix")
}
}
grp <- as.character(df[[GROUP]])
groups <- sort(unique(grp), method = "radix")
recs <- lapply(groups, function(g) {
rows <- which(grp == g)
rr <- rows[is_ref[rows]]
pr <- rows[!is_ref[rows]]
list(ref = data.frame(start = s_all[rr], end = e_all[rr], label = labels_all[rr], stringsAsFactors = FALSE),
pred = data.frame(start = s_all[pr], end = e_all[pr], label = labels_all[pr], score = if (has_score) sc_all[pr] else rep(0, length(pr)),
row = pr - 1L, stringsAsFactors = FALSE))
})
res <- cs_eval_seg_intervals(recs, classes, THRESHOLDS, has_score)
names_ <- res$classes
n_ref <- res$n_ref
n_pred <- res$n_pred
unit <- "seconds"
n_groups <- length(groups)
}
# %% Assumptions
assumptions <- list(
list(key = "complete", label = "The reference is complete", status = "info",
detail = "Regions or segments missing from the reference turn correct predictions into errors."),
list(key = "overlap", label = "Reference classes don't overlap", status = "info",
detail = "Where reference regions of two classes overlap, the shared part counts for both; accuracy then divides by more than the scored area.")
)
# %% Result
f3 <- function(v) if (is.null(v) || is.na(v)) "—" else sprintf("%.3f", v)
tkey <- function(t) sprintf("%g", t)
values <- list(kind = KIND, n_groups = n_groups, n_classes = length(names_), n_reference = n_ref, n_predictions = n_pred,
accuracy = res$accuracy, miou = res$miou, mean_dice = res$mean_dice, fw_iou = res$fw_iou,
scored = if (!is.null(res$scored)) res$scored else sum(res$gsum), ignored = if (!is.null(res$ignored)) res$ignored else NA_real_,
map = NA_real_)
for (j in seq_along(names_)) {
values[[sprintf("iou[%s]", names_[j])]] <- res$iou[j]
values[[sprintf("dice[%s]", names_[j])]] <- res$dice[j]
}
cls_cols <- list(list(key = "class", label = LABEL, type = "string"), list(key = "ref", label = sprintf("Reference %s", unit), type = "number"),
list(key = "pred", label = sprintf("Predicted %s", unit), type = "number"), list(key = "inter", label = sprintf("Overlap (%s)", unit), type = "number"),
list(key = "iou", label = "IoU", type = "number"), list(key = "dice", label = "Dice", type = "number"))
cls_rows <- lapply(seq_along(names_), function(j) list(class = names_[j], ref = res$gsum[j], pred = res$psum[j], inter = res$inter[j],
iou = res$iou[j], dice = res$dice[j]))
tables <- list()
charts <- list()
if (KIND == "intervals") {
m_rows <- res$matching
for (r in m_rows) {
values[[sprintf("f1[%s]", tkey(r$threshold))]] <- r$f1
values[[sprintf("precision[%s]", tkey(r$threshold))]] <- r$precision
values[[sprintf("recall[%s]", tkey(r$threshold))]] <- r$recall
if (has_score) values[[sprintf("ap[%s]", tkey(r$threshold))]] <- r$map
}
if (has_score) {
maps <- vapply(m_rows, function(r) r$map, numeric(1))
maps <- maps[!is.na(maps)]
values$map <- if (length(maps)) mean(maps) else NA_real_
for (r in m_rows) {
key <- sprintf("ap_%s", tkey(r$threshold))
cls_cols[[length(cls_cols) + 1L]] <- list(key = key, label = sprintf("AP@%s", tkey(r$threshold)), type = "number")
for (j in seq_along(cls_rows)) cls_rows[[j]][[key]] <- if (is.null(r$ap[[cls_rows[[j]]$class]])) NA_real_ else r$ap[[cls_rows[[j]]$class]]
}
}
tables[[length(tables) + 1L]] <- list(key = "classes", title = "Per class (time overlap)", columns = cls_cols, rows = cls_rows)
mcols <- list(list(key = "threshold", label = "IoU threshold", type = "number"), list(key = "tp", label = "Matched", type = "integer"),
list(key = "fp", label = "False alarms", type = "integer"), list(key = "fn", label = "Missed", type = "integer"),
list(key = "precision", label = "Precision", type = "number"), list(key = "recall", label = "Recall", type = "number"),
list(key = "f1", label = "F1", type = "number"))
if (has_score) mcols[[length(mcols) + 1L]] <- list(key = "map", label = "mAP", type = "number")
tables[[length(tables) + 1L]] <- list(key = "matching", title = "Segments matched at each IoU threshold", columns = mcols,
rows = lapply(m_rows, function(r) r[c("threshold", "tp", "fp", "fn", "precision", "recall", "f1", "map")]))
pc <- character(0); pm <- character(0); pv <- numeric(0)
for (r in m_rows) for (km in list(c("f1", "F1"), c("precision", "Precision"), c("recall", "Recall"))) if (!is.na(r[[km[1]]])) {
pc <- c(pc, sprintf("IoU %s", tkey(r$threshold))); pm <- c(pm, km[2]); pv <- c(pv, r[[km[1]]])
}
if (length(pv)) {
charts[[length(charts) + 1L]] <- cs_chart("f1-at-iou", "cleveland-dot", "Segment F1, precision and recall by IoU threshold", list(
category = cs_col("IoU threshold", pc, "categorical", levels = vapply(m_rows, function(r) sprintf("IoU %s", tkey(r$threshold)), character(1))),
value = cs_col("Share", pv, "numeric"),
group = cs_col("Measure", pm, "categorical", levels = c("F1", "Precision", "Recall"))))
}
} else {
tables[[length(tables) + 1L]] <- list(key = "classes", title = "Per class (pixels summed over images)", columns = cls_cols, rows = cls_rows)
tables[[length(tables) + 1L]] <- list(key = "images", title = "Mean IoU per image", rows = utils::head(group_rows, 500),
columns = c(list(list(key = "group", label = GROUP, type = "string")), if (!is.null(FRAME)) list(list(key = "frame", label = FRAME, type = "number")),
list(list(key = "miou", label = "Mean IoU", type = "number"))),
note = if (length(group_rows) > 500) "First 500 images." else NULL)
}
dc <- character(0); dm <- character(0); dv <- numeric(0)
for (j in seq_along(names_)) for (km in list(c("iou", "IoU"), c("dice", "Dice"))) if (!is.na(res[[km[1]]][j])) {
dc <- c(dc, names_[j]); dm <- c(dm, km[2]); dv <- c(dv, res[[km[1]]][j])
}
if (length(dv)) {
charts <- c(list(cs_chart("by-class", "cleveland-dot", "IoU and Dice by class", list(
category = cs_col(LABEL, dc, "categorical", levels = names_), value = cs_col("Overlap", dv, "numeric"),
group = cs_col("Measure", dm, "categorical", levels = c("IoU", "Dice"))))), charts)
}
what <- if (KIND == "masks") "pixel accuracy" else "time-weighted accuracy"
summary <- sprintf("Across %d %s and %d classes, mean IoU = %s, mean Dice = %s and %s = %s.", n_groups, if (KIND == "masks") "images" else "recordings",
length(names_), f3(res$miou), f3(res$mean_dice), what, f3(res$accuracy))
if (KIND == "intervals") {
summary <- paste0(summary, " Segment F1: ", paste(vapply(res$matching, function(r) sprintf("%s at IoU %s", f3(r$f1), tkey(r$threshold)), character(1)), collapse = ", "), ".")
if (has_score && !is.na(values$map)) summary <- paste0(summary, sprintf(" mAP over the thresholds = %s.", f3(values$map)))
}
cs_publish(list(
method = "evaluate.segments",
methodVersion = "1.1.0",
title = "Segmentation quality",
engine = cs_engine_info("nanoparquet"),
n = nrow(df),
summary = summary,
statistics = list(list(key = "miou", label = "Mean IoU", value = res$miou), list(key = "mean_dice", label = "Mean Dice", value = res$mean_dice),
list(key = "accuracy", label = if (KIND == "masks") "Pixel accuracy" else "Time-weighted accuracy", value = res$accuracy)),
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = list(paste0(if (is.null(REF_ROLES)) sprintf("Reference rows: %s = %s; predictions: %s = %s. ", SOURCE, st$reference, SOURCE, st$prediction)
else "Reference rows come from the reference table; this table's rows are the predictions. ",
if (KIND == "masks") paste0("Masks are compared on their run lengths (no pixels decoded)", if (BACKGROUND) "; unlabeled pixels form a background class" else "",
if (!is.null(CROWD)) "; crowd regions are left out of scoring" else "", ".")
else paste0("Segments match within a recording and class, ", if (!is.null(SCORE)) "highest score first." else "earliest first."))),
charts = charts,
values = values
))
Sources
- Everingham, M., Van Gool, L., Williams, C. K. I., Winn, J., & Zisserman, A. (2010). The PASCAL Visual Object Classes (VOC) challenge. International Journal of Computer Vision, 88(2), 303–338.
- Long, J., Shelhamer, E., & Darrell, T. (2015). Fully convolutional networks for semantic segmentation. CVPR 2015, 3431–3440.
- Dice, L. R. (1945). Measures of the amount of ecologic association between species. Ecology, 26(3), 297–302.
- Lea, C., Flynn, M. D., Vidal, R., Reiter, A., & Hager, G. D. (2017). Temporal convolutional networks for action segmentation and detection. CVPR 2017, 156–165.
- Caba Heilbron, F., Escorcia, V., Ghanem, B., & Niebles, J. C. (2015). ActivityNet: A large-scale video benchmark for human activity understanding. CVPR 2015, 961–970.
- Mesaros, A., Heittola, T., & Virtanen, T. (2016). Metrics for polyphonic sound event detection. Applied Sciences, 6(6), 162.
From the CodeSplash method registry · evaluate.segments v1.1.0.