HEvaluate predictions · evaluate.detections
Object detection quality (COCO average precision)
How well do predicted boxes or masks find the labeled objects, class by class?
Scores predicted boxes (or instance masks) against reference annotations with the COCO conventions: intersection over union, average precision at IoU 0.50, 0.75 and averaged over 0.50:0.95, by object size, average recall at 1, 10 and up to 100 detections per image, per-class precision–recall curves and the true and false positives at IoU 0.50 per class and image. Crowd regions and the size ranges follow COCO, so the numbers match pycocotools. Reads the boxes table that annotation import and object detection write: reference and predicted rows stacked, told apart by a source column, or the predictions with the reference boxes in a table of their own.
A real result
Example “Boxes coco”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
Across 10 images and 3 classes, AP (IoU 0.50:0.95) = 0.473, AP50 = 0.560 and AP75 = 0.560; average recall with up to 100 detections per image = 0.534. At IoU 0.50: 16 true positives, 16 false positives, 10 missed objects.
- AP (0.50:0.95)
- 0.4726
- AP50
- 0.5600
- AP75
- 0.5600
- AR@100
- 0.5342
Plots
COCO's interpolated precision at 101 recall points, up to the recall each class reaches.
View data
| label | Precision (interpolated) | Recall |
|---|---|---|
| person | 1 | 0 |
| person | 1 | 0.0100 |
| person | 1 | 0.0200 |
| person | 1 | 0.0300 |
| person | 1 | 0.0400 |
| person | 1 | 0.0500 |
| person | 1 | 0.0600 |
| person | 1 | 0.0700 |
| person | 1 | 0.0800 |
| person | 1 | 0.0900 |
| person | 1 | 0.1000 |
| person | 1 | 0.1100 |
| person | 1 | 0.1200 |
| person | 1 | 0.1300 |
| person | 1 | 0.1400 |
| person | 1 | 0.1500 |
| person | 1 | 0.1600 |
| person | 1 | 0.1700 |
| person | 1 | 0.1800 |
| person | 1 | 0.1900 |
| person | 1 | 0.2000 |
| person | 1 | 0.2100 |
| person | 1 | 0.2200 |
| person | 1 | 0.2300 |
| person | 1 | 0.2400 |
| person | 1 | 0.2500 |
| person | 1 | 0.2600 |
| person | 1 | 0.2700 |
| person | 1 | 0.2800 |
| person | 1 | 0.2900 |
| person | 1 | 0.3000 |
| person | 1 | 0.3100 |
| person | 1 | 0.3200 |
| person | 1 | 0.3300 |
| person | 1 | 0.3400 |
| person | 1 | 0.3500 |
| person | 1 | 0.3600 |
| person | 1 | 0.3700 |
| person | 1 | 0.3800 |
| person | 1 | 0.3900 |
| person | 1 | 0.4000 |
| person | 1 | 0.4100 |
| person | 1 | 0.4200 |
| person | 1 | 0.4300 |
| person | 1 | 0.4400 |
| person | 1 | 0.4500 |
| person | 1 | 0.4600 |
| person | 1 | 0.4700 |
| person | 1 | 0.4800 |
| person | 1 | 0.4900 |
| person | 1 | 0.5000 |
| person | 1 | 0.5100 |
| person | 1 | 0.5200 |
| person | 1 | 0.5300 |
| person | 1 | 0.5400 |
| person | 1 | 0.5500 |
| person | 1 | 0.5600 |
| person | 1 | 0.5700 |
| person | 1 | 0.5800 |
| person | 1 | 0.5900 |
First 60 of 184 rows.
View data
| label | Measure | Average precision |
|---|---|---|
| bicycle | AP | 0.3373 |
| bicycle | AP50 | 0.4323 |
| bicycle | AP75 | 0.4323 |
| car | AP | 0.5007 |
| car | AP50 | 0.5545 |
| car | AP75 | 0.5545 |
| person | AP | 0.5799 |
| person | AP50 | 0.6931 |
| person | AP75 | 0.6931 |
Assumptions
- Every object is labeled — Predictions of objects that the reference doesn't list count as false positives.
- Predicted classes are in the reference — 1 predictions of 1 unknown class(es) were left out.
- Enough objects per class — Fewer than 10 reference objects: bicycle, car.
COCO summary (boxes)
| Metric | IoU | Object size | Detections per image | Value |
|---|---|---|---|---|
| AP | 0.50:0.95 | all | 100 | 0.4726 |
| AP | 0.50 | all | 100 | 0.5600 |
| AP | 0.75 | all | 100 | 0.5600 |
| AP | 0.50:0.95 | small | 100 | 0.2472 |
| AP | 0.50:0.95 | medium | 100 | 0.7396 |
| AP | 0.50:0.95 | large | 100 | 0.4713 |
| AR | 0.50:0.95 | all | 1 | 0.3971 |
| AR | 0.50:0.95 | all | 10 | 0.5342 |
| AR | 0.50:0.95 | all | 100 | 0.5342 |
| AR | 0.50:0.95 | small | 100 | 0.2667 |
| AR | 0.50:0.95 | medium | 100 | 0.7619 |
| AR | 0.50:0.95 | large | 100 | 0.4667 |
Size groups use the reference area: small < 32², medium 32²–96², large > 96² pixels. Empty = no object of that size.
Per class (IoU 0.50 counts with every image's top detections)
| label | Reference objects | Crowd regions | Predictions | AP | AP50 | AP75 | AR@100 | True positives | False positives | Missed |
|---|---|---|---|---|---|---|---|---|---|---|
| bicycle | 7 | 0 | 10 | 0.3373 | 0.4323 | 0.4323 | 0.4714 | 4 | 6 | 3 |
| car | 9 | 0 | 9 | 0.5007 | 0.5545 | 0.5545 | 0.5111 | 5 | 4 | 4 |
| person | 10 | 1 | 15 | 0.5799 | 0.6931 | 0.6931 | 0.6200 | 7 | 6 | 3 |
Per image at IoU 0.50
| media_id | Reference objects | Predictions | True positives | False positives | Missed |
|---|---|---|---|---|---|
| img01 | 2 | 2 | 1 | 1 | 1 |
| img02 | 3 | 4 | 3 | 1 | 0 |
| img03 | 5 | 7 | 2 | 3 | 3 |
| img04 | 2 | 3 | 1 | 2 | 1 |
| img05 | 4 | 7 | 4 | 3 | 0 |
| img06 | 2 | 5 | 2 | 3 | 0 |
| img07 | 2 | 3 | 1 | 2 | 1 |
| img08 | 3 | 2 | 2 | 0 | 1 |
| img09 | 0 | 1 | 0 | 1 | 0 |
| img10 | 3 | 0 | 0 | 0 | 3 |
- 1 predicted boxes have a class the reference never uses (dog); they can't be scored and were left out.
- Reference rows: source = annotation; predictions: source = prediction. Crowd regions (iscrowd) absorb overlapping predictions without counting them. COCO conventions: IoU 0.50:0.05:0.95, 101 recall points, greedy matching by score within each image and class.
Across 10 images and 3 classes, AP (IoU 0.50:0.95) = 0.473, AP50 = 0.560 and AP75 = 0.560; average recall with up to 100 detections per image = 0.534. At IoU 0.50: 16 true positives, 16 false positives, 10 missed objects.
- AP (0.50:0.95)
- 0.4726
- AP50
- 0.5600
- AP75
- 0.5600
- AR@100
- 0.5342
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Every object is labeled — Predictions of objects that the reference doesn't list count as false positives.
- Predicted classes are in the reference — 1 predictions of 1 unknown class(es) were left out.
- Enough objects per class — Fewer than 10 reference objects: bicycle, car.
COCO summary (boxes)
| Metric | IoU | Object size | Detections per image | Value |
|---|---|---|---|---|
| AP | 0.50:0.95 | all | 100 | 0.4726 |
| AP | 0.50 | all | 100 | 0.5600 |
| AP | 0.75 | all | 100 | 0.5600 |
| AP | 0.50:0.95 | small | 100 | 0.2472 |
| AP | 0.50:0.95 | medium | 100 | 0.7396 |
| AP | 0.50:0.95 | large | 100 | 0.4713 |
| AR | 0.50:0.95 | all | 1 | 0.3971 |
| AR | 0.50:0.95 | all | 10 | 0.5342 |
| AR | 0.50:0.95 | all | 100 | 0.5342 |
| AR | 0.50:0.95 | small | 100 | 0.2667 |
| AR | 0.50:0.95 | medium | 100 | 0.7619 |
| AR | 0.50:0.95 | large | 100 | 0.4667 |
Size groups use the reference area: small < 32², medium 32²–96², large > 96² pixels. Empty = no object of that size.
Per class (IoU 0.50 counts with every image's top detections)
| label | Reference objects | Crowd regions | Predictions | AP | AP50 | AP75 | AR@100 | True positives | False positives | Missed |
|---|---|---|---|---|---|---|---|---|---|---|
| bicycle | 7 | 0 | 10 | 0.3373 | 0.4323 | 0.4323 | 0.4714 | 4 | 6 | 3 |
| car | 9 | 0 | 9 | 0.5007 | 0.5545 | 0.5545 | 0.5111 | 5 | 4 | 4 |
| person | 10 | 1 | 15 | 0.5799 | 0.6931 | 0.6931 | 0.6200 | 7 | 6 | 3 |
Per image at IoU 0.50
| media_id | Reference objects | Predictions | True positives | False positives | Missed |
|---|---|---|---|---|---|
| img01 | 2 | 2 | 1 | 1 | 1 |
| img02 | 3 | 4 | 3 | 1 | 0 |
| img03 | 5 | 7 | 2 | 3 | 3 |
| img04 | 2 | 3 | 1 | 2 | 1 |
| img05 | 4 | 7 | 4 | 3 | 0 |
| img06 | 2 | 5 | 2 | 3 | 0 |
| img07 | 2 | 3 | 1 | 2 | 1 |
| img08 | 3 | 2 | 2 | 0 | 1 |
| img09 | 0 | 1 | 0 | 1 | 0 |
| img10 | 3 | 0 | 0 | 0 | 3 |
- 1 predicted boxes have a class the reference never uses (dog); they can't be scored and were left out.
- Reference rows: source = annotation; predictions: source = prediction. Crowd regions (iscrowd) absorb overlapping predictions without counting them. COCO conventions: IoU 0.50:0.05:0.95, 101 recall points, greedy matching by score within each image and class.
Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.
Worked examples in the app
- Boxes cocoimg4_boxes · area: area · crowd: iscrowd · image: media_id · label: label · score: score · source: source · x0: x0 · x1: x1 · y0: y0 · y1: y1
- Masks cocoimg4_boxes · area: area · crowd: iscrowd · height: image_height · image: media_id · label: label · mask: mask_rle · score: score · source: source · width: image_width · x0: x0 · x1: x1 · y0: y0 · y1: y1
- Boxes plain limit 20img4_boxes · image: media_id · label: label · score: score · source: source · x0: x0 · x1: x1 · y0: y0 · y1: y1
- Class agnosticimg4_boxes · crowd: iscrowd · image: media_id · label: label · score: score · source: source · x0: x0 · x1: x1 · y0: y0 · y1: y1
- Video framesimg4_tracks · frame: frame · image: media_id · label: label · score: score · source: source · x0: x0 · x1: x1 · y0: y0 · y1: y1
- Perfect predictionsimg4_perfect · image: media_id · label: label · score: score · source: source · x0: x0 · x1: x1 · y0: y0 · y1: y1
- Degenerate constantimg4_boxes · image: media_id · label: label · score: score · source: source · x0: x0 · x1: x1 · y0: y0 · y1: y1
- Degenerate all naimg4_boxes · image: media_id · label: label · score: score · source: source · x0: x0 · x1: x1 · y0: y0 · y1: y1
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
- Imagecategorical / numeric · 1 column
- Which image each box belongs to (the media id). Boxes are matched only within the same image (and frame).
- Frame (optional)numeric · 0–1 column
- For video frames: the frame number. Each image and frame pair is scored as its own picture.
- Left (x0)numeric · 1 column
- Left edge of the box in pixels (0 = the image's left edge).
- Top (y0)numeric · 1 column
- Top edge of the box in pixels (0 = the image's top edge).
- Right (x1)numeric · 1 column
- Right edge of the box in pixels; width = x1 − x0.
- Bottom (y1)numeric · 1 column
- Bottom edge of the box in pixels; height = y1 − y0.
- Classcategorical · 1 column
- The object class. A prediction counts only against reference objects of the same class.
- Confidence scorenumeric · 1 column
- The detector's confidence for each predicted box; higher scores are ranked first. Empty on reference rows.
- 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.
- Crowd region (optional)boolean / numeric · 0–1 column
- True for a reference region that covers a crowd of objects; predictions inside it are neither rewarded nor penalized.
- Reference area (optional)numeric · 0–1 column
- The area in pixels that decides a reference object's size group (COCO uses the mask area); empty uses the box or mask area.
- Mask (COCO RLE, optional)categorical · 0–1 column
- Instance masks as COCO run-length strings, for mask average precision. Needs the image width and height.
- Image width (optional)numeric · 0–1 column
- Width in pixels the mask was encoded at (image_width in the boxes table).
- Image height (optional)numeric · 0–1 column
- Height in pixels the mask was encoded at (image_height in the boxes table).
Choices you make
statistics
- Overlap measured ondefault bbox
Boxes score box detectors; masks score instance segmentation and need the mask, width and height columns.
- Boxes(default) — Intersection over union of the boxes.
- Masks — Intersection over union of the masks' pixels, counted on the run lengths.
- Detections per imagedefault 100
Only each image's top-scoring detections up to this many count (COCO uses 100). Average recall is also shown at 1 and 10.
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 boxes as a table of their own, one row per labeled object. Every row of the analyzed table then counts as a prediction; rows it marks as reference are left out.
options
- Ignore classesdefault off
Matches boxes whatever their class: one class-agnostic AP that only judges localization.
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.
Every object is labeledNot checked from data: state why it holds
Objects missing from the reference turn correct predictions into false positives; incomplete labels make AP look worse than it is.
Predicted classes are in the reference
Predictions of a class the reference never uses can't be scored and are left out; they are counted in a warning.
Enough objects per class
With fewer than about 10 reference objects in a class its AP moves a lot with a single box; read small classes with care.
What it reports
- n_images
- How many images, classes, reference objects and predicted boxes the scores use; predictions of unknown classes are left out.
- n_classes
- How many images, classes, reference objects and predicted boxes the scores use; predictions of unknown classes are left out.
- n_reference
- How many images, classes, reference objects and predicted boxes the scores use; predictions of unknown classes are left out.
- n_crowd
- A labeled area that holds many objects at once; predictions inside it are neither rewarded nor counted as false positives.
- n_predictions
- How many images, classes, reference objects and predicted boxes the scores use; predictions of unknown classes are left out.
- n_unknown_label
- How many images, classes, reference objects and predicted boxes the scores use; predictions of unknown classes are left out.
- iou_type
- The area two boxes share divided by the area they cover together: 1 for the same box, 0 when they don't touch.
- max_dets
- Area under the precision–recall curve of a detector, averaged over classes and over IoU thresholds 0.50 to 0.95.
- ap
- Area under the precision–recall curve of a detector, averaged over classes and over IoU thresholds 0.50 to 0.95.
- ap50
- Average precision when a box must overlap its object by at least 50% (AP50) or 75% (AP75) IoU.
- ap75
- Average precision when a box must overlap its object by at least 50% (AP50) or 75% (AP75) IoU.
- ap_small
- AP for small (under 32×32 px), medium and large (over 96×96 px) reference objects; small ones are usually hardest.
- ap_medium
- AP for small (under 32×32 px), medium and large (over 96×96 px) reference objects; small ones are usually hardest.
- ap_large
- AP for small (under 32×32 px), medium and large (over 96×96 px) reference objects; small ones are usually hardest.
- ar1
- Share of labeled objects found when only each image's top k detections count, averaged over IoU 0.50 to 0.95.
- ar10
- Share of labeled objects found when only each image's top k detections count, averaged over IoU 0.50 to 0.95.
- ar_max
- Share of labeled objects found when only each image's top k detections count, averaged over IoU 0.50 to 0.95.
- ar_small
- AP for small (under 32×32 px), medium and large (over 96×96 px) reference objects; small ones are usually hardest.
- ar_medium
- AP for small (under 32×32 px), medium and large (over 96×96 px) reference objects; small ones are usually hardest.
- ar_large
- AP for small (under 32×32 px), medium and large (over 96×96 px) reference objects; small ones are usually hardest.
- tp50
- At IoU 0.5: predictions that found an object (true), that found none (false positive), and objects nobody found (missed).
- fp50
- At IoU 0.5: predictions that found an object (true), that found none (false positive), and objects nobody found (missed).
- fn50
- At IoU 0.5: predictions that found an object (true), that found none (false positive), and objects nobody found (missed).
- precision50
- At IoU 0.5: predictions that found an object (true), that found none (false positive), and objects nobody found (missed).
- recall50
- At IoU 0.5: predictions that found an object (true), that found none (false positive), and objects nobody found (missed).
Per group, level or term: ap[<class>], ap50[<class>], ap75[<class>], ar[<class>]
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
- Matching, the precision–recall steps and every count are identical in both engines (the same operations in the same order, ties broken by table order); averages can differ in the last bits (summation order).
- pycocotools reports AP (IoU 0.50:0.95) at a fixed limit of 100 detections even when the limits are changed; here AP uses the chosen limit. With the default limit the twelve numbers are the same.
The exact script CodeSplash ran for example “Boxes coco” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Object detection quality (COCO average precision)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.detections 1.1.0 · spec b85c9129c0a7e375
# 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 # twin: codesplashr cs_eval_det_*
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
IMG = "media_id"
FRAME = None
X0, Y0, X1, Y1 = "x0", "y0", "x1", "y1"
LABEL, SCORE = "label", "score"
SOURCE = "source"
CROWD = "iscrowd"
AREA = "area"
MASK = None
WIDTH = None
HEIGHT = None
IOU_TYPE = "bbox" # bbox | segm
MAX_DETS = int(100)
AGNOSTIC = False
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 [IMG, FRAME, X0, Y0, X1, Y1, LABEL, SCORE, SOURCE, CROWD, AREA, MASK, WIDTH, HEIGHT] if c))
df = pd.read_parquet("tests/parity/fixtures/img4_boxes.parquet", columns=columns)
if IOU_TYPE == "segm" and not (MASK and WIDTH and HEIGHT):
cs.cs_error("CS_E_INVALID_OPTION", option="Overlap measured on", allowed="Boxes unless the mask, width and height columns are set", value="Masks")
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.detections/boxes-coco/out-python", "reference_table"),
{"image": IMG, "frame": FRAME, "x0": X0, "y0": Y0, "x1": X1, "y1": Y1, "label": LABEL, "score": SCORE,
"crowd": CROWD, "area": AREA, "mask": MASK, "width": WIDTH, "height": HEIGHT}, REF_ROLES,
{"frame": "Frame", **({"mask": "Mask", "width": "Image width", "height": "Image height"} if IOU_TYPE == "segm" else {})},
SOURCE, REF_LEVEL, ["image", "x0", "y0", "x1", "y1", "label"] + (["mask", "width", "height"] if IOU_TYPE == "segm" else []))
df, pre_warnings, wc = w["df"], w["warnings"], w["columns"]
IMG, FRAME, X0, Y0, X1, Y1 = wc["image"], wc["frame"], wc["x0"], wc["y0"], wc["x1"], wc["y1"]
LABEL, CROWD, AREA, MASK, WIDTH, HEIGHT = wc["label"], wc["crowd"], wc["area"], wc["mask"], wc["width"], wc["height"]
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 = [IMG, X0, Y0, X1, Y1, LABEL, SOURCE] + ([MASK, WIDTH, HEIGHT] if IOU_TYPE == "segm" else [])
st = stacked(df, needed, [c for c in [X0, Y0, X1, Y1, SCORE, AREA, WIDTH, HEIGHT] if c], SOURCE, REF_LEVEL, SOURCE_LEVELS)
df, is_ref, warnings = st["df"], st["is_ref"], pre_warnings + st["warnings"]
score_all = df[SCORE].to_numpy(dtype=float, na_value=np.nan)
no_score = ~is_ref & np.isnan(score_all)
if no_score.any():
warnings.append(f"{int(no_score.sum())} predicted boxes have no {SCORE} and were left out.")
df, is_ref, score_all = df.loc[~no_score].reset_index(drop=True), is_ref[~no_score], score_all[~no_score]
box = df[[X0, Y0, X1, Y1]].to_numpy(dtype=float)
bad = (box[:, 2] < box[:, 0]) | (box[:, 3] < box[:, 1])
if bad.any():
cs.cs_error("CS_E_INVALID_VALUES", column=f"{X1} and {Y1}", requirement=f"at least {X0} and {Y0}", count=int(bad.sum()))
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)
crowd = flags(df[CROWD]) if CROWD else np.zeros(len(df), dtype=bool)
crowd[~is_ref] = False # predictions are never crowd regions
img_idx, images = image_keys(df[IMG], df[FRAME] if FRAME else None)
labels_all = np.asarray([str(x) for x in df[LABEL].tolist()], dtype=object)
# %% Masks (COCO run-length strings, column-major)
runs = None
if IOU_TYPE == "segm":
runs, n_bad = [], 0
for s, w, h in zip(df[MASK].tolist(), df[WIDTH].to_numpy(dtype=float), df[HEIGHT].to_numpy(dtype=float)):
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)
sizes = {}
for i, r in enumerate(runs):
if sizes.setdefault(int(img_idx[i]), r[2]) != 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)
obj_area = np.asarray([det.runs_area(r) for r in runs])
else:
obj_area = det.box_area(box)
# %% Classes and areas
ref_classes = sorted(set(labels_all[is_ref].tolist()))
classes = ["(all classes)"] if AGNOSTIC else ref_classes
cat_of = {c: i for i, c in enumerate(ref_classes)}
unknown = sorted(set(labels_all[~is_ref].tolist()) - set(ref_classes))
known_pred = ~is_ref & np.asarray([lab in cat_of for lab in labels_all])
if unknown:
n_unk = int((~is_ref & ~known_pred).sum())
shown = ", ".join(unknown[:5]) + (" …" if len(unknown) > 5 else "")
warnings.append(f"{n_unk} predicted boxes have a class the reference never uses ({shown}); they can't be scored and were left out.")
else:
n_unk = 0
ref_area = obj_area.copy()
if AREA:
a_col = df[AREA].to_numpy(dtype=float, na_value=np.nan)
ref_area = np.where(np.isnan(a_col), obj_area, a_col)
cat_all = np.asarray([0 if AGNOSTIC else cat_of.get(lab, -1) for lab in labels_all], dtype=int)
gi = np.flatnonzero(is_ref)
di = np.flatnonzero(known_pred)
gt = {"img": img_idx[gi], "cat": cat_all[gi], "box": box[gi], "area": ref_area[gi], "crowd": crowd[gi],
"runs": [runs[j] for j in gi] if runs is not None else None}
dt = {"img": img_idx[di], "cat": cat_all[di], "box": box[di], "score": score_all[di], "area": obj_area[di],
"runs": [runs[j] for j in di] if runs is not None else None}
# %% COCO evaluation
max_dets = (1, 10, MAX_DETS)
ev = det.evaluate(gt, dt, len(images), len(classes), IOU_TYPE, max_dets)
stats = ev["stats"]
status = ev["det_status"] # per evaluated prediction at IoU 0.50: tp | fp | ignored | beyond
matched = ev["det_match"] # the reference it matched (position in gt), −1 none
thr = ev["thresholds"]
t50 = int(np.flatnonzero(thr == 0.5)[0])
n_ref_regular = int((~gt["crowd"]).sum())
ref_hit = np.zeros(gi.size, dtype=bool)
for q in range(di.size):
if status[q] == "tp":
ref_hit[matched[q]] = True
tp50 = int(np.sum(status == "tp"))
fp50 = int(np.sum(status == "fp"))
fn50 = int(np.sum(~ref_hit & ~gt["crowd"]))
per = []
for k, c in enumerate(classes):
pc = det.per_class(ev["precision"], ev["recall"], thr, k)
in_g = gt["cat"] == k
in_d = dt["cat"] == k
per.append({"class": c, "n_ref": int(np.sum(in_g & ~gt["crowd"])), "n_crowd": int(np.sum(in_g & gt["crowd"])),
"n_pred": int(np.sum(in_d)), "ap": pc["ap"], "ap50": pc["ap50"], "ap75": pc["ap75"], "ar": pc["ar"],
"tp": int(np.sum(in_d & (status == "tp"))), "fp": int(np.sum(in_d & (status == "fp"))),
"fn": int(np.sum(in_g & ~ref_hit & ~gt["crowd"]))})
# %% Assumptions
small = [p["class"] for p in per if p["n_ref"] < 10]
assumptions = [
{"key": "complete", "label": "Every object is labeled", "status": "info",
"detail": "Predictions of objects that the reference doesn't list count as false positives."},
{"key": "classes", "label": "Predicted classes are in the reference", "status": "warn" if unknown else "pass",
"detail": (f"{n_unk} predictions of {len(unknown)} unknown class(es) were left out." if unknown else "Every predicted class appears in the reference.")},
{"key": "images", "label": "Enough objects per class", "status": "warn" if small else "pass",
"detail": (f"Fewer than 10 reference objects: {', '.join(small[:8])}{' …' if len(small) > 8 else ''}." if small else "Every class has at least 10 reference objects.")},
]
# %% Result
f3 = lambda v: "—" if v is None else f"{v:.3f}"
values = {"n_images": len(images), "n_classes": len(classes), "n_reference": n_ref_regular, "n_crowd": int(gt["crowd"].sum()),
"n_predictions": int(di.size), "n_unknown_label": n_unk, "iou_type": IOU_TYPE, "max_dets": MAX_DETS,
"ap": stats["ap"], "ap50": stats["ap50"], "ap75": stats["ap75"], "ap_small": stats["ap_small"],
"ap_medium": stats["ap_medium"], "ap_large": stats["ap_large"], "ar1": stats["ar_0"], "ar10": stats["ar_1"],
"ar_max": stats["ar_2"], "ar_small": stats["ar_small"], "ar_medium": stats["ar_medium"], "ar_large": stats["ar_large"],
"tp50": tp50, "fp50": fp50, "fn50": fn50,
"precision50": tp50 / (tp50 + fp50) if (tp50 + fp50) else None,
"recall50": tp50 / n_ref_regular if n_ref_regular else None}
for p in per:
for key in ("ap", "ap50", "ap75", "ar"):
values[f"{key}[{p['class']}]"] = p[key]
summary_rows = [
("AP", "0.50:0.95", "all", MAX_DETS, stats["ap"]), ("AP", "0.50", "all", MAX_DETS, stats["ap50"]),
("AP", "0.75", "all", MAX_DETS, stats["ap75"]), ("AP", "0.50:0.95", "small", MAX_DETS, stats["ap_small"]),
("AP", "0.50:0.95", "medium", MAX_DETS, stats["ap_medium"]), ("AP", "0.50:0.95", "large", MAX_DETS, stats["ap_large"]),
("AR", "0.50:0.95", "all", 1, stats["ar_0"]), ("AR", "0.50:0.95", "all", 10, stats["ar_1"]),
("AR", "0.50:0.95", "all", MAX_DETS, stats["ar_2"]), ("AR", "0.50:0.95", "small", MAX_DETS, stats["ar_small"]),
("AR", "0.50:0.95", "medium", MAX_DETS, stats["ar_medium"]), ("AR", "0.50:0.95", "large", MAX_DETS, stats["ar_large"]),
]
tables = [
{"key": "coco", "title": "COCO summary" + (" (masks)" if IOU_TYPE == "segm" else " (boxes)"),
"columns": [{"key": "metric", "label": "Metric", "type": "string"}, {"key": "iou", "label": "IoU", "type": "string"},
{"key": "area", "label": "Object size", "type": "string"}, {"key": "max_dets", "label": "Detections per image", "type": "integer"},
{"key": "value", "label": "Value", "type": "number"}],
"rows": [{"metric": m, "iou": t, "area": a, "max_dets": d, "value": v} for m, t, a, d, v in summary_rows],
"note": "Size groups use the reference area: small < 32², medium 32²–96², large > 96² pixels. Empty = no object of that size."},
{"key": "classes", "title": "Per class (IoU 0.50 counts with every image's top detections)",
"columns": [{"key": "class", "label": LABEL, "type": "string"}, {"key": "n_ref", "label": "Reference objects", "type": "integer"},
{"key": "n_crowd", "label": "Crowd regions", "type": "integer"}, {"key": "n_pred", "label": "Predictions", "type": "integer"},
{"key": "ap", "label": "AP", "type": "number"}, {"key": "ap50", "label": "AP50", "type": "number"},
{"key": "ap75", "label": "AP75", "type": "number"}, {"key": "ar", "label": f"AR@{MAX_DETS}", "type": "number"},
{"key": "tp", "label": "True positives", "type": "integer"}, {"key": "fp", "label": "False positives", "type": "integer"},
{"key": "fn", "label": "Missed", "type": "integer"}],
"rows": per},
]
img_rows = []
for i, (m, f) in enumerate(images):
in_g = gt["img"] == i
in_d = dt["img"] == i
img_rows.append({"image": m, "frame": None if f == float("-inf") else f, "n_ref": int(np.sum(in_g & ~gt["crowd"])),
"n_pred": int(np.sum(in_d)), "tp": int(np.sum(in_d & (status == "tp"))), "fp": int(np.sum(in_d & (status == "fp"))),
"fn": int(np.sum(in_g & ~ref_hit & ~gt["crowd"]))})
img_cols = [{"key": "image", "label": IMG, "type": "string"}] + ([{"key": "frame", "label": FRAME, "type": "number"}] if FRAME else []) + [
{"key": "n_ref", "label": "Reference objects", "type": "integer"}, {"key": "n_pred", "label": "Predictions", "type": "integer"},
{"key": "tp", "label": "True positives", "type": "integer"}, {"key": "fp", "label": "False positives", "type": "integer"},
{"key": "fn", "label": "Missed", "type": "integer"}]
tables.append({"key": "images", "title": "Per image at IoU 0.50", "columns": img_cols, "rows": img_rows[:500],
"note": "First 500 images." if len(img_rows) > 500 else None})
charts = []
rec = ev["recall_points"]
top = sorted(range(len(per)), key=lambda k: (-per[k]["n_ref"], k))[:8]
cr, cp, cc = [], [], []
for k in top:
if per[k]["n_ref"] == 0:
continue
reach = ev["recall"][t50, k, 0, -1]
for r, p in zip(rec, ev["precision"][t50, :, k, 0, -1]):
if r <= reach:
cr.append(float(r))
cp.append(float(p))
cc.append(per[k]["class"])
if cr:
shown = [per[k]["class"] for k in top if per[k]["n_ref"] > 0]
charts.append(cs.chart("pr", "pr-curve", "Precision–recall at IoU 0.50, by class", {
"recall": cs.col("Recall", cr, "numeric"), "precision": cs.col("Precision (interpolated)", cp, "numeric"),
"curve": cs.col(LABEL, cc, "categorical", levels=shown)},
note="COCO's interpolated precision at 101 recall points, up to the recall each class reaches." + (" The 8 classes with the most reference objects." if len(per) > 8 else "")))
dots = [(p["class"], m, p[key]) for p in per for key, m in (("ap", "AP"), ("ap50", "AP50"), ("ap75", "AP75")) if p[key] is not None]
if dots:
charts.append(cs.chart("ap-by-class", "cleveland-dot", "Average precision by class", {
"category": cs.col(LABEL, [d[0] for d in dots], "categorical", levels=classes),
"value": cs.col("Average precision", [d[2] for d in dots], "numeric"),
"group": cs.col("Measure", [d[1] for d in dots], "categorical", levels=["AP", "AP50", "AP75"])}))
summary = (f"Across {len(images)} images and {len(classes)} class{'es' if len(classes) != 1 else ''}, AP (IoU 0.50:0.95) = {f3(stats['ap'])}, "
f"AP50 = {f3(stats['ap50'])} and AP75 = {f3(stats['ap75'])}; average recall with up to {MAX_DETS} detections per image = {f3(stats['ar_2'])}. "
f"At IoU 0.50: {tp50} true positives, {fp50} false positives, {fn50} missed objects.")
cs.publish({
"method": "evaluate.detections",
"methodVersion": "1.1.0",
"title": "Object detection quality",
"engine": cs.engine_info("pandas", "numpy"),
"n": int(len(df)),
"summary": summary,
"statistics": [{"key": "ap", "label": "AP (0.50:0.95)", "value": stats["ap"]}, {"key": "ap50", "label": "AP50", "value": stats["ap50"]},
{"key": "ap75", "label": "AP75", "value": stats["ap75"]}, {"key": "ar_max", "label": f"AR@{MAX_DETS}", "value": stats["ar_2"]}],
"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. ")
+ ("Classes ignored: any predicted box can match any reference box. " if AGNOSTIC else "")
+ ("Crowd regions (" + CROWD + ") absorb overlapping predictions without counting them. " if CROWD else "")
+ "COCO conventions: IoU 0.50:0.05:0.95, 101 recall points, greedy matching by score within each image and class."],
"charts": charts,
"values": values,
})
The exact script CodeSplash ran for example “Boxes coco” · R version 4.5.1 (2025-06-13)
# Object detection quality (COCO average precision)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.detections 1.1.0 · spec b85c9129c0a7e375
# 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_det_* (COCO evaluation), cs_eval_stacked, cs_rle_* (COCO RLE strings)
# %% Data
IMG <- "media_id"
FRAME <- NULL
X0 <- "x0"; Y0 <- "y0"; X1 <- "x1"; Y1 <- "y1"
LABEL <- "label"; SCORE <- "score"
SOURCE <- "source"
CROWD <- "iscrowd"
AREA <- "area"
MASK <- NULL
WIDTH <- NULL
HEIGHT <- NULL
IOU_TYPE <- "bbox" # bbox | segm
MAX_DETS <- as.integer(100)
AGNOSTIC <- FALSE
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(IMG, FRAME, X0, Y0, X1, Y1, LABEL, SCORE, SOURCE, CROWD, AREA, MASK, WIDTH, HEIGHT))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/img4_boxes.parquet", col_select = columns))
if (IOU_TYPE == "segm" && (is.null(MASK) || is.null(WIDTH) || is.null(HEIGHT))) {
cs_error("CS_E_INVALID_OPTION", option = "Overlap measured on", allowed = "Boxes unless the mask, width and height columns are set", value = "Masks")
}
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.detections/boxes-coco/out-r", "reference_table"),
list(image = IMG, frame = FRAME, x0 = X0, y0 = Y0, x1 = X1, y1 = Y1, label = LABEL, score = SCORE,
crowd = CROWD, area = AREA, mask = MASK, width = WIDTH, height = HEIGHT), REF_ROLES,
c(list(frame = "Frame"), if (IOU_TYPE == "segm") list(mask = "Mask", width = "Image width", height = "Image height")),
SOURCE, REF_LEVEL, c("image", "x0", "y0", "x1", "y1", "label", if (IOU_TYPE == "segm") c("mask", "width", "height")))
df <- w$df
pre_warnings <- w$warnings
wc <- w$columns
IMG <- wc$image; FRAME <- wc$frame; X0 <- wc$x0; Y0 <- wc$y0; X1 <- wc$x1; Y1 <- wc$y1
LABEL <- wc$label; CROWD <- wc$crowd; AREA <- wc$area; MASK <- wc$mask; WIDTH <- wc$width; HEIGHT <- wc$height
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(IMG, X0, Y0, X1, Y1, LABEL, SOURCE, if (IOU_TYPE == "segm") c(MASK, WIDTH, HEIGHT))
st <- cs_eval_stacked(df, needed, c(X0, Y0, X1, Y1, SCORE, AREA, WIDTH, HEIGHT), SOURCE, REF_LEVEL, SOURCE_LEVELS)
df <- st$df
is_ref <- st$is_ref
warnings <- c(pre_warnings, st$warnings)
score_all <- as.numeric(df[[SCORE]])
no_score <- !is_ref & is.na(score_all)
if (any(no_score)) {
warnings <- c(warnings, sprintf("%d predicted boxes have no %s and were left out.", sum(no_score), SCORE))
df <- df[!no_score, , drop = FALSE]
is_ref <- is_ref[!no_score]
score_all <- score_all[!no_score]
}
box <- cbind(as.numeric(df[[X0]]), as.numeric(df[[Y0]]), as.numeric(df[[X1]]), as.numeric(df[[Y1]]))
bad <- (box[, 3] < box[, 1]) | (box[, 4] < box[, 2])
if (any(bad)) cs_error("CS_E_INVALID_VALUES", column = sprintf("%s and %s", X1, Y1), requirement = sprintf("at least %s and %s", X0, Y0), count = sum(bad))
if (sum(is_ref) == 0L || sum(!is_ref) == 0L) cs_error("CS_E_GROUP_COUNT", column = SOURCE, expected = 2, k = 1)
crowd <- if (!is.null(CROWD)) cs_eval_flags(df[[CROWD]]) else logical(nrow(df))
crowd[!is_ref] <- FALSE # predictions are never crowd regions
ik <- cs_eval_image_keys(df[[IMG]], if (!is.null(FRAME)) df[[FRAME]] else NULL)
img_idx <- ik$index
n_img <- length(ik$media)
labels_all <- as.character(df[[LABEL]])
# %% Masks (COCO run-length strings, column-major)
runs <- NULL
if (IOU_TYPE == "segm") {
n_bad <- 0L
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)
sizes <- list()
for (i in seq_along(runs)) {
key <- as.character(img_idx[i])
if (is.null(sizes[[key]])) sizes[[key]] <- runs[[i]]$size
if (!identical(sizes[[key]], runs[[i]]$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)
}
}
obj_area <- vapply(runs, function(r) sum(r$e - r$s), numeric(1))
} else {
obj_area <- cs_eval_det_box_area(box)
}
# %% Classes and areas
ref_classes <- sort(unique(labels_all[is_ref]), method = "radix")
classes <- if (AGNOSTIC) "(all classes)" else ref_classes
unknown <- sort(setdiff(unique(labels_all[!is_ref]), ref_classes), method = "radix")
known_pred <- !is_ref & labels_all %in% ref_classes
n_unk <- 0L
if (length(unknown)) {
n_unk <- sum(!is_ref & !known_pred)
shown <- paste0(paste(utils::head(unknown, 5), collapse = ", "), if (length(unknown) > 5) " …" else "")
warnings <- c(warnings, sprintf("%d predicted boxes have a class the reference never uses (%s); they can't be scored and were left out.", n_unk, shown))
}
ref_area <- obj_area
if (!is.null(AREA)) {
a_col <- as.numeric(df[[AREA]])
ref_area <- ifelse(is.na(a_col), obj_area, a_col)
}
cat_all <- if (AGNOSTIC) rep(0L, nrow(df)) else { m <- match(labels_all, ref_classes) - 1L; m[is.na(m)] <- -1L; m }
gi <- which(is_ref)
di <- which(known_pred)
gt <- list(img = img_idx[gi], cat = cat_all[gi], box = box[gi, , drop = FALSE], area = ref_area[gi], crowd = crowd[gi],
runs = if (!is.null(runs)) runs[gi] else NULL)
dt <- list(img = img_idx[di], cat = cat_all[di], box = box[di, , drop = FALSE], score = score_all[di], area = obj_area[di],
runs = if (!is.null(runs)) runs[di] else NULL)
# %% COCO evaluation
max_dets <- c(1L, 10L, MAX_DETS)
ev <- cs_eval_det_evaluate(gt, dt, n_img, length(classes), IOU_TYPE, max_dets)
stats <- ev$stats
status <- ev$det_status # per evaluated prediction at IoU 0.50: tp | fp | ignored | beyond
matched <- ev$det_match # the reference it matched (0-based position in gt), -1 none
thr <- ev$thresholds
t50 <- which(thr == 0.5)[1]
nz <- function(v) if (is.null(v)) NA_real_ else v
n_ref_regular <- sum(!gt$crowd)
ref_hit <- logical(length(gi))
for (q in seq_along(di)) if (status[q] == "tp") ref_hit[matched[q] + 1L] <- TRUE
tp50 <- sum(status == "tp")
fp50 <- sum(status == "fp")
fn50 <- sum(!ref_hit & !gt$crowd)
per <- lapply(seq_along(classes), function(k) {
pc <- cs_eval_det_per_class(ev$precision, ev$recall, thr, k)
in_g <- gt$cat == k - 1L
in_d <- dt$cat == k - 1L
list(class = classes[k], n_ref = sum(in_g & !gt$crowd), n_crowd = sum(in_g & gt$crowd), n_pred = sum(in_d),
ap = nz(pc$ap), ap50 = nz(pc$ap50), ap75 = nz(pc$ap75), ar = nz(pc$ar),
tp = sum(in_d & status == "tp"), fp = sum(in_d & status == "fp"), fn = sum(in_g & !ref_hit & !gt$crowd))
})
# %% Assumptions
small <- vapply(Filter(function(p) p$n_ref < 10, per), function(p) p$class, character(1))
assumptions <- list(
list(key = "complete", label = "Every object is labeled", status = "info",
detail = "Predictions of objects that the reference doesn't list count as false positives."),
list(key = "classes", label = "Predicted classes are in the reference", status = if (length(unknown)) "warn" else "pass",
detail = if (length(unknown)) sprintf("%d predictions of %d unknown class(es) were left out.", n_unk, length(unknown)) else "Every predicted class appears in the reference."),
list(key = "images", label = "Enough objects per class", status = if (length(small)) "warn" else "pass",
detail = if (length(small)) sprintf("Fewer than 10 reference objects: %s%s.", paste(utils::head(small, 8), collapse = ", "), if (length(small) > 8) " …" else "") else "Every class has at least 10 reference objects.")
)
# %% Result
f3 <- function(v) if (is.null(v) || is.na(v)) "—" else sprintf("%.3f", v)
values <- list(n_images = n_img, n_classes = length(classes), n_reference = n_ref_regular, n_crowd = sum(gt$crowd),
n_predictions = length(di), n_unknown_label = n_unk, iou_type = IOU_TYPE, max_dets = MAX_DETS,
ap = nz(stats$ap), ap50 = nz(stats$ap50), ap75 = nz(stats$ap75), ap_small = nz(stats$ap_small),
ap_medium = nz(stats$ap_medium), ap_large = nz(stats$ap_large), ar1 = nz(stats$ar_0), ar10 = nz(stats$ar_1),
ar_max = nz(stats$ar_2), ar_small = nz(stats$ar_small), ar_medium = nz(stats$ar_medium), ar_large = nz(stats$ar_large),
tp50 = tp50, fp50 = fp50, fn50 = fn50,
precision50 = if (tp50 + fp50 > 0) tp50 / (tp50 + fp50) else NA_real_,
recall50 = if (n_ref_regular > 0) tp50 / n_ref_regular else NA_real_)
for (p in per) for (key in c("ap", "ap50", "ap75", "ar")) values[[sprintf("%s[%s]", key, p$class)]] <- p[[key]]
sr <- list(list("AP", "0.50:0.95", "all", MAX_DETS, stats$ap), list("AP", "0.50", "all", MAX_DETS, stats$ap50),
list("AP", "0.75", "all", MAX_DETS, stats$ap75), list("AP", "0.50:0.95", "small", MAX_DETS, stats$ap_small),
list("AP", "0.50:0.95", "medium", MAX_DETS, stats$ap_medium), list("AP", "0.50:0.95", "large", MAX_DETS, stats$ap_large),
list("AR", "0.50:0.95", "all", 1L, stats$ar_0), list("AR", "0.50:0.95", "all", 10L, stats$ar_1),
list("AR", "0.50:0.95", "all", MAX_DETS, stats$ar_2), list("AR", "0.50:0.95", "small", MAX_DETS, stats$ar_small),
list("AR", "0.50:0.95", "medium", MAX_DETS, stats$ar_medium), list("AR", "0.50:0.95", "large", MAX_DETS, stats$ar_large))
tables <- list(
list(key = "coco", title = paste0("COCO summary", if (IOU_TYPE == "segm") " (masks)" else " (boxes)"),
columns = list(list(key = "metric", label = "Metric", type = "string"), list(key = "iou", label = "IoU", type = "string"),
list(key = "area", label = "Object size", type = "string"), list(key = "max_dets", label = "Detections per image", type = "integer"),
list(key = "value", label = "Value", type = "number")),
rows = lapply(sr, function(r) list(metric = r[[1]], iou = r[[2]], area = r[[3]], max_dets = r[[4]], value = nz(r[[5]]))),
note = "Size groups use the reference area: small < 32², medium 32²–96², large > 96² pixels. Empty = no object of that size."),
list(key = "classes", title = "Per class (IoU 0.50 counts with every image's top detections)",
columns = list(list(key = "class", label = LABEL, type = "string"), list(key = "n_ref", label = "Reference objects", type = "integer"),
list(key = "n_crowd", label = "Crowd regions", type = "integer"), list(key = "n_pred", label = "Predictions", type = "integer"),
list(key = "ap", label = "AP", type = "number"), list(key = "ap50", label = "AP50", type = "number"),
list(key = "ap75", label = "AP75", type = "number"), list(key = "ar", label = sprintf("AR@%d", MAX_DETS), type = "number"),
list(key = "tp", label = "True positives", type = "integer"), list(key = "fp", label = "False positives", type = "integer"),
list(key = "fn", label = "Missed", type = "integer")),
rows = per)
)
img_rows <- lapply(seq_len(n_img), function(i) {
in_g <- gt$img == i - 1L
in_d <- dt$img == i - 1L
list(image = ik$media[i], frame = if (is.infinite(ik$frame[i])) NA_real_ else ik$frame[i], n_ref = sum(in_g & !gt$crowd),
n_pred = sum(in_d), tp = sum(in_d & status == "tp"), fp = sum(in_d & status == "fp"), fn = sum(in_g & !ref_hit & !gt$crowd))
})
img_cols <- c(list(list(key = "image", label = IMG, type = "string")), if (!is.null(FRAME)) list(list(key = "frame", label = FRAME, type = "number")),
list(list(key = "n_ref", label = "Reference objects", type = "integer"), list(key = "n_pred", label = "Predictions", type = "integer"),
list(key = "tp", label = "True positives", type = "integer"), list(key = "fp", label = "False positives", type = "integer"),
list(key = "fn", label = "Missed", type = "integer")))
tables[[length(tables) + 1L]] <- list(key = "images", title = "Per image at IoU 0.50", columns = img_cols, rows = utils::head(img_rows, 500),
note = if (n_img > 500) "First 500 images." else NULL)
charts <- list()
rec <- ev$recall_points
m_last <- length(max_dets)
nref <- vapply(per, function(p) p$n_ref, numeric(1))
top <- utils::head(order(-nref, seq_along(per), method = "radix"), 8)
cr <- numeric(0); cp <- numeric(0); cc <- character(0)
for (k in top) {
if (per[[k]]$n_ref == 0) next
reach <- ev$recall[t50, k, 1, m_last]
pk <- ev$precision[t50, , k, 1, m_last]
sel <- rec <= reach
cr <- c(cr, rec[sel]); cp <- c(cp, pk[sel]); cc <- c(cc, rep(per[[k]]$class, sum(sel)))
}
if (length(cr)) {
shown <- vapply(Filter(function(k) per[[k]]$n_ref > 0, top), function(k) per[[k]]$class, character(1))
charts[[length(charts) + 1L]] <- cs_chart("pr", "pr-curve", "Precision–recall at IoU 0.50, by class", list(
recall = cs_col("Recall", cr, "numeric"), precision = cs_col("Precision (interpolated)", cp, "numeric"),
curve = cs_col(LABEL, cc, "categorical", levels = shown)),
note = paste0("COCO's interpolated precision at 101 recall points, up to the recall each class reaches.", if (length(per) > 8) " The 8 classes with the most reference objects." else ""))
}
dc <- character(0); dm <- character(0); dv <- numeric(0)
for (p in per) for (km in list(c("ap", "AP"), c("ap50", "AP50"), c("ap75", "AP75"))) if (!is.na(p[[km[1]]])) {
dc <- c(dc, p$class); dm <- c(dm, km[2]); dv <- c(dv, p[[km[1]]])
}
if (length(dv)) {
charts[[length(charts) + 1L]] <- cs_chart("ap-by-class", "cleveland-dot", "Average precision by class", list(
category = cs_col(LABEL, dc, "categorical", levels = classes), value = cs_col("Average precision", dv, "numeric"),
group = cs_col("Measure", dm, "categorical", levels = c("AP", "AP50", "AP75"))))
}
summary <- sprintf("Across %d images and %d class%s, AP (IoU 0.50:0.95) = %s, AP50 = %s and AP75 = %s; average recall with up to %d detections per image = %s. At IoU 0.50: %d true positives, %d false positives, %d missed objects.",
n_img, length(classes), if (length(classes) != 1) "es" else "", f3(stats$ap), f3(stats$ap50), f3(stats$ap75), MAX_DETS, f3(stats$ar_2), tp50, fp50, fn50)
cs_publish(list(
method = "evaluate.detections",
methodVersion = "1.1.0",
title = "Object detection quality",
engine = cs_engine_info("nanoparquet"),
n = nrow(df),
summary = summary,
statistics = list(list(key = "ap", label = "AP (0.50:0.95)", value = nz(stats$ap)), list(key = "ap50", label = "AP50", value = nz(stats$ap50)),
list(key = "ap75", label = "AP75", value = nz(stats$ap75)), list(key = "ar_max", label = sprintf("AR@%d", MAX_DETS), value = nz(stats$ar_2))),
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 (AGNOSTIC) "Classes ignored: any predicted box can match any reference box. " else "",
if (!is.null(CROWD)) sprintf("Crowd regions (%s) absorb overlapping predictions without counting them. ", CROWD) else "",
"COCO conventions: IoU 0.50:0.05:0.95, 101 recall points, greedy matching by score within each image and class.")),
charts = charts,
values = values
))
Sources
- Lin, T.-Y., Maire, M., Belongie, S., et al. (2014). Microsoft COCO: Common objects in context. ECCV 2014, 740–755.
- 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.
- Padilla, R., Netto, S. L., & da Silva, E. A. B. (2020). A survey on performance metrics for object-detection algorithms. IWSSIP 2020, 237–242.
- Hosang, J., Benenson, R., Dollár, P., & Schiele, B. (2016). What makes for effective detection proposals? IEEE TPAMI, 38(4), 814–830.
From the CodeSplash method registry · evaluate.detections v1.1.0.