One-stage and set-based detectors: SSD, RetinaNet, DETR
Dense detectors that score every location in one pass and the loss fixes they needed (hard negative mining, focal loss), then DETR's set prediction with one-to-one matching and Deformable DETR's sparse attention.
What runs in CodeSplash
- VIS004Single Shot MultiBox Detector (SSD) Explained here
- VIS006RetinaNet with focal loss Partly runs in CodeSplash
- VIS007Detection Transformer (DETR) Runs as a notebook
- VIS008Deformable DETR Explained here
- Object detection quality (COCO average precision) Experimental
- Convolutional neural network (CNN) Experimental
You will be able to
- Explain why dense detectors drown in easy background boxes
- Compare hard negative mining with focal loss
- Describe DETR's one-to-one matching and why it needs no NMS
- Say what deformable attention samples and why it trains faster
Every location at once
ReadA one-stage detector skips proposals. At every position of several feature maps it predicts a class and box offsets for a few default boxes, so a single image yields tens of thousands of candidates. Nearly all of them are background.
That imbalance is the whole problem. Each easy background box adds a little loss, and tens of thousands of littles outweigh the few boxes that hold objects. Training then mostly learns to say "background".
SSD: train on the hard negatives
ReadSSD predicts from feature maps at several resolutions, fine maps for small objects and coarse maps for large ones. To tame the background it uses hard negative miningHard negative mining (detection)Training on only the background boxes the model gets most wrong, so easy background doesn't swamp the few object boxes.: keep only the background boxes with the highest loss, at most three per positive.
The program has 10 default boxes, 2 of them positive. It keeps the 6 hardest negatives, numbers 1, 4, 7, 8, 5 and 9 from zero, and divides the total loss by the positives: 2.40.
RetinaNet: let easy examples fade
ReadRetinaNet keeps every box but changes the loss. Focal lossFocal lossCross-entropy multiplied by (1 − p)^γ, so well-classified examples add almost nothing and training focuses on hard ones. multiplies cross-entropy by (1 − p)^γ, where p is the probability given to the right class. With γ = 2, a box the model already gets right with p near 1 contributes almost nothing.
The program compares an easy, a middling and a hard box (p of 0.99, 0.8 and one in five). Relative to plain cross-entropy their losses are scaled by 0.000100, 0.0400 and 0.640: the easy box fades by a factor of ten thousand, the hard one keeps most of its weight.
Focal loss in CodeSplash
In the appThe loss runs here for classes, not boxes. The CNN, the deep neural network (torch MLP) and the image classifier have Loss: Focal loss under Advanced, with Focusing (γ)Focusing parameter (γ)The exponent γ in focal loss's (1 − p)^γ: 0 is plain cross-entropy; larger values fade well-classified rows faster. and, for two classes, Positive-class weight (α)Positive-class weight (α)Two classes only: focal loss weights positive rows by α and negative rows by 1 − α (RetinaNet used α = 0.25).. Only training batches use it; early stopping still watches the log loss. Here the CNN sorts odd from even digits with RetinaNet's γ = 2 and α = 0.25:
Convolutional neural network (CNN): cross-validated ROC AUC 0.990 ± 0.004 over 3 folds; ROC AUC on the locked test set 0.997 (n = 200).
- CV ROC AUC
- 0.9903
- SD across folds
- 0.0039
- Test ROC AUC
- 0.9973
Plots
View data
| Network | Epoch | Training loss |
|---|---|---|
| CNN | 1 | 0.0887 |
| CNN | 2 | 0.0720 |
| CNN | 3 | 0.0710 |
| CNN | 4 | 0.0672 |
| CNN | 5 | 0.0628 |
| CNN | 6 | 0.0602 |
| CNN | 7 | 0.0580 |
| CNN | 8 | 0.0552 |
| CNN | 9 | 0.0519 |
| CNN | 10 | 0.0486 |
| CNN | 11 | 0.0456 |
| CNN | 12 | 0.0428 |
| CNN | 13 | 0.0402 |
| CNN | 14 | 0.0378 |
| CNN | 15 | 0.0359 |
| CNN | 16 | 0.0340 |
| CNN | 17 | 0.0323 |
| CNN | 18 | 0.0310 |
| CNN | 19 | 0.0296 |
| CNN | 20 | 0.0283 |
| CNN | 21 | 0.0272 |
| CNN | 22 | 0.0260 |
| CNN | 23 | 0.0249 |
| CNN | 24 | 0.0239 |
| CNN | 25 | 0.0228 |
| CNN | 26 | 0.0219 |
| CNN | 27 | 0.0211 |
| CNN | 28 | 0.0203 |
| CNN | 29 | 0.0196 |
| CNN | 30 | 0.0190 |
| CNN | 31 | 0.0183 |
| CNN | 32 | 0.0178 |
| CNN | 33 | 0.0172 |
| CNN | 34 | 0.0166 |
| CNN | 35 | 0.0160 |
| CNN | 36 | 0.0155 |
| CNN | 37 | 0.0150 |
| CNN | 38 | 0.0145 |
| CNN | 39 | 0.0141 |
| CNN | 40 | 0.0136 |
| CNN | 41 | 0.0132 |
| CNN | 42 | 0.0127 |
| CNN | 43 | 0.0123 |
| CNN | 44 | 0.0120 |
| CNN | 45 | 0.0116 |
| CNN | 46 | 0.0113 |
| CNN | 47 | 0.0110 |
| CNN | 48 | 0.0106 |
| CNN | 49 | 0.0103 |
| CNN | 50 | 0.0100 |
| CNN | 51 | 0.0097 |
| CNN | 52 | 0.0095 |
| CNN | 53 | 0.0092 |
| CNN | 54 | 0.0089 |
| CNN | 55 | 0.0087 |
| CNN | 56 | 0.0084 |
| CNN | 57 | 0.0082 |
| CNN | 58 | 0.0080 |
| CNN | 59 | 0.0078 |
| CNN | 60 | 0.0075 |
Each square is one learned k × k kernel; the color scale's two ends are weights of opposite sign.
View data
| Column | Panel | Row | Weight |
|---|---|---|---|
| 1 | filter 1 | 1 | 0.6025 |
| 2 | filter 1 | 1 | 0.7961 |
| 3 | filter 1 | 1 | 0.5856 |
| 4 | filter 1 | 1 | −0.3517 |
| 5 | filter 1 | 1 | −0.5870 |
| 1 | filter 1 | 2 | −0.0385 |
| 2 | filter 1 | 2 | 0.5992 |
| 3 | filter 1 | 2 | 0.0562 |
| 4 | filter 1 | 2 | −0.4267 |
| 5 | filter 1 | 2 | −0.4099 |
| 1 | filter 1 | 3 | −0.5664 |
| 2 | filter 1 | 3 | −0.5924 |
| 3 | filter 1 | 3 | 0.0807 |
| 4 | filter 1 | 3 | 0.4475 |
| 5 | filter 1 | 3 | 0.0270 |
| 1 | filter 1 | 4 | 0.4102 |
| 2 | filter 1 | 4 | −0.1515 |
| 3 | filter 1 | 4 | 0.2046 |
| 4 | filter 1 | 4 | −0.0738 |
| 5 | filter 1 | 4 | 0.2720 |
| 1 | filter 1 | 5 | 1.076 |
| 2 | filter 1 | 5 | −0.6224 |
| 3 | filter 1 | 5 | −0.1055 |
| 4 | filter 1 | 5 | 0.9085 |
| 5 | filter 1 | 5 | 0.1758 |
| 1 | filter 2 | 1 | −0.9771 |
| 2 | filter 2 | 1 | 0.5945 |
| 3 | filter 2 | 1 | 0.2706 |
| 4 | filter 2 | 1 | 0.1771 |
| 5 | filter 2 | 1 | −0.2865 |
| 1 | filter 2 | 2 | 0.5769 |
| 2 | filter 2 | 2 | 0.9765 |
| 3 | filter 2 | 2 | 0.3225 |
| 4 | filter 2 | 2 | 0.1254 |
| 5 | filter 2 | 2 | 0.2983 |
| 1 | filter 2 | 3 | 0.1105 |
| 2 | filter 2 | 3 | −0.2159 |
| 3 | filter 2 | 3 | 0.4110 |
| 4 | filter 2 | 3 | −0.3837 |
| 5 | filter 2 | 3 | 0.2701 |
| 1 | filter 2 | 4 | −0.6632 |
| 2 | filter 2 | 4 | −0.3980 |
| 3 | filter 2 | 4 | −0.1981 |
| 4 | filter 2 | 4 | −0.0054 |
| 5 | filter 2 | 4 | 0.5709 |
| 1 | filter 2 | 5 | −0.7142 |
| 2 | filter 2 | 5 | 0.1280 |
| 3 | filter 2 | 5 | 0.3657 |
| 4 | filter 2 | 5 | −0.4053 |
| 5 | filter 2 | 5 | −0.2846 |
| 1 | filter 3 | 1 | −0.9417 |
| 2 | filter 3 | 1 | −0.4792 |
| 3 | filter 3 | 1 | 0.2015 |
| 4 | filter 3 | 1 | −0.7629 |
| 5 | filter 3 | 1 | 0.6295 |
| 1 | filter 3 | 2 | 0.0084 |
| 2 | filter 3 | 2 | 0.0880 |
| 3 | filter 3 | 2 | −0.3141 |
| 4 | filter 3 | 2 | −0.8493 |
| 5 | filter 3 | 2 | −0.5164 |
First 60 of 100 rows.
Each map is the input filtered by one first-layer kernel, after the ReLU.
View data
| Column | Panel | Row | Activation |
|---|---|---|---|
| 1 | input | 1 | 0 |
| 2 | input | 1 | 0 |
| 3 | input | 1 | 0.3125 |
| 4 | input | 1 | 0.8125 |
| 5 | input | 1 | 0.5625 |
| 6 | input | 1 | 0.0625 |
| 7 | input | 1 | 0 |
| 8 | input | 1 | 0 |
| 1 | input | 2 | 0 |
| 2 | input | 2 | 0 |
| 3 | input | 2 | 0.8125 |
| 4 | input | 2 | 0.9375 |
| 5 | input | 2 | 0.6250 |
| 6 | input | 2 | 0.9375 |
| 7 | input | 2 | 0.3125 |
| 8 | input | 2 | 0 |
| 1 | input | 3 | 0 |
| 2 | input | 3 | 0.1875 |
| 3 | input | 3 | 0.9375 |
| 4 | input | 3 | 0.1250 |
| 5 | input | 3 | 0 |
| 6 | input | 3 | 0.6875 |
| 7 | input | 3 | 0.5000 |
| 8 | input | 3 | 0 |
| 1 | input | 4 | 0 |
| 2 | input | 4 | 0.2500 |
| 3 | input | 4 | 0.7500 |
| 4 | input | 4 | 0 |
| 5 | input | 4 | 0 |
| 6 | input | 4 | 0.5000 |
| 7 | input | 4 | 0.5000 |
| 8 | input | 4 | 0 |
| 1 | input | 5 | 0 |
| 2 | input | 5 | 0.3125 |
| 3 | input | 5 | 0.5000 |
| 4 | input | 5 | 0 |
| 5 | input | 5 | 0 |
| 6 | input | 5 | 0.5625 |
| 7 | input | 5 | 0.5000 |
| 8 | input | 5 | 0 |
| 1 | input | 6 | 0 |
| 2 | input | 6 | 0.2500 |
| 3 | input | 6 | 0.6875 |
| 4 | input | 6 | 0 |
| 5 | input | 6 | 0.0625 |
| 6 | input | 6 | 0.7500 |
| 7 | input | 6 | 0.4375 |
| 8 | input | 6 | 0 |
| 1 | input | 7 | 0 |
| 2 | input | 7 | 0.1250 |
| 3 | input | 7 | 0.8750 |
| 4 | input | 7 | 0.3125 |
| 5 | input | 7 | 0.6250 |
| 6 | input | 7 | 0.7500 |
| 7 | input | 7 | 0 |
| 8 | input | 7 | 0 |
| 1 | input | 8 | 0 |
| 2 | input | 8 | 0 |
| 3 | input | 8 | 0.3750 |
| 4 | input | 8 | 0.8125 |
First 60 of 320 rows.
View data
| Actual | Rows | Predicted |
|---|---|---|
| false | 389 | false |
| false | 11 | true |
| true | 36 | false |
| true | 364 | true |
Cross-validation
| Fold | Repeat | n | ROC AUC | log loss | accuracy | balanced accuracy |
|---|---|---|---|---|---|---|
| 1 | 1 | 267 | 0.9873 | 0.2250 | 0.9288 | 0.9287 |
| 2 | 1 | 267 | 0.9889 | 0.2113 | 0.9363 | 0.9365 |
| 3 | 1 | 266 | 0.9948 | 0.1968 | 0.9586 | 0.9586 |
Out-of-fold confusion matrix (rows: actual)
| Actual | false | true | Recall |
|---|---|---|---|
| false | 389 | 11 | 0.9725 |
| true | 36 | 364 | 0.9100 |
Training curves
| Network | Epoch | Training loss | Validation loss |
|---|---|---|---|
| CNN | 1 | 0.0887 | — |
| CNN | 2 | 0.0720 | — |
| CNN | 3 | 0.0710 | — |
| CNN | 4 | 0.0672 | — |
| CNN | 5 | 0.0628 | — |
| CNN | 6 | 0.0602 | — |
| CNN | 7 | 0.0580 | — |
| CNN | 8 | 0.0552 | — |
| CNN | 9 | 0.0519 | — |
| CNN | 10 | 0.0486 | — |
| CNN | 11 | 0.0456 | — |
| CNN | 12 | 0.0428 | — |
| CNN | 13 | 0.0402 | — |
| CNN | 14 | 0.0378 | — |
| CNN | 15 | 0.0359 | — |
| CNN | 16 | 0.0340 | — |
| CNN | 17 | 0.0323 | — |
| CNN | 18 | 0.0310 | — |
| CNN | 19 | 0.0296 | — |
| CNN | 20 | 0.0283 | — |
| CNN | 21 | 0.0272 | — |
| CNN | 22 | 0.0260 | — |
| CNN | 23 | 0.0249 | — |
| CNN | 24 | 0.0239 | — |
| CNN | 25 | 0.0228 | — |
| CNN | 26 | 0.0219 | — |
| CNN | 27 | 0.0211 | — |
| CNN | 28 | 0.0203 | — |
| CNN | 29 | 0.0196 | — |
| CNN | 30 | 0.0190 | — |
| CNN | 31 | 0.0183 | — |
| CNN | 32 | 0.0178 | — |
| CNN | 33 | 0.0172 | — |
| CNN | 34 | 0.0166 | — |
| CNN | 35 | 0.0160 | — |
| CNN | 36 | 0.0155 | — |
| CNN | 37 | 0.0150 | — |
| CNN | 38 | 0.0145 | — |
| CNN | 39 | 0.0141 | — |
| CNN | 40 | 0.0136 | — |
First 40 of 60 rows.
The exact R script · R R version 4.5.1 (2025-06-13)
# Convolutional neural network (CNN)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.cnn 1.4.1 · spec a7a95a92e91bdbb5
# Dataset: ml_digits (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# torch for R (LibTorch); the network is built by codesplashr's cs_deep_fit_cnn twin.
# %% Data and split plan
TARGET <- "odd"
FEATURES <- c("r0c0", "r0c1", "r0c2", "r0c3", "r0c4", "r0c5", "r0c6", "r0c7", "r1c0", "r1c1", "r1c2", "r1c3", "r1c4", "r1c5", "r1c6", "r1c7", "r2c0", "r2c1", "r2c2", "r2c3", "r2c4", "r2c5", "r2c6", "r2c7", "r3c0", "r3c1", "r3c2", "r3c3", "r3c4", "r3c5", "r3c6", "r3c7", "r4c0", "r4c1", "r4c2", "r4c3", "r4c4", "r4c5", "r4c6", "r4c7", "r5c0", "r5c1", "r5c2", "r5c3", "r5c4", "r5c5", "r5c6", "r5c7", "r6c0", "r6c1", "r6c2", "r6c3", "r6c4", "r6c5", "r6c6", "r6c7", "r7c0", "r7c1", "r7c2", "r7c3", "r7c4", "r7c5", "r7c6", "r7c7")
TASK <- "binary"
CLASSES <- c("false", "true")
POSITIVE <- "true"
METRIC <- "roc_auc"
SEED <- 42
PARAMS <- list(
image_width = 8,
conv_blocks = 1,
filters = 4,
kernel_size = 5,
dense_units = 0,
dropout = 0,
epochs = 60,
learning_rate = 0.02,
batch_size = NULL,
weight_decay = 0.001,
early_stopping = 0,
validation_fraction = 0.1,
semi_supervised = "none",
fixmatch_threshold = 0.95,
fixmatch_weight = 1,
fixmatch_ratio = 2,
fixmatch_flip = FALSE,
loss = "focal",
focal_gamma = 2,
focal_alpha = 0.25,
optimizer = "default",
lr_schedule = "none",
warmup_epochs = 0,
grad_clip = 0,
ema_decay = 0,
swa_start = 0,
label_smoothing = 0,
mixup_alpha = 0,
history_every_step = FALSE,
profile = "parity",
checkpoint_every = NULL
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_digits.parquet", col_select = unique(c(TARGET, FEATURES))))
plan <- cs_ml_read_plan("target/academy-parity/run-97055/learn.cnn/binary_odd_focal_alpha_full_batch/folds.parquet") # host-written folds: identical in Python and R
design <- cs_ml_design(
df, FEATURES,
kinds = list(
r0c0 = "numeric",
r0c1 = "numeric",
r0c2 = "numeric",
r0c3 = "numeric",
r0c4 = "numeric",
r0c5 = "numeric",
r0c6 = "numeric",
r0c7 = "numeric",
r1c0 = "numeric",
r1c1 = "numeric",
r1c2 = "numeric",
r1c3 = "numeric",
r1c4 = "numeric",
r1c5 = "numeric",
r1c6 = "numeric",
r1c7 = "numeric",
r2c0 = "numeric",
r2c1 = "numeric",
r2c2 = "numeric",
r2c3 = "numeric",
r2c4 = "numeric",
r2c5 = "numeric",
r2c6 = "numeric",
r2c7 = "numeric",
r3c0 = "numeric",
r3c1 = "numeric",
r3c2 = "numeric",
r3c3 = "numeric",
r3c4 = "numeric",
r3c5 = "numeric",
r3c6 = "numeric",
r3c7 = "numeric",
r4c0 = "numeric",
r4c1 = "numeric",
r4c2 = "numeric",
r4c3 = "numeric",
r4c4 = "numeric",
r4c5 = "numeric",
r4c6 = "numeric",
r4c7 = "numeric",
r5c0 = "numeric",
r5c1 = "numeric",
r5c2 = "numeric",
r5c3 = "numeric",
r5c4 = "numeric",
r5c5 = "numeric",
r5c6 = "numeric",
r5c7 = "numeric",
r6c0 = "numeric",
r6c1 = "numeric",
r6c2 = "numeric",
r6c3 = "numeric",
r6c4 = "numeric",
r6c5 = "numeric",
r6c6 = "numeric",
r6c7 = "numeric",
r7c0 = "numeric",
r7c1 = "numeric",
r7c2 = "numeric",
r7c3 = "numeric",
r7c4 = "numeric",
r7c5 = "numeric",
r7c6 = "numeric",
r7c7 = "numeric"
),
levels = list(
),
impute = "median",
scale = "none",
indicators = FALSE
)
target <- cs_ml_encode_target(df[[TARGET]], TASK, CLASSES, POSITIVE)
y <- target$fit
y_index <- target$index
weights <- cs_ml_class_weights(y_index, TASK, "none", plan$train)
run <- cs_ml_run(TASK, CLASSES, POSITIVE, METRIC)
out <- cs_ml_out_dir("target/academy-parity/run-97055/learn.cnn/binary_odd_focal_alpha_full_batch/out-r")
warnings <- list()
sample_weights <- function(rows) if (is.null(weights)) NULL else weights[rows + 1L]
rows_of <- function(rows) df[rows + 1L, , drop = FALSE]
RESAMPLE <- "none"
if (RESAMPLE != "none" && TASK == "regression") {
warnings <- c(warnings, list("Resampling applies to classification only — ignored for this regression target."))
}
resampled <- NULL # the final model's resampling summary
notes <- list()
# A fit's design matrix, targets and weights: training rows only, resampled when asked
# (cs_ml_resample — the same rows in Python, from the shared random stream).
training_set <- function(X, rows, fold_id, repeat_) {
yy <- y[rows + 1L]
ww <- sample_weights(rows)
if (RESAMPLE == "none" || TASK == "regression") return(list(X = X, y = yy, w = ww))
r <- cs_ml_resample(X, yy, ww, RESAMPLE, ratio = 1, k = as.integer(5),
seed = cs_ml_resample_seed(SEED, fold_id, repeat_))
if (fold_id == 0) resampled <<- r$info
r
}
fit_on <- function(s) fit_model(s$X, s$y, s$w)
# %% Model
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
optimizer = "default",
lr_schedule = "none",
warmup_epochs = 0,
grad_clip = 0,
ema_decay = 0,
swa_start = 0,
label_smoothing = 0,
mixup_alpha = 0,
history_every_step = FALSE,
profile = "parity",
checkpoint_every = NULL
), out_dir = "target/academy-parity/run-97055/learn.cnn/binary_odd_focal_alpha_full_batch/out-r")
.deep_folds <- length(if (0 > 0) utils::head(plan$folds, 0) else plan$folds)
.deep_training_set <- training_set
# Tell the trainer which fit comes next (cross-validation fold i, or the final model), then build the
# training set as _ml_learn does.
training_set <- function(X, rows, fold_id, repeat_) {
cs_deep_trainer_set_fold(as.integer(fold_id), .deep_folds, if (fold_id > 0) "cv" else "final")
.deep_training_set(X, rows, fold_id, repeat_)
}
# A small convolutional network on torch for R (float64, one thread). Each row's design columns are the
# pixels of one grayscale image, row by row; blocks of convolution -> ReLU -> 2 x 2 max pooling feed a dense
# layer and the output layer. Pixels are divided by the training rows' largest value. Initial weights,
# batches, dropout masks and early-stopping rows come from the shared random stream, so Python's torch
# trains the same network.
# Focal loss (Lin et al. 2017) instead of cross-entropy on the training batches: rows the network already gets
# right count less (cs_deep_focal_* through the trainer; twin: codesplash.deep.trainer.set_loss).
cs_deep_trainer_set_loss(PARAMS$loss, gamma = PARAMS$focal_gamma, alpha = PARAMS$focal_alpha, task = TASK)
fit_model <- function(X, y, w) {
if (TASK == "binary") {
target <- as.numeric(y); o <- 1L
} else {
target <- cs_deep_one_hot(y, length(CLASSES)); o <- length(CLASSES)
}
cs_deep_fit_cnn(
unname(X), target, w, TASK, o,
image_width = if (is.null(PARAMS$image_width)) NULL else as.integer(PARAMS$image_width),
conv_blocks = as.integer(PARAMS$conv_blocks),
filters = as.integer(PARAMS$filters),
kernel_size = as.integer(PARAMS$kernel_size),
dense_units = as.integer(PARAMS$dense_units),
dropout = PARAMS$dropout,
epochs = as.integer(PARAMS$epochs),
lr = PARAMS$learning_rate,
batch_size = if (is.null(PARAMS$batch_size)) NULL else as.integer(PARAMS$batch_size),
weight_decay = PARAMS$weight_decay,
early_stopping = as.integer(PARAMS$early_stopping) > 0,
validation_fraction = PARAMS$validation_fraction,
patience = max(1L, as.integer(PARAMS$early_stopping)),
seed = SEED
)
}
predict_model <- function(model, X) cs_deep_cnn_predict(model, unname(X), TASK)
feature_importance <- function(model, names) NULL
save_model <- function(model, directory) {
path <- file.path(directory, "model.rds")
saveRDS(model, path) # plain numeric weights, the architecture and the pixel scale
hist <- file.path(directory, "history.parquet")
nanoparquet::write_parquet(cs_deep_history_frame(model$history), hist)
list(list(key = "model", path = path, format = "rds"), list(key = "history", path = hist, format = "parquet"))
}
load_model <- function(directory) readRDS(file.path(directory, "model.rds"))
# %% Cross-validation
folds <- if (0 > 0) utils::head(plan$folds, 0) else plan$folds
progress <- cs_progress("Cross-validating", total = length(folds))
for (i in seq_along(folds)) {
fold <- folds[[i]]
prep <- cs_ml_design_fit(design, rows_of(fold$train))
model <- fit_on(training_set(cs_ml_design_apply(prep, rows_of(fold$train)), fold$train, fold$id, fold$repeat_))
cs_ml_add(run, fold$id, fold$repeat_, "valid", fold$valid, y, y_index,
predict_model(model, cs_ml_design_apply(prep, rows_of(fold$valid))))
cs_progress_update(progress, i, sprintf("Fold %d of %d", i, length(folds)))
}
cs_ml_lap(run, "cv_seconds")
# %% Final model
artifacts <- list()
importance <- NULL
prep <- cs_ml_design_fit(design, rows_of(plan$train))
names_ <- cs_ml_design_names(prep)
if (TRUE) {
model <- fit_on(training_set(cs_ml_design_apply(prep, rows_of(plan$train)), plan$train, 0L, 0L))
if (!is.null(resampled)) {
warnings <- c(warnings, as.list(resampled$notes))
notes <- c(notes, list(cs_ml_resample_describe(resampled)))
}
if (length(plan$test)) {
cs_ml_add(run, 0L, 0L, "test", plan$test, y, y_index,
predict_model(model, cs_ml_design_apply(prep, rows_of(plan$test))))
}
importance <- feature_importance(model, names_)
artifacts[[length(artifacts) + 1L]] <- list(
key = "design", path = cs_ml_save_json(cs_ml_design_json(prep), file.path(out, "design.json")), format = "json"
)
artifacts <- c(artifacts, save_model(model, out))
cs_ml_lap(run, "final_seconds")
}
artifacts[[length(artifacts) + 1L]] <- list(key = "predictions", path = cs_ml_write(run, out), format = "parquet")
cs_progress_done(progress)
# %% Result
cs_publish(cs_deep_extend_cnn(cs_ml_result(
run,
title = "Convolutional neural network (CNN)",
engine = cs_engine_info("torch", "codesplashr", "nanoparquet"),
n_features = length(names_),
n_train = length(plan$train),
n_test = length(plan$test),
params = PARAMS,
features = names_,
importance = importance,
artifacts = artifacts,
warnings = warnings,
notes = notes
), model, names_, run, cs_ml_design_apply(prep, rows_of(plan$train[1])), CLASSES))
Convolutional neural network (CNN): cross-validated ROC AUC 0.990 ± 0.004 over 3 folds; ROC AUC on the locked test set 0.997 (n = 200).
- CV ROC AUC
- 0.9903
- SD across folds
- 0.0039
- Test ROC AUC
- 0.9973
To keep this page light, the plots are shown once, under the R tab.
Cross-validation
| Fold | Repeat | n | ROC AUC | log loss | accuracy | balanced accuracy |
|---|---|---|---|---|---|---|
| 1 | 1 | 267 | 0.9873 | 0.2250 | 0.9288 | 0.9287 |
| 2 | 1 | 267 | 0.9889 | 0.2113 | 0.9363 | 0.9365 |
| 3 | 1 | 266 | 0.9948 | 0.1968 | 0.9586 | 0.9586 |
Out-of-fold confusion matrix (rows: actual)
| Actual | false | true | Recall |
|---|---|---|---|
| false | 389 | 11 | 0.9725 |
| true | 36 | 364 | 0.9100 |
Training curves
| Network | Epoch | Training loss | Validation loss |
|---|---|---|---|
| CNN | 1 | 0.0887 | — |
| CNN | 2 | 0.0720 | — |
| CNN | 3 | 0.0710 | — |
| CNN | 4 | 0.0672 | — |
| CNN | 5 | 0.0628 | — |
| CNN | 6 | 0.0602 | — |
| CNN | 7 | 0.0580 | — |
| CNN | 8 | 0.0552 | — |
| CNN | 9 | 0.0519 | — |
| CNN | 10 | 0.0486 | — |
| CNN | 11 | 0.0456 | — |
| CNN | 12 | 0.0428 | — |
| CNN | 13 | 0.0402 | — |
| CNN | 14 | 0.0378 | — |
| CNN | 15 | 0.0359 | — |
| CNN | 16 | 0.0340 | — |
| CNN | 17 | 0.0323 | — |
| CNN | 18 | 0.0310 | — |
| CNN | 19 | 0.0296 | — |
| CNN | 20 | 0.0283 | — |
| CNN | 21 | 0.0272 | — |
| CNN | 22 | 0.0260 | — |
| CNN | 23 | 0.0249 | — |
| CNN | 24 | 0.0239 | — |
| CNN | 25 | 0.0228 | — |
| CNN | 26 | 0.0219 | — |
| CNN | 27 | 0.0211 | — |
| CNN | 28 | 0.0203 | — |
| CNN | 29 | 0.0196 | — |
| CNN | 30 | 0.0190 | — |
| CNN | 31 | 0.0183 | — |
| CNN | 32 | 0.0178 | — |
| CNN | 33 | 0.0172 | — |
| CNN | 34 | 0.0166 | — |
| CNN | 35 | 0.0160 | — |
| CNN | 36 | 0.0155 | — |
| CNN | 37 | 0.0150 | — |
| CNN | 38 | 0.0145 | — |
| CNN | 39 | 0.0141 | — |
| CNN | 40 | 0.0136 | — |
First 40 of 60 rows.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Convolutional neural network (CNN)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method learn.cnn 1.4.1 · spec a7a95a92e91bdbb5
# Dataset: ml_digits (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.deep import core as deep
from codesplash.deep import cnn as deepcnn # twin of codesplashr::cs_deep_fit_cnn (shared weights, AdamW written out)
# %% Data and split plan
TARGET = "odd"
FEATURES = ["r0c0", "r0c1", "r0c2", "r0c3", "r0c4", "r0c5", "r0c6", "r0c7", "r1c0", "r1c1", "r1c2", "r1c3", "r1c4", "r1c5", "r1c6", "r1c7", "r2c0", "r2c1", "r2c2", "r2c3", "r2c4", "r2c5", "r2c6", "r2c7", "r3c0", "r3c1", "r3c2", "r3c3", "r3c4", "r3c5", "r3c6", "r3c7", "r4c0", "r4c1", "r4c2", "r4c3", "r4c4", "r4c5", "r4c6", "r4c7", "r5c0", "r5c1", "r5c2", "r5c3", "r5c4", "r5c5", "r5c6", "r5c7", "r6c0", "r6c1", "r6c2", "r6c3", "r6c4", "r6c5", "r6c6", "r6c7", "r7c0", "r7c1", "r7c2", "r7c3", "r7c4", "r7c5", "r7c6", "r7c7"]
TASK = "binary"
CLASSES = ["false", "true"]
POSITIVE = "true"
METRIC = "roc_auc"
SEED = 42
PARAMS = {
"image_width": 8,
"conv_blocks": 1,
"filters": 4,
"kernel_size": 5,
"dense_units": 0,
"dropout": 0,
"epochs": 60,
"learning_rate": 0.02,
"batch_size": None,
"weight_decay": 0.001,
"early_stopping": 0,
"validation_fraction": 0.1,
"semi_supervised": "none",
"fixmatch_threshold": 0.95,
"fixmatch_weight": 1,
"fixmatch_ratio": 2,
"fixmatch_flip": False,
"loss": "focal",
"focal_gamma": 2,
"focal_alpha": 0.25,
"optimizer": "default",
"lr_schedule": "none",
"warmup_epochs": 0,
"grad_clip": 0,
"ema_decay": 0,
"swa_start": 0,
"label_smoothing": 0,
"mixup_alpha": 0,
"history_every_step": False,
"profile": "parity",
"checkpoint_every": None,
}
df = pd.read_parquet("tests/parity/fixtures/ml_digits.parquet", columns=list(dict.fromkeys([TARGET] + FEATURES)))
plan = csml.read_plan("target/academy-parity/run-97055/learn.cnn/binary_odd_focal_alpha_full_batch/folds.parquet") # host-written folds: identical in Python and R
design = csml.Design.for_frame(
df,
FEATURES,
kinds={
"r0c0": "numeric",
"r0c1": "numeric",
"r0c2": "numeric",
"r0c3": "numeric",
"r0c4": "numeric",
"r0c5": "numeric",
"r0c6": "numeric",
"r0c7": "numeric",
"r1c0": "numeric",
"r1c1": "numeric",
"r1c2": "numeric",
"r1c3": "numeric",
"r1c4": "numeric",
"r1c5": "numeric",
"r1c6": "numeric",
"r1c7": "numeric",
"r2c0": "numeric",
"r2c1": "numeric",
"r2c2": "numeric",
"r2c3": "numeric",
"r2c4": "numeric",
"r2c5": "numeric",
"r2c6": "numeric",
"r2c7": "numeric",
"r3c0": "numeric",
"r3c1": "numeric",
"r3c2": "numeric",
"r3c3": "numeric",
"r3c4": "numeric",
"r3c5": "numeric",
"r3c6": "numeric",
"r3c7": "numeric",
"r4c0": "numeric",
"r4c1": "numeric",
"r4c2": "numeric",
"r4c3": "numeric",
"r4c4": "numeric",
"r4c5": "numeric",
"r4c6": "numeric",
"r4c7": "numeric",
"r5c0": "numeric",
"r5c1": "numeric",
"r5c2": "numeric",
"r5c3": "numeric",
"r5c4": "numeric",
"r5c5": "numeric",
"r5c6": "numeric",
"r5c7": "numeric",
"r6c0": "numeric",
"r6c1": "numeric",
"r6c2": "numeric",
"r6c3": "numeric",
"r6c4": "numeric",
"r6c5": "numeric",
"r6c6": "numeric",
"r6c7": "numeric",
"r7c0": "numeric",
"r7c1": "numeric",
"r7c2": "numeric",
"r7c3": "numeric",
"r7c4": "numeric",
"r7c5": "numeric",
"r7c6": "numeric",
"r7c7": "numeric",
},
levels={
},
impute="median",
scale="none",
indicators=False,
)
y, y_index = csml.encode_target(df[TARGET], TASK, CLASSES, POSITIVE)
weights = csml.class_weights(y_index, TASK, "none", plan.train)
run = csml.LearnerRun(TASK, CLASSES, POSITIVE, METRIC)
out = csml.out_dir("target/academy-parity/run-97055/learn.cnn/binary_odd_focal_alpha_full_batch/out-python")
warnings = []
def sample_weights(rows):
return None if weights is None else weights[rows]
RESAMPLE = "none"
if RESAMPLE != "none" and TASK == "regression":
warnings.append("Resampling applies to classification only — ignored for this regression target.")
resampled = None # the final model's resampling summary
notes = []
def training_set(X, rows, fold_id, repeat):
"""A fit's design matrix, targets and weights: training rows only, resampled when asked
(codesplash.ml.resample — the same rows in R, from the shared random stream)."""
yy, ww = y[rows], sample_weights(rows)
if RESAMPLE == "none" or TASK == "regression":
return X, yy, ww
from codesplash.ml import resample as csres
X2, y2, w2, info = csres.resample(
X, yy, ww, RESAMPLE, ratio=1, k=5, seed=csres.resample_seed(SEED, fold_id, repeat)
)
if fold_id == 0:
global resampled
resampled = info
return X2, y2, w2
# %% Model
from codesplash.deep import trainer as deep_trainer # training options, live progress, checkpoints (twin: cs_deep_trainer_*)
deep_trainer.configure(
{
"optimizer": "default",
"lr_schedule": "none",
"warmup_epochs": 0,
"grad_clip": 0,
"ema_decay": 0,
"swa_start": 0,
"label_smoothing": 0,
"mixup_alpha": 0,
"history_every_step": False,
"profile": "parity",
"checkpoint_every": None,
},
out_dir="target/academy-parity/run-97055/learn.cnn/binary_odd_focal_alpha_full_batch/out-python",
)
_DEEP_FOLDS = len(plan.folds[: 0] if 0 else plan.folds)
_deep_training_set = training_set
def training_set(X, rows, fold_id, repeat):
"""Tell the trainer which fit comes next (cross-validation fold i, or the final model), then build
the training set as _ml_learn does."""
deep_trainer.set_fold(int(fold_id), _DEEP_FOLDS, "cv" if fold_id else "final")
return _deep_training_set(X, rows, fold_id, repeat)
# A small convolutional network on PyTorch (float64, one thread). Each row's design columns are the pixels
# of one grayscale image, row by row; blocks of convolution -> ReLU -> 2 x 2 max pooling feed a dense layer
# and the output layer. Pixels are divided by the training rows' largest value. Initial weights, batches,
# dropout masks and early-stopping rows come from the shared random stream, so R's torch trains the same
# network.
# Focal loss (Lin et al. 2017) instead of cross-entropy on the training batches: rows the network already gets
# right count less (codesplash.deep.focal through the trainer; twin: cs_deep_trainer_set_loss).
deep_trainer.set_loss(PARAMS["loss"], gamma=PARAMS["focal_gamma"], alpha=PARAMS["focal_alpha"], task=TASK)
def fit_model(X, y, w):
if TASK == "binary":
target, o = np.asarray(y, dtype=np.float64), 1
else:
target, o = deep.one_hot(y, len(CLASSES)), len(CLASSES)
return deepcnn.fit_cnn(
X, target, w, TASK, o,
image_width=None if PARAMS["image_width"] is None else int(PARAMS["image_width"]),
conv_blocks=int(PARAMS["conv_blocks"]),
filters=int(PARAMS["filters"]),
kernel_size=int(PARAMS["kernel_size"]),
dense_units=int(PARAMS["dense_units"]),
dropout=PARAMS["dropout"],
epochs=int(PARAMS["epochs"]),
lr=PARAMS["learning_rate"],
batch_size=None if PARAMS["batch_size"] is None else int(PARAMS["batch_size"]),
weight_decay=PARAMS["weight_decay"],
early_stopping=int(PARAMS["early_stopping"]) > 0,
validation_fraction=PARAMS["validation_fraction"],
patience=max(1, int(PARAMS["early_stopping"])),
seed=SEED,
)
def predict_model(model, X):
return deepcnn.cnn_predict(model, X, TASK)
def feature_importance(model, names):
return None
def save_model(model, directory):
import joblib
path = os.path.join(directory, "model.joblib")
joblib.dump(model, path) # plain numpy weights, the architecture and the pixel scale
hist = os.path.join(directory, "history.parquet")
deep.history_frame(model["history"]).to_parquet(hist, index=False)
return [{"key": "model", "path": path, "format": "joblib"}, {"key": "history", "path": hist, "format": "parquet"}]
def load_model(directory):
import joblib
return joblib.load(os.path.join(directory, "model.joblib"))
# %% Cross-validation
folds = plan.folds[: 0] if 0 else plan.folds
progress = cs.progress("Cross-validating", total=len(folds))
for i, fold in enumerate(folds):
prep = design.fit(df.iloc[fold.train])
model = fit_model(*training_set(prep.transform(df.iloc[fold.train]), fold.train, fold.id, fold.repeat))
run.add(fold.id, fold.repeat, "valid", fold.valid, y, y_index, predict_model(model, prep.transform(df.iloc[fold.valid])))
progress.update(i + 1, f"Fold {i + 1} of {len(folds)}")
run.lap("cv_seconds")
# %% Final model
artifacts = []
importance = None
prep = design.fit(df.iloc[plan.train])
names = prep.names
if True:
model = fit_model(*training_set(prep.transform(df.iloc[plan.train]), plan.train, 0, 0))
if resampled is not None:
from codesplash.ml import resample as csres
warnings.extend(resampled["notes"])
notes.append(csres.describe(resampled))
if len(plan.test):
run.add(0, 0, "test", plan.test, y, y_index, predict_model(model, prep.transform(df.iloc[plan.test])))
importance = feature_importance(model, names)
artifacts.append({"key": "design", "path": csml.save_json(prep.to_json(), os.path.join(out, "design.json")), "format": "json"})
artifacts.extend(save_model(model, out))
run.lap("final_seconds")
artifacts.append({"key": "predictions", "path": run.write(out), "format": "parquet"})
progress.done()
# %% Result
cs.publish(
deepcnn.extend_cnn(run.result(
title="Convolutional neural network (CNN)",
engine=cs.engine_info("torch", "codesplash", "numpy", "pandas"),
n_features=len(names),
n_train=len(plan.train),
n_test=len(plan.test),
params=PARAMS,
features=names,
importance=importance,
artifacts=artifacts,
warnings=warnings,
notes=notes,
), model, names, run, prep.transform(df.iloc[plan.train[:1]]), CLASSES)
)
These digits are balanced, so there is little to focus on. Accuracy is 94.1%, against 96.3% with cross-entropy, and log loss rises from 0.104 to 0.211: focal loss stops pushing easy rows toward 0 or 1. It pays off when easy examples vastly outnumber hard ones, as background boxes do.
The same trade in a table
ExploreRare positives make accuracy and plain losses misleading in any classifier, not only detectors. Shrink the positive class and watch what a model optimizing accuracy learns to do.
HExplorable · Rare events and the decision threshold
Why can a 98% accurate model be useless, and where should the threshold go?
A lazy model calls every case negative. What accuracy does it score?
| flagged | passed | |
|---|---|---|
| pos | 52 | 62 |
| neg | 312 | 4574 |
Bars are drawn to one count scale, so a rare positive class looks as rare as it is. The ROC curve barely notices the imbalance; the precision–recall curve shows it. Cheapest threshold here: 1.14; the binormal formula gives 1.35.
Commit your prediction above to see the result
Make your prediction to see the result.
DETR: predict a set
ReadDETR treats detection as set predictionSet prediction (DETR)Predicting a fixed set of boxes and matching them one-to-one to the labeled objects, so no anchors or NMS are needed.. A Transformer decoder turns a fixed number of learned object queries, say 100, into 100 predictions. Training matches them one-to-one to the labeled objects with the Hungarian methodHungarian method (linear assignment)Pairs two lists (tracks and detections) one-to-one so the total cost is smallest; ties go to the lowest index in CodeSplash., using a cost that mixes class probability and box distance; every unmatched query is taught to say "no object".
In the program three queries meet two objects. The cheapest matching gives object 0 to query 0 and object 1 to query 1, at total cost 0.500; query 2 becomes background.
No anchors, no duplicates?
PredictPredict first
Does DETR need non-maximum suppression after prediction?
Reveal
No. Each labeled object is matched to exactly one query, so a second query predicting the same object is trained toward "no object". Duplicates are punished during training instead of deleted afterwards.
Deformable DETR: look at a few points
ReadDETR trained slowly and missed small objects: each query attended to every pixel of a coarse map. Deformable attentionDeformable attentionEach query looks at a few learned sample points near a reference point, not at every pixel, so attention stays cheap. lets each query look at a few sample points around a reference point, with learned offsets and weights, across several resolutions.
The points fall between pixels, so their values come from bilinear interpolation. In the program two points read 2.75 and 5.25; with attention weights 0.711 and 0.289 the output is their weighted average, 3.473.
What runs here
ReadAcross 9 images and 3 classes, AP (IoU 0.50:0.95) = 1.000, AP50 = 1.000 and AP75 = 1.000; average recall with up to 100 detections per image = 1.000. At IoU 0.50: 26 true positives, 0 false positives, 0 missed objects.
- AP (0.50:0.95)
- 1
- AP50
- 1
- AP75
- 1
- AR@100
- 1
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 303 rows.
View data
| label | Measure | Average precision |
|---|---|---|
| bicycle | AP | 1 |
| bicycle | AP50 | 1 |
| bicycle | AP75 | 1 |
| car | AP | 1 |
| car | AP50 | 1 |
| car | AP75 | 1 |
| person | AP | 1 |
| person | AP50 | 1 |
| person | AP75 | 1 |
Assumptions
- Every object is labeled — Predictions of objects that the reference doesn't list count as false positives.
- Predicted classes are in the reference — Every predicted class appears in the reference.
- 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 | 1 |
| AP | 0.50 | all | 100 | 1 |
| AP | 0.75 | all | 100 | 1 |
| AP | 0.50:0.95 | small | 100 | 1 |
| AP | 0.50:0.95 | medium | 100 | 1 |
| AP | 0.50:0.95 | large | 100 | 1 |
| AR | 0.50:0.95 | all | 1 | 0.7746 |
| AR | 0.50:0.95 | all | 10 | 1 |
| AR | 0.50:0.95 | all | 100 | 1 |
| AR | 0.50:0.95 | small | 100 | 1 |
| AR | 0.50:0.95 | medium | 100 | 1 |
| AR | 0.50:0.95 | large | 100 | 1 |
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 | 7 | 1 | 1 | 1 | 1 | 7 | 0 | 0 |
| car | 9 | 0 | 9 | 1 | 1 | 1 | 1 | 9 | 0 | 0 |
| person | 10 | 0 | 10 | 1 | 1 | 1 | 1 | 10 | 0 | 0 |
Per image at IoU 0.50
| media_id | Reference objects | Predictions | True positives | False positives | Missed |
|---|---|---|---|---|---|
| img01 | 2 | 2 | 2 | 0 | 0 |
| img02 | 3 | 3 | 3 | 0 | 0 |
| img03 | 5 | 5 | 5 | 0 | 0 |
| img04 | 2 | 2 | 2 | 0 | 0 |
| img05 | 4 | 4 | 4 | 0 | 0 |
| img06 | 2 | 2 | 2 | 0 | 0 |
| img07 | 2 | 2 | 2 | 0 | 0 |
| img08 | 3 | 3 | 3 | 0 | 0 |
| img10 | 3 | 3 | 3 | 0 | 0 |
- Reference rows: source = annotation; predictions: source = prediction. COCO conventions: IoU 0.50:0.05:0.95, 101 recall points, greedy matching by score within each image and class.
The exact R script · R 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 337343d72a5f065a
# Dataset: img4_perfect (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 <- NULL
AREA <- NULL
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_perfect.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/perfect-predictions/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
))
Across 9 images and 3 classes, AP (IoU 0.50:0.95) = 1.000, AP50 = 1.000 and AP75 = 1.000; average recall with up to 100 detections per image = 1.000. At IoU 0.50: 26 true positives, 0 false positives, 0 missed objects.
- AP (0.50:0.95)
- 1
- AP50
- 1
- AP75
- 1
- AR@100
- 1
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 — Every predicted class appears in the reference.
- 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 | 1 |
| AP | 0.50 | all | 100 | 1 |
| AP | 0.75 | all | 100 | 1 |
| AP | 0.50:0.95 | small | 100 | 1 |
| AP | 0.50:0.95 | medium | 100 | 1 |
| AP | 0.50:0.95 | large | 100 | 1 |
| AR | 0.50:0.95 | all | 1 | 0.7746 |
| AR | 0.50:0.95 | all | 10 | 1 |
| AR | 0.50:0.95 | all | 100 | 1 |
| AR | 0.50:0.95 | small | 100 | 1 |
| AR | 0.50:0.95 | medium | 100 | 1 |
| AR | 0.50:0.95 | large | 100 | 1 |
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 | 7 | 1 | 1 | 1 | 1 | 7 | 0 | 0 |
| car | 9 | 0 | 9 | 1 | 1 | 1 | 1 | 9 | 0 | 0 |
| person | 10 | 0 | 10 | 1 | 1 | 1 | 1 | 10 | 0 | 0 |
Per image at IoU 0.50
| media_id | Reference objects | Predictions | True positives | False positives | Missed |
|---|---|---|---|---|---|
| img01 | 2 | 2 | 2 | 0 | 0 |
| img02 | 3 | 3 | 3 | 0 | 0 |
| img03 | 5 | 5 | 5 | 0 | 0 |
| img04 | 2 | 2 | 2 | 0 | 0 |
| img05 | 4 | 4 | 4 | 0 | 0 |
| img06 | 2 | 2 | 2 | 0 | 0 |
| img07 | 2 | 2 | 2 | 0 | 0 |
| img08 | 3 | 3 | 3 | 0 | 0 |
| img10 | 3 | 3 | 3 | 0 | 0 |
- Reference rows: source = annotation; predictions: source = prediction. COCO conventions: IoU 0.50:0.05:0.95, 101 recall points, greedy matching by score within each image and class.
The exact Python script · Python 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 337343d72a5f065a
# Dataset: img4_perfect (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 = None
AREA = None
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_perfect.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/perfect-predictions/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,
})
Check: dense and set detectors
CheckpointCheck yourself
An image has 5 positive default boxes and 8,000 background boxes. With SSD's three-to-one rule, how many background boxes enter the loss?
Show the answer
Answer: 15
At most 3 × 5 = 15, the ones with the highest loss. The other 7,985 are skipped for this image.
Check yourself
Why does SSD predict from several feature maps instead of one?
Show the answer
Answer: a
A small object covers only a few cells of a coarse map. Predicting at several resolutions gives every object size a map that fits it.
Check yourself
With γ = 2, by what factor does focal loss scale the cross-entropy of a box classified with p = 0.9?
Show the answer
Answer: 0.01
(1 − 0.9)² = 0.01: a hundred times smaller. At p = 0.5 the factor is 0.25, so hard boxes keep much more weight.
Check yourself
What does focal loss become with γ = 0?
Show the answer
Answer: a
(1 − p)⁰ = 1, so nothing is down-weighted. γ sets how strongly easy examples fade.
Check yourself
You train the CNN with Loss: Focal loss, γ = 2, and early stopping on. Which loss decides when training stops?
Show the answer
Answer: a
Focal loss changes only the training batches. Early stopping compares epochs on the plain log loss of the validation rows, so runs with different γ are judged on the same scale.
Check yourself
A DETR model has 100 queries and an image has 3 labeled objects. How many queries are trained toward a box during one step?
Show the answer
Answer: a
The other 97 are trained toward "no object". The matching, not the score, decides which query owns which object.
Check yourself
Which pair of hand-made parts does DETR remove from the detection pipeline?
Show the answer
Answer: a
Learned queries replace anchors, and one-to-one matching replaces NMS.
Check yourself
Why does Deformable DETR train faster than DETR?
Show the answer
Answer: a
Sparse sampling cuts the attention cost and makes multi-scale features affordable, which also helps small objects.
Check yourself
A sample point lands between four feature cells. How does deformable attention read its value?
Show the answer
Answer: b
Interpolation keeps the offsets differentiable, so the network can learn where to look.
Recap
Recap- One-stage detectors score every location; easy background dominates a plain loss.
- SSD trains on the hardest negatives, three per positive; RetinaNet's focal loss fades easy examples.
- DETR predicts a set and matches it one-to-one to the objects, so it needs neither anchors nor NMS.
- Deformable attention samples a few interpolated points per query, which trains faster and helps small objects.
Concepts in this lesson