Skip to content

Ranking quality and detection errors

Some models are judged by the order they put things in, others by the two kinds of error at a threshold. Score rankings query by query with nDCG, MAP and MRR, and read a detector's DET curve, equal error rate and detection cost.

Advanced ~14 min7 steps

What runs in CodeSplash

You will be able to

  • Choose between nDCG, MAP, MRR, precision and recall at a cutoff for a ranking task
  • Compare two rankers query by query, with an interval and a paired test
  • Read a DET curve, the equal error rate and the minimum and actual detection cost

Read first

01

When the order is the answer

Read

A search box, a recommender or a triage queue doesn't hand back one prediction per row. It hands back a list per query, and people read the top of it. Accuracy can't see that: what matters is whether the relevant items come first.

02

Which ranking metric

Read

So ranking metrics are computed within each query and then averaged over queries:

MetricWhat it rewardsUse it when
nDCG@knDCG (normalized discounted cumulative gain)How well the top k results are ordered by relevance, from 0 to 1, where 1 is the best possible order of the judged items.relevant items high up, more relevant ones higher stillrelevance has grades (0–3)
MAPMean average precision (MAP)The average over queries of the precision at the rank of each relevant item, so it rewards putting every relevant item early.every relevant item early in the full listyou want all of them
MRR@kMean reciprocal rank (MRR)The average over queries of 1 / rank of the first relevant result (0 when none is in the top k); good when one hit is enough.the first relevant item earlyone good answer is enough
Recall@kfinding the relevant items within kthe list is a shortlist someone reads
Precision@ka clean top kscreen space is scarce

nDCG divides each result's gain by log⁡2(rank+1)\log_2(\text{rank} + 1) and compares the sum with the best possible order of that query's judged items, so 1 means "couldn't have been ordered better".

03

Two search systems, thirty queries

Read
Ranking qualityRecorded · Python and R agreeRecorded 2026-11-21 · 26 values compared
R

Across 30 queries for keyword, nDCG@10 = 0.873 (95% CI 0.827 to 0.916), MAP = 0.871, MRR@10 = 0.948 and recall@10 = 0.977. semantic − keyword: nDCG@10 +0.078 (95% CI 0.025 to 0.131, p = .008).

nDCG@10
0.8731
MAP
0.8710
MRR@10
0.9483
Recall@10
0.9765

Plots

nDCG and recall at each cutoffHow does ranking quality change as more of the top results are counted?
View data
Cutoff kMetricsystemMean over queries
1nDCGkeyword0.6667
2nDCGkeyword0.7783
3nDCGkeyword0.8082
4nDCGkeyword0.8315
5nDCGkeyword0.8400
6nDCGkeyword0.8470
7nDCGkeyword0.8607
8nDCGkeyword0.8641
9nDCGkeyword0.8702
10nDCGkeyword0.8731
1Recallkeyword0.1857
2Recallkeyword0.4059
3Recallkeyword0.5543
4Recallkeyword0.6785
5Recallkeyword0.7662
6Recallkeyword0.8295
7Recallkeyword0.8865
8Recallkeyword0.9256
9Recallkeyword0.9635
10Recallkeyword0.9765
1nDCGsemantic0.9080
2nDCGsemantic0.9099
3nDCGsemantic0.8939
4nDCGsemantic0.9274
5nDCGsemantic0.9367
6nDCGsemantic0.9390
7nDCGsemantic0.9465
8nDCGsemantic0.9462
9nDCGsemantic0.9491
10nDCGsemantic0.9510
1Recallsemantic0.2317
2Recallsemantic0.4375
3Recallsemantic0.5802
4Recallsemantic0.7274
5Recallsemantic0.8327
6Recallsemantic0.8784
7Recallsemantic0.9274
8Recallsemantic0.9462
9Recallsemantic0.9726
10Recallsemantic0.9899
nDCG@10 per queryHow does a numeric variable differ across groups?
View data
systemnDCG@10
keyword0.9794
keyword0.6399
keyword0.9525
keyword0.9763
keyword0.9781
keyword0.7775
keyword0.9766
keyword0.9924
keyword0.9050
keyword0.8428
keyword0.9515
keyword0.9966
keyword0.7171
keyword0.6193
keyword0.8308
keyword0.9562
keyword1
keyword0.9539
keyword0.9383
keyword0.8428
keyword0.8505
keyword0.9605
keyword0.9900
keyword0.7420
keyword0.6590
keyword0.7865
keyword0.8592
keyword0.9911
keyword0.6546
semantic1
semantic1
semantic0.9975
semantic0.9296
semantic0.7327
semantic0.8412
semantic0.9756
semantic0.9174
semantic0.9634
semantic0.9926
semantic0.7076
semantic0.9691
semantic0.9733
semantic0.9942
semantic1
semantic0.9432
semantic0.9908
semantic1
semantic1
semantic1
semantic1
semantic0.9889
semantic0.9692
semantic0.8152
semantic0.9328
semantic0.9832
semantic1
semantic0.9927
semantic0.9675

Assumptions

  • Judgments cover the ranked items — Rows without a relevance judgment are dropped, not treated as non-relevant; recall and nDCG use the judged items of each query.
  • Enough queries — 30 queries.

Ranking quality (95% intervals from resampling queries)

systemQueriesnDCG@10nDCG@10 95% CIMAPMAP 95% CIMRR@10MRR@10 95% CIPrecision@10Precision@10 95% CIRecall@10Recall@10 95% CIHit rate@10Hit rate@10 95% CI
keyword300.87310.827 to 0.9160.87100.816 to 0.9210.94830.883 to 1.0000.49000.410 to 0.5730.97650.955 to 0.9940.96670.900 to 1.000
semantic300.95100.922 to 0.9760.94160.908 to 0.96911.000 to 1.0000.50000.417 to 0.5870.98990.975 to 1.0000.96670.900 to 1.000

nDCG@10 against keyword (paired by query)

systemQueries in bothMean difference95% CI low95% CI highp (sign flip)Null
semantic290.07780.02490.1313.0082000 random sign patterns

Per query (keyword)

queryJudged itemsRelevantnDCG@10APRR@10Recall@10
q01990.9794111
q02620.63990.50000.50001
q031160.95250.850210.8333
q04950.97630.885011
q05940.97810.816711
q061190.77750.967510.8889
q07110————
q081290.97660.901710.8889
q091140.99240.916711
q101360.90500.675910.8333
q11730.8428111
q12630.95150.805611
q131360.99660.944411
q141280.71710.958310.8750
q151060.61930.881911
q16830.83080.866711
q1713100.9562111
q181291111
q19740.95390.792911
q201050.9383111
q21730.8428111
q22950.85050.942911
q231250.96050.942911
q241460.99000.897211
q25740.74200.887511
q26720.65900.58330.50001
q27630.78650.833311
q28640.8592111
q291160.99110.933311
q301030.65460.47620.50001
  • 1 of 30 queries have no relevant judged item; they count in precision@10 and hit rate but not in recall, MRR, MAP or nDCG.
  • Ranked by score (highest first); ties broken by doc. Relevant = relevance ≥ 1; gain 2^rel − 1; precision@10 divides by 10. Intervals: 2000 query resamples on the shared seeded stream (seed 42).
The exact R script · R R version 4.5.1 (2025-06-13)
# Ranking and retrieval quality
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.ranking 1.0.0 · spec ca58f2e600e626cb
# Dataset: evt_ranking (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/evt_ranking.parquet", col_select = c("query", "relevance", "score", "doc", "system")))
n_input <- nrow(df)
df[["query"]] <- factor(df[["query"]], levels = sort(unique(df[["query"]]), method = "radix"))
df[["doc"]] <- factor(df[["doc"]], levels = sort(unique(df[["doc"]]), method = "radix"))
df[["system"]] <- factor(df[["system"]], levels = c("keyword", "semantic"))  # stored level order
df <- df[stats::complete.cases(df[c("query", "relevance", "score", "doc", "system")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("query", "relevance", "score", "doc", "system"))  # infinite values stop the run (registry/errors.yaml)

# %% Rankings
# Each query's items ranked by score (highest first); ties by the item id, else by row order.
qc <- "query"
rc <- "relevance"
sc <- "score"
ic <- "doc"
yc <- "system"
k <- as.integer(10)
gain_kind <- "exponential"  # exponential | linear
threshold <- 1
reps <- as.integer(2000)
conf <- 0.95
seed <- 42  # portable Wichmann-Hill stream: Python resamples the same queries
cs_check_rows(nrow(df), 2, "A ranking evaluation")
rel_all <- as.numeric(df[[rc]])
if (any(rel_all < 0)) cs_error("CS_E_INVALID_VALUES", column = rc, requirement = "a relevance of 0 or more", count = sum(rel_all < 0))
score_all <- as.numeric(df[[sc]])
queries <- levels(df[[qc]])
cs_check_groups(df[[qc]], qc, minimum = 2)
systems <- if (!is.null(yc)) levels(df[[yc]]) else "(all rows)"
qcol <- as.character(df[[qc]])
ycol <- if (!is.null(yc)) as.character(df[[yc]]) else rep("(all rows)", nrow(df))
icol <- if (!is.null(ic)) as.character(df[[ic]]) else NULL
k_max <- max(k, 10L)
metric_keys <- c("ndcg", "map", "mrr", "precision_k", "recall_k", "hit_rate")
mean_def <- function(x) { x <- unlist(Filter(Negate(is.null), x)); x <- x[!is.na(x)]; if (length(x)) mean(x) else NULL }

per <- list()
curves <- list()
for (s in systems) {
  rows_s <- vector("list", length(queries))
  nd_c <- list()
  rc_c <- list()
  for (qi in seq_along(queries)) {
    m_idx <- which(qcol == queries[qi] & ycol == s)
    if (length(m_idx) == 0) next
    tb <- if (!is.null(icol)) icol[m_idx] else seq_along(m_idx)
    o <- cs_rank_order(score_all[m_idx], tb)
    ranked <- rel_all[m_idx][o]
    rows_s[[qi]] <- cs_rank_query_metrics(ranked, k, threshold, gain_kind)
    cv <- cs_rank_curve(ranked, k_max, threshold, gain_kind)
    nd_c[[length(nd_c) + 1L]] <- cv$ndcg
    rc_c[[length(rc_c) + 1L]] <- cv$recall
  }
  per[[s]] <- rows_s
  nd_m <- vapply(seq_len(k_max), function(j) { v <- vapply(nd_c, function(c) c[j], numeric(1)); v <- v[!is.na(v)]; if (length(v)) mean(v) else NA_real_ }, numeric(1))
  rc_m <- vapply(seq_len(k_max), function(j) { v <- vapply(rc_c, function(c) c[j], numeric(1)); v <- v[!is.na(v)]; if (length(v)) mean(v) else NA_real_ }, numeric(1))
  curves[[s]] <- list(ndcg = nd_m, recall = rc_m)
}

# %% Summaries per system
summ <- list()
for (s in systems) {
  present <- Filter(Negate(is.null), per[[s]])
  if (length(present) == 0) cs_error("CS_E_TOO_FEW_ROWS", what = sprintf("System %s", s), min = 1, n = 0)
  ci <- cs_rank_bootstrap_means(present, metric_keys, reps, seed, conf)
  sm <- list(n_queries = length(present), n_no_relevant = sum(vapply(present, function(q) q$n_relevant == 0, logical(1))))
  for (m in metric_keys) sm[[m]] <- mean_def(lapply(present, function(q) q[[m]]))
  for (m in metric_keys) sm[[paste0(m, "_low")]] <- if (is.na(ci[[m]][1])) NULL else ci[[m]][1]
  for (m in metric_keys) sm[[paste0(m, "_high")]] <- if (is.na(ci[[m]][2])) NULL else ci[[m]][2]
  summ[[s]] <- sm
}
ref <- systems[1]
head_s <- summ[[ref]]
if (head_s$n_queries < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = qc, min = 2, k = head_s$n_queries)

# %% Systems against the first (paired by query, nDCG@k)
nd_of <- function(s) lapply(per[[s]], function(q) if (is.null(q)) NULL else q$ndcg)
comparisons <- list()
for (s in systems[-1]) {
  a <- nd_of(ref)
  b <- nd_of(s)
  keep <- vapply(seq_along(a), function(i) !is.null(a[[i]]) && !is.null(b[[i]]), logical(1))
  d <- vapply(which(keep), function(i) b[[i]] - a[[i]], numeric(1))
  ci <- cs_rank_bootstrap_mean_ci(d, reps, seed, conf)
  sf <- if (length(d) >= 2) cs_signflip_test(d, 0, "two-sided", reps, seed + 1) else NULL
  comparisons[[length(comparisons) + 1L]] <- list(system = s, n = length(d), diff = if (length(d)) mean(d) else NULL,
    low = if (is.na(ci[1])) NULL else ci[1], high = if (is.na(ci[2])) NULL else ci[2], p = if (is.null(sf)) NULL else sf$p,
    how = if (is.null(sf)) NULL else if (sf$kind == "exact") "exact" else sprintf("%d random sign patterns", sf$b))
}

# %% Assumptions
n_q <- head_s$n_queries
assumptions <- list(
  list(key = "judged", label = "Judgments cover the ranked items", status = "info",
       detail = "Rows without a relevance judgment are dropped, not treated as non-relevant; recall and nDCG use the judged items of each query."),
  list(key = "queries", label = "Enough queries", status = if (n_q < 25) "warn" else "pass",
       detail = paste0(n_q, " queries", if (n_q < 25) "; intervals are rough with fewer than 25." else "."))
)
if (head_s$n_no_relevant > 0) warnings <- c(warnings, sprintf("%d of %d queries have no relevant judged item; they count in precision@%d and hit rate but not in recall, MRR, MAP or nDCG.", head_s$n_no_relevant, n_q, k))

# %% Result
pct <- sprintf("%.0f%%", conf * 100)
f3 <- function(v) if (is.null(v) || is.na(v)) "—" else sprintf("%.3f", v)
values <- list(n_queries = n_q, n_rows = nrow(df), k = k, gain = gain_kind, rel_threshold = threshold,
               n_systems = length(systems), reference_system = if (!is.null(yc)) ref else NULL, n_no_relevant = head_s$n_no_relevant)
for (m in metric_keys) values[[m]] <- head_s[[m]]
for (m in metric_keys) values[[paste0(m, "_low")]] <- head_s[[paste0(m, "_low")]]
for (m in metric_keys) values[[paste0(m, "_high")]] <- head_s[[paste0(m, "_high")]]
labels <- c(ndcg = sprintf("nDCG@%d", k), map = "MAP", mrr = sprintf("MRR@%d", k), precision_k = sprintf("Precision@%d", k),
            recall_k = sprintf("Recall@%d", k), hit_rate = sprintf("Hit rate@%d", k))
sys_cols <- list(list(key = "system", label = if (!is.null(yc)) yc else "System", type = "string"), list(key = "n_queries", label = "Queries", type = "integer"))
for (m in metric_keys) sys_cols <- c(sys_cols, list(list(key = m, label = labels[[m]], type = "number"), list(key = paste0(m, "_ci"), label = paste(labels[[m]], pct, "CI"), type = "string")))
sys_rows <- lapply(systems, function(s) {
  r <- list(system = s, n_queries = summ[[s]]$n_queries)
  for (m in metric_keys) r[[m]] <- summ[[s]][[m]]
  for (m in metric_keys) r[[paste0(m, "_ci")]] <- sprintf("%s to %s", f3(summ[[s]][[paste0(m, "_low")]]), f3(summ[[s]][[paste0(m, "_high")]]))
  r
})
tables <- list(list(key = "systems", title = sprintf("Ranking quality (%s intervals from resampling queries)", pct), columns = sys_cols, rows = sys_rows))
if (length(comparisons)) {
  tables[[length(tables) + 1L]] <- list(key = "comparisons", title = sprintf("nDCG@%d against %s (paired by query)", k, ref),
    columns = list(list(key = "system", label = yc, type = "string"), list(key = "n", label = "Queries in both", type = "integer"),
                   list(key = "diff", label = "Mean difference", type = "number"), list(key = "low", label = paste(pct, "CI low"), type = "number"),
                   list(key = "high", label = paste(pct, "CI high"), type = "number"), list(key = "p", label = "p (sign flip)", type = "pvalue"),
                   list(key = "how", label = "Null", type = "string")),
    rows = comparisons)
}
q_rows <- list()
for (qi in seq_along(queries)) {
  m <- per[[ref]][[qi]]
  if (!is.null(m) && length(q_rows) < 500) q_rows[[length(q_rows) + 1L]] <- list(query = queries[qi], items = m$n_items, relevant = m$n_relevant,
    ndcg = m$ndcg, ap = m$map, rr = m$mrr, recall = m$recall_k)
}
tables[[length(tables) + 1L]] <- list(key = "queries", title = if (!is.null(yc)) sprintf("Per query (%s)", ref) else "Per query",
  columns = list(list(key = "query", label = qc, type = "string"), list(key = "items", label = "Judged items", type = "integer"),
                 list(key = "relevant", label = "Relevant", type = "integer"), list(key = "ndcg", label = sprintf("nDCG@%d", k), type = "number"),
                 list(key = "ap", label = "AP", type = "number"), list(key = "rr", label = sprintf("RR@%d", k), type = "number"),
                 list(key = "recall", label = sprintf("Recall@%d", k), type = "number")),
  rows = q_rows, note = if (n_q > 500) "First 500 queries." else NULL)
cutoffs <- seq_len(k_max)
charts <- list(cs_chart("at-k", "metric-at-k", "nDCG and recall at each cutoff", list(
  k = cs_col("Cutoff k", rep(c(cutoffs, cutoffs), length(systems)), "numeric"),
  value = cs_col("Mean over queries", unlist(lapply(systems, function(s) c(curves[[s]]$ndcg, curves[[s]]$recall)))),
  metric = cs_col("Metric", rep(rep(c("nDCG", "Recall"), each = k_max), length(systems)), "categorical", levels = c("nDCG", "Recall")),
  system = cs_col(if (!is.null(yc)) yc else "System", rep(systems, each = 2 * k_max), "categorical", levels = systems)),
  controls = list(k = k)))
nd_s <- character(0)
nd_v <- numeric(0)
for (s in systems) for (q in per[[s]]) if (!is.null(q) && !is.null(q$ndcg)) { nd_s <- c(nd_s, s); nd_v <- c(nd_v, q$ndcg) }
if (length(nd_v)) {
  roles <- list(y = cs_col(sprintf("nDCG@%d", k), nd_v))
  if (!is.null(yc)) roles$group <- cs_col(yc, nd_s, "categorical", levels = systems)
  charts[[length(charts) + 1L]] <- cs_chart("per-query", "box-violin", sprintf("nDCG@%d per query", k), roles)
}
lead <- if (!is.null(yc)) sprintf(" for %s", ref) else ""
summary <- sprintf("Across %d queries%s, nDCG@%d = %s (%s CI %s to %s), MAP = %s, MRR@%d = %s and recall@%d = %s.",
                   n_q, lead, k, f3(head_s$ndcg), pct, f3(head_s$ndcg_low), f3(head_s$ndcg_high), f3(head_s$map), k, f3(head_s$mrr), k, f3(head_s$recall_k))
for (cmp in comparisons) if (!is.null(cmp$diff)) summary <- paste(summary, sprintf("%s − %s: nDCG@%d %+.3f (%s CI %s to %s, %s).", cmp$system, ref, k, cmp$diff, pct,
  f3(cmp$low), f3(cmp$high), if (is.null(cmp$p)) "no test" else cs_fmt_p(cmp$p)))
cs_publish(list(
  method = "evaluate.ranking",
  methodVersion = "1.0.0",
  title = "Ranking quality",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = nrow(df),
  summary = summary,
  statistics = lapply(c("ndcg", "map", "mrr", "recall_k"), function(m) list(key = m, label = labels[[m]], value = head_s[[m]])),
  tables = tables,
  assumptions = assumptions,
  warnings = warnings,
  notes = list(paste0(sprintf("Ranked by %s (highest first); ties broken by ", sc), if (!is.null(ic)) paste0(ic, ".") else "row order.",
                      sprintf(" Relevant = %s ≥ %s; gain %s; precision@%d divides by %d. Intervals: %d query resamples on the shared seeded stream (seed %d).",
                              rc, format(threshold), if (gain_kind == "exponential") "2^rel − 1" else "rel", k, k, reps, as.integer(seed)))),
  charts = charts,
  values = values
))
Python

Across 30 queries for keyword, nDCG@10 = 0.873 (95% CI 0.827 to 0.916), MAP = 0.871, MRR@10 = 0.948 and recall@10 = 0.977. semantic − keyword: nDCG@10 +0.078 (95% CI 0.025 to 0.131, p = .008).

nDCG@10
0.8731
MAP
0.8710
MRR@10
0.9483
Recall@10
0.9765

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Judgments cover the ranked items — Rows without a relevance judgment are dropped, not treated as non-relevant; recall and nDCG use the judged items of each query.
  • Enough queries — 30 queries.

Ranking quality (95% intervals from resampling queries)

systemQueriesnDCG@10nDCG@10 95% CIMAPMAP 95% CIMRR@10MRR@10 95% CIPrecision@10Precision@10 95% CIRecall@10Recall@10 95% CIHit rate@10Hit rate@10 95% CI
keyword300.87310.827 to 0.9160.87100.816 to 0.9210.94830.883 to 1.0000.49000.410 to 0.5730.97650.955 to 0.9940.96670.900 to 1.000
semantic300.95100.922 to 0.9760.94160.908 to 0.96911.000 to 1.0000.50000.417 to 0.5870.98990.975 to 1.0000.96670.900 to 1.000

nDCG@10 against keyword (paired by query)

systemQueries in bothMean difference95% CI low95% CI highp (sign flip)Null
semantic290.07780.02490.1313.0082000 random sign patterns

Per query (keyword)

queryJudged itemsRelevantnDCG@10APRR@10Recall@10
q01990.9794111
q02620.63990.50000.50001
q031160.95250.850210.8333
q04950.97630.885011
q05940.97810.816711
q061190.77750.967510.8889
q07110————
q081290.97660.901710.8889
q091140.99240.916711
q101360.90500.675910.8333
q11730.8428111
q12630.95150.805611
q131360.99660.944411
q141280.71710.958310.8750
q151060.61930.881911
q16830.83080.866711
q1713100.9562111
q181291111
q19740.95390.792911
q201050.9383111
q21730.8428111
q22950.85050.942911
q231250.96050.942911
q241460.99000.897211
q25740.74200.887511
q26720.65900.58330.50001
q27630.78650.833311
q28640.8592111
q291160.99110.933311
q301030.65460.47620.50001
  • 1 of 30 queries have no relevant judged item; they count in precision@10 and hit rate but not in recall, MRR, MAP or nDCG.
  • Ranked by score (highest first); ties broken by doc. Relevant = relevance ≥ 1; gain 2^rel − 1; precision@10 divides by 10. Intervals: 2000 query resamples on the shared seeded stream (seed 42).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Ranking and retrieval quality
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.ranking 1.0.0 · spec ca58f2e600e626cb
# Dataset: evt_ranking (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.errors import check_groups, check_rows
from codesplash.evaluate import ranking as rk  # twin: codesplashr cs_rank_*
from codesplash.stats import signflip

# %% Data
df = pd.read_parquet("tests/parity/fixtures/evt_ranking.parquet", columns=["query", "relevance", "score", "doc", "system"])
n_input = len(df)
df["query"] = pd.Categorical(df["query"], categories=sorted(df["query"].dropna().unique()))
df["doc"] = pd.Categorical(df["doc"], categories=sorted(df["doc"].dropna().unique()))
df["system"] = pd.Categorical(df["system"], categories=["keyword", "semantic"])  # stored level order
df = df.dropna(subset=["query", "relevance", "score", "doc", "system"])  # listwise deletion over the analysis columns
df["query"] = df["query"].cat.remove_unused_categories()
df["doc"] = df["doc"].cat.remove_unused_categories()
df["system"] = df["system"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["query", "relevance", "score", "doc", "system"])  # infinite values stop the run (registry/errors.yaml)

# %% Rankings
# Each query's items ranked by score (highest first); ties by the item id, else by row order.
qc, rc, sc = "query", "relevance", "score"
ic = "doc"
yc = "system"
k = int(10)
gain_kind = "exponential"  # exponential | linear
threshold = 1
reps = int(2000)
conf = 0.95
seed = 42  # portable Wichmann–Hill stream: R resamples the same queries
check_rows(len(df), 2, "A ranking evaluation")
rel_all = df[rc].to_numpy(dtype=float)
if np.any(rel_all < 0):
    cs.cs_error("CS_E_INVALID_VALUES", column=rc, requirement="a relevance of 0 or more", count=int(np.sum(rel_all < 0)))
score_all = df[sc].to_numpy(dtype=float)
queries = [str(v) for v in df[qc].cat.categories]
check_groups(df[qc], qc, minimum=2)
systems = [str(v) for v in df[yc].cat.categories] if yc else ["(all rows)"]
qcol = df[qc].astype(str).to_numpy()
ycol = df[yc].astype(str).to_numpy() if yc else np.array(["(all rows)"] * len(df))
icol = df[ic].astype(str).to_numpy() if ic else None
k_max = max(k, 10)

per = {}     # system → list of per-query metric dicts (queries in level order; None when absent)
curves = {}  # system → (nDCG@j, recall@j) means over queries, j = 1..k_max
for s in systems:
    rows_s = []
    nd_c, rc_c = [], []
    for q in queries:
        m_idx = np.flatnonzero((qcol == q) & (ycol == s))
        if m_idx.size == 0:
            rows_s.append(None)
            continue
        tb = list(icol[m_idx]) if icol is not None else list(range(m_idx.size))
        o = rk.order_within(score_all[m_idx], tb)
        ranked = rel_all[m_idx][o]
        rows_s.append(rk.query_metrics(ranked, k, threshold, gain_kind))
        nd, rcv = rk.curve(ranked, k_max, threshold, gain_kind)
        nd_c.append(nd)
        rc_c.append(rcv)
    per[s] = rows_s
    curves[s] = ([rk._mean([c[j] for c in nd_c]) for j in range(k_max)], [rk._mean([c[j] for c in rc_c]) for j in range(k_max)])

# %% Summaries per system
summ = {}
for i, s in enumerate(systems):
    present = [q for q in per[s] if q is not None]
    if not present:
        cs.cs_error("CS_E_TOO_FEW_ROWS", what=f"System {s}", min=1, n=0)
    ci = rk.bootstrap_means(present, rk.METRICS, reps, seed, conf)
    summ[s] = {"n_queries": len(present), "n_no_relevant": sum(1 for q in present if q["n_relevant"] == 0),
               **{m: rk._mean([q[m] for q in present]) for m in rk.METRICS},
               **{f"{m}_low": ci[m][0] for m in rk.METRICS}, **{f"{m}_high": ci[m][1] for m in rk.METRICS}}
ref = systems[0]
head = summ[ref]
if head["n_queries"] < 2:
    cs.cs_error("CS_E_TOO_FEW_GROUPS", column=qc, min=2, k=head["n_queries"])

# %% Systems against the first (paired by query, nDCG@k)
comparisons = []
for s in systems[1:]:
    d = rk.paired_differences([q["ndcg"] if q else None for q in per[ref]], [q["ndcg"] if q else None for q in per[s]])
    lo, hi = rk.bootstrap_mean_ci(d, reps, seed, conf)
    sf = signflip.signflip_test(d, 0.0, "two-sided", reps, seed + 1) if len(d) >= 2 else None
    comparisons.append({"system": s, "n": len(d), "diff": float(np.mean(d)) if d else None, "low": lo, "high": hi,
                        "p": sf["p"] if sf else None, "how": (("exact" if sf["kind"] == "exact" else f"{sf['b']} random sign patterns") if sf else None)})

# %% Assumptions
n_q = head["n_queries"]
assumptions = [
    {"key": "judged", "label": "Judgments cover the ranked items", "status": "info",
     "detail": "Rows without a relevance judgment are dropped, not treated as non-relevant; recall and nDCG use the judged items of each query."},
    {"key": "queries", "label": "Enough queries", "status": "warn" if n_q < 25 else "pass",
     "detail": f"{n_q} queries" + ("; intervals are rough with fewer than 25." if n_q < 25 else ".")},
]
if head["n_no_relevant"]:
    warnings.append(f"{head['n_no_relevant']} of {n_q} queries have no relevant judged item; they count in precision@{k} and hit rate but not in recall, MRR, MAP or nDCG.")

# %% Result
pct = f"{conf:.0%}"
f3 = lambda v: "—" if v is None else f"{v:.3f}"
values = {"n_queries": n_q, "n_rows": int(len(df)), "k": k, "gain": gain_kind, "rel_threshold": threshold,
          "n_systems": len(systems), "reference_system": ref if yc else None, "n_no_relevant": head["n_no_relevant"],
          **{m: head[m] for m in rk.METRICS}, **{f"{m}_low": head[f"{m}_low"] for m in rk.METRICS},
          **{f"{m}_high": head[f"{m}_high"] for m in rk.METRICS}}
labels = {"ndcg": f"nDCG@{k}", "map": "MAP", "mrr": f"MRR@{k}", "precision_k": f"Precision@{k}", "recall_k": f"Recall@{k}", "hit_rate": f"Hit rate@{k}"}
tables = [{"key": "systems", "title": f"Ranking quality ({pct} intervals from resampling queries)",
           "columns": [{"key": "system", "label": yc or "System", "type": "string"}, {"key": "n_queries", "label": "Queries", "type": "integer"}]
                      + [c for m in rk.METRICS for c in ({"key": m, "label": labels[m], "type": "number"},
                                                          {"key": f"{m}_ci", "label": f"{labels[m]} {pct} CI", "type": "string"})],
           "rows": [{"system": s, "n_queries": summ[s]["n_queries"],
                     **{m: summ[s][m] for m in rk.METRICS},
                     **{f"{m}_ci": (f"{f3(summ[s][f'{m}_low'])} to {f3(summ[s][f'{m}_high'])}") for m in rk.METRICS}} for s in systems]}]
if comparisons:
    tables.append({"key": "comparisons", "title": f"nDCG@{k} against {ref} (paired by query)",
                   "columns": [{"key": "system", "label": yc, "type": "string"}, {"key": "n", "label": "Queries in both", "type": "integer"},
                               {"key": "diff", "label": "Mean difference", "type": "number"}, {"key": "low", "label": f"{pct} CI low", "type": "number"},
                               {"key": "high", "label": f"{pct} CI high", "type": "number"}, {"key": "p", "label": "p (sign flip)", "type": "pvalue"},
                               {"key": "how", "label": "Null", "type": "string"}],
                   "rows": comparisons})
q_rows = []
for q, m in zip(queries, per[ref]):
    if m is not None and len(q_rows) < 500:
        q_rows.append({"query": q, "items": m["n_items"], "relevant": m["n_relevant"], "ndcg": m["ndcg"], "ap": m["map"], "rr": m["mrr"], "recall": m["recall_k"]})
tables.append({"key": "queries", "title": f"Per query ({ref})" if yc else "Per query",
               "columns": [{"key": "query", "label": qc, "type": "string"}, {"key": "items", "label": "Judged items", "type": "integer"},
                           {"key": "relevant", "label": "Relevant", "type": "integer"}, {"key": "ndcg", "label": f"nDCG@{k}", "type": "number"},
                           {"key": "ap", "label": "AP", "type": "number"}, {"key": "rr", "label": f"RR@{k}", "type": "number"},
                           {"key": "recall", "label": f"Recall@{k}", "type": "number"}],
               "rows": q_rows, "note": "First 500 queries." if n_q > 500 else None})
cutoffs = list(range(1, k_max + 1))
charts = [cs.chart("at-k", "metric-at-k", "nDCG and recall at each cutoff", {
    "k": cs.col("Cutoff k", [j for s in systems for _ in (0, 1) for j in cutoffs], "numeric"),
    "value": cs.col("Mean over queries", [v for s in systems for v in curves[s][0] + curves[s][1]]),
    "metric": cs.col("Metric", [lab for s in systems for lab in ("nDCG",) * k_max + ("Recall",) * k_max], "categorical", levels=["nDCG", "Recall"]),
    "system": cs.col(yc or "System", [s for s in systems for _ in range(2 * k_max)], "categorical", levels=systems)},
    controls={"k": k})]
nd_vals = [(s, q["ndcg"]) for s in systems for q in per[s] if q is not None and q["ndcg"] is not None]
if nd_vals:
    charts.append(cs.chart("per-query", "box-violin", f"nDCG@{k} per query", {
        "y": cs.col(f"nDCG@{k}", [v for _, v in nd_vals]),
        **({"group": cs.col(yc, [s for s, _ in nd_vals], "categorical", levels=systems)} if yc else {})}))
lead = f" for {ref}" if yc else ""
summary = (f"Across {n_q} queries{lead}, nDCG@{k} = {f3(head['ndcg'])} ({pct} CI {f3(head['ndcg_low'])} to {f3(head['ndcg_high'])}), "
           f"MAP = {f3(head['map'])}, MRR@{k} = {f3(head['mrr'])} and recall@{k} = {f3(head['recall_k'])}.")
for c in comparisons:
    summary += f" {c['system']} − {ref}: nDCG@{k} {c['diff']:+.3f} ({pct} CI {f3(c['low'])} to {f3(c['high'])}, {cs.fmt_p(c['p']) if c['p'] is not None else 'no test'})." if c["diff"] is not None else ""
cs.publish({
    "method": "evaluate.ranking",
    "methodVersion": "1.0.0",
    "title": "Ranking quality",
    "engine": cs.engine_info("pandas", "numpy"),
    "n": int(len(df)),
    "summary": summary,
    "statistics": [{"key": m, "label": labels[m], "value": head[m]} for m in ("ndcg", "map", "mrr", "recall_k")],
    "tables": tables,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Ranked by {sc} (highest first); ties broken by " + (f"{ic}." if ic else "row order.")
              + f" Relevant = {rc} ≥ {threshold:g}; gain " + ("2^rel − 1" if gain_kind == "exponential" else "rel")
              + f"; precision@{k} divides by {k}. Intervals: {reps} query resamples on the shared seeded stream (seed {seed})."],
    "charts": charts,
    "values": values,
})

The keyword system reaches nDCG@10 = 0.873 (interval 0.827 to 0.916) over 30 queries. The comparison table pairs the systems by query: each query is scored by both, so their difference is measured on the same questions, and the interval resamples whole queries.

Predict first

When the intervals resample, what is drawn with replacement?

RowsQueriesItems
Reveal

Queries. Items within a query aren't independent: one hard query drags all of its items down together.

04

Pin the conventions before you compare

Read

Ranking numbers move with small choices, so the method states each one:

  • Ties in the score are broken by the item id (or row order), never at random.
  • Gain: exponential 2rel−12^{rel} - 1 makes a grade-3 item worth seven grade-1 items; linear makes it worth three.
  • Cutoff k: choose it before comparing systems.
Ranking qualityRecorded · Python and R agreeRecorded 2026-11-21 · 26 values compared
R

Across 30 queries, nDCG@5 = 0.945 (95% CI 0.918 to 0.966), MAP = 0.942, MRR@5 = 1.000 and recall@5 = 0.833.

nDCG@5
0.9448
MAP
0.9416
MRR@5
1
Recall@5
0.8327

Plots

nDCG and recall at each cutoffHow does ranking quality change as more of the top results are counted?
View data
Cutoff kMetricSystemMean over queries
1nDCG(all rows)0.9368
2nDCG(all rows)0.9323
3nDCG(all rows)0.9071
4nDCG(all rows)0.9338
5nDCG(all rows)0.9448
6nDCG(all rows)0.9439
7nDCG(all rows)0.9539
8nDCG(all rows)0.9530
9nDCG(all rows)0.9566
10nDCG(all rows)0.9602
1Recall(all rows)0.2317
2Recall(all rows)0.4375
3Recall(all rows)0.5802
4Recall(all rows)0.7274
5Recall(all rows)0.8327
6Recall(all rows)0.8784
7Recall(all rows)0.9274
8Recall(all rows)0.9462
9Recall(all rows)0.9726
10Recall(all rows)0.9899
nDCG@5 per queryHow does a numeric variable differ across groups?
View data
nDCG@5
1
1
1
0.9561
0.7438
0.8158
0.9808
0.8181
0.9671
0.9854
0.7960
0.9403
0.9943
0.9218
1
0.9214
0.9486
1
1
1
1
0.9336
0.9105
0.9122
0.9072
0.9779
1
1
0.9675

Assumptions

  • Judgments cover the ranked items — Rows without a relevance judgment are dropped, not treated as non-relevant; recall and nDCG use the judged items of each query.
  • Enough queries — 30 queries.

Ranking quality (95% intervals from resampling queries)

SystemQueriesnDCG@5nDCG@5 95% CIMAPMAP 95% CIMRR@5MRR@5 95% CIPrecision@5Precision@5 95% CIRecall@5Recall@5 95% CIHit rate@5Hit rate@5 95% CI
(all rows)300.94480.918 to 0.9660.94160.907 to 0.96811.000 to 1.0000.77330.700 to 0.8530.83270.762 to 0.8900.96670.900 to 1.000

Per query

queryJudged itemsRelevantnDCG@5APRR@5Recall@5
q01991110.5556
q02621111
q0311610.976210.8333
q04950.9561111
q05940.74380.916710.7500
q061190.81580.988910.5556
q07110————
q081290.9808110.5556
q091140.81810.667910.7500
q101360.96710.976210.8333
q11730.98540.916711
q12630.79600.916711
q131360.94030.800010.6667
q141280.99430.910610.6250
q151060.92180.948410.6667
q16831111
q1713100.9214110.5000
q181290.9486110.5556
q19741111
q201051111
q21731111
q22951111
q231250.93360.926710.8000
q241460.91050.883310.6667
q25740.9122111
q26720.90720.700011
q27630.97790.916711
q28641111
q2911610.944410.8333
q301030.96750.916711
  • 1 of 30 queries have no relevant judged item; they count in precision@5 and hit rate but not in recall, MRR, MAP or nDCG.
  • Ranked by score (highest first); ties broken by doc. Relevant = relevance ≥ 1; gain rel; precision@5 divides by 5. Intervals: 500 query resamples on the shared seeded stream (seed 42).
The exact R script · R R version 4.5.1 (2025-06-13)
# Ranking and retrieval quality
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.ranking 1.0.0 · spec 02b78a6618e22614
# Dataset: evt_ranking_one (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/evt_ranking_one.parquet", col_select = c("query", "relevance", "score", "doc")))
n_input <- nrow(df)
df[["query"]] <- factor(df[["query"]], levels = sort(unique(df[["query"]]), method = "radix"))
df[["doc"]] <- factor(df[["doc"]], levels = sort(unique(df[["doc"]]), method = "radix"))
df <- df[stats::complete.cases(df[c("query", "relevance", "score", "doc")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("query", "relevance", "score", "doc"))  # infinite values stop the run (registry/errors.yaml)

# %% Rankings
# Each query's items ranked by score (highest first); ties by the item id, else by row order.
qc <- "query"
rc <- "relevance"
sc <- "score"
ic <- "doc"
yc <- NULL
k <- as.integer(5)
gain_kind <- "linear"  # exponential | linear
threshold <- 1
reps <- as.integer(500)
conf <- 0.95
seed <- 42  # portable Wichmann-Hill stream: Python resamples the same queries
cs_check_rows(nrow(df), 2, "A ranking evaluation")
rel_all <- as.numeric(df[[rc]])
if (any(rel_all < 0)) cs_error("CS_E_INVALID_VALUES", column = rc, requirement = "a relevance of 0 or more", count = sum(rel_all < 0))
score_all <- as.numeric(df[[sc]])
queries <- levels(df[[qc]])
cs_check_groups(df[[qc]], qc, minimum = 2)
systems <- if (!is.null(yc)) levels(df[[yc]]) else "(all rows)"
qcol <- as.character(df[[qc]])
ycol <- if (!is.null(yc)) as.character(df[[yc]]) else rep("(all rows)", nrow(df))
icol <- if (!is.null(ic)) as.character(df[[ic]]) else NULL
k_max <- max(k, 10L)
metric_keys <- c("ndcg", "map", "mrr", "precision_k", "recall_k", "hit_rate")
mean_def <- function(x) { x <- unlist(Filter(Negate(is.null), x)); x <- x[!is.na(x)]; if (length(x)) mean(x) else NULL }

per <- list()
curves <- list()
for (s in systems) {
  rows_s <- vector("list", length(queries))
  nd_c <- list()
  rc_c <- list()
  for (qi in seq_along(queries)) {
    m_idx <- which(qcol == queries[qi] & ycol == s)
    if (length(m_idx) == 0) next
    tb <- if (!is.null(icol)) icol[m_idx] else seq_along(m_idx)
    o <- cs_rank_order(score_all[m_idx], tb)
    ranked <- rel_all[m_idx][o]
    rows_s[[qi]] <- cs_rank_query_metrics(ranked, k, threshold, gain_kind)
    cv <- cs_rank_curve(ranked, k_max, threshold, gain_kind)
    nd_c[[length(nd_c) + 1L]] <- cv$ndcg
    rc_c[[length(rc_c) + 1L]] <- cv$recall
  }
  per[[s]] <- rows_s
  nd_m <- vapply(seq_len(k_max), function(j) { v <- vapply(nd_c, function(c) c[j], numeric(1)); v <- v[!is.na(v)]; if (length(v)) mean(v) else NA_real_ }, numeric(1))
  rc_m <- vapply(seq_len(k_max), function(j) { v <- vapply(rc_c, function(c) c[j], numeric(1)); v <- v[!is.na(v)]; if (length(v)) mean(v) else NA_real_ }, numeric(1))
  curves[[s]] <- list(ndcg = nd_m, recall = rc_m)
}

# %% Summaries per system
summ <- list()
for (s in systems) {
  present <- Filter(Negate(is.null), per[[s]])
  if (length(present) == 0) cs_error("CS_E_TOO_FEW_ROWS", what = sprintf("System %s", s), min = 1, n = 0)
  ci <- cs_rank_bootstrap_means(present, metric_keys, reps, seed, conf)
  sm <- list(n_queries = length(present), n_no_relevant = sum(vapply(present, function(q) q$n_relevant == 0, logical(1))))
  for (m in metric_keys) sm[[m]] <- mean_def(lapply(present, function(q) q[[m]]))
  for (m in metric_keys) sm[[paste0(m, "_low")]] <- if (is.na(ci[[m]][1])) NULL else ci[[m]][1]
  for (m in metric_keys) sm[[paste0(m, "_high")]] <- if (is.na(ci[[m]][2])) NULL else ci[[m]][2]
  summ[[s]] <- sm
}
ref <- systems[1]
head_s <- summ[[ref]]
if (head_s$n_queries < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = qc, min = 2, k = head_s$n_queries)

# %% Systems against the first (paired by query, nDCG@k)
nd_of <- function(s) lapply(per[[s]], function(q) if (is.null(q)) NULL else q$ndcg)
comparisons <- list()
for (s in systems[-1]) {
  a <- nd_of(ref)
  b <- nd_of(s)
  keep <- vapply(seq_along(a), function(i) !is.null(a[[i]]) && !is.null(b[[i]]), logical(1))
  d <- vapply(which(keep), function(i) b[[i]] - a[[i]], numeric(1))
  ci <- cs_rank_bootstrap_mean_ci(d, reps, seed, conf)
  sf <- if (length(d) >= 2) cs_signflip_test(d, 0, "two-sided", reps, seed + 1) else NULL
  comparisons[[length(comparisons) + 1L]] <- list(system = s, n = length(d), diff = if (length(d)) mean(d) else NULL,
    low = if (is.na(ci[1])) NULL else ci[1], high = if (is.na(ci[2])) NULL else ci[2], p = if (is.null(sf)) NULL else sf$p,
    how = if (is.null(sf)) NULL else if (sf$kind == "exact") "exact" else sprintf("%d random sign patterns", sf$b))
}

# %% Assumptions
n_q <- head_s$n_queries
assumptions <- list(
  list(key = "judged", label = "Judgments cover the ranked items", status = "info",
       detail = "Rows without a relevance judgment are dropped, not treated as non-relevant; recall and nDCG use the judged items of each query."),
  list(key = "queries", label = "Enough queries", status = if (n_q < 25) "warn" else "pass",
       detail = paste0(n_q, " queries", if (n_q < 25) "; intervals are rough with fewer than 25." else "."))
)
if (head_s$n_no_relevant > 0) warnings <- c(warnings, sprintf("%d of %d queries have no relevant judged item; they count in precision@%d and hit rate but not in recall, MRR, MAP or nDCG.", head_s$n_no_relevant, n_q, k))

# %% Result
pct <- sprintf("%.0f%%", conf * 100)
f3 <- function(v) if (is.null(v) || is.na(v)) "—" else sprintf("%.3f", v)
values <- list(n_queries = n_q, n_rows = nrow(df), k = k, gain = gain_kind, rel_threshold = threshold,
               n_systems = length(systems), reference_system = if (!is.null(yc)) ref else NULL, n_no_relevant = head_s$n_no_relevant)
for (m in metric_keys) values[[m]] <- head_s[[m]]
for (m in metric_keys) values[[paste0(m, "_low")]] <- head_s[[paste0(m, "_low")]]
for (m in metric_keys) values[[paste0(m, "_high")]] <- head_s[[paste0(m, "_high")]]
labels <- c(ndcg = sprintf("nDCG@%d", k), map = "MAP", mrr = sprintf("MRR@%d", k), precision_k = sprintf("Precision@%d", k),
            recall_k = sprintf("Recall@%d", k), hit_rate = sprintf("Hit rate@%d", k))
sys_cols <- list(list(key = "system", label = if (!is.null(yc)) yc else "System", type = "string"), list(key = "n_queries", label = "Queries", type = "integer"))
for (m in metric_keys) sys_cols <- c(sys_cols, list(list(key = m, label = labels[[m]], type = "number"), list(key = paste0(m, "_ci"), label = paste(labels[[m]], pct, "CI"), type = "string")))
sys_rows <- lapply(systems, function(s) {
  r <- list(system = s, n_queries = summ[[s]]$n_queries)
  for (m in metric_keys) r[[m]] <- summ[[s]][[m]]
  for (m in metric_keys) r[[paste0(m, "_ci")]] <- sprintf("%s to %s", f3(summ[[s]][[paste0(m, "_low")]]), f3(summ[[s]][[paste0(m, "_high")]]))
  r
})
tables <- list(list(key = "systems", title = sprintf("Ranking quality (%s intervals from resampling queries)", pct), columns = sys_cols, rows = sys_rows))
if (length(comparisons)) {
  tables[[length(tables) + 1L]] <- list(key = "comparisons", title = sprintf("nDCG@%d against %s (paired by query)", k, ref),
    columns = list(list(key = "system", label = yc, type = "string"), list(key = "n", label = "Queries in both", type = "integer"),
                   list(key = "diff", label = "Mean difference", type = "number"), list(key = "low", label = paste(pct, "CI low"), type = "number"),
                   list(key = "high", label = paste(pct, "CI high"), type = "number"), list(key = "p", label = "p (sign flip)", type = "pvalue"),
                   list(key = "how", label = "Null", type = "string")),
    rows = comparisons)
}
q_rows <- list()
for (qi in seq_along(queries)) {
  m <- per[[ref]][[qi]]
  if (!is.null(m) && length(q_rows) < 500) q_rows[[length(q_rows) + 1L]] <- list(query = queries[qi], items = m$n_items, relevant = m$n_relevant,
    ndcg = m$ndcg, ap = m$map, rr = m$mrr, recall = m$recall_k)
}
tables[[length(tables) + 1L]] <- list(key = "queries", title = if (!is.null(yc)) sprintf("Per query (%s)", ref) else "Per query",
  columns = list(list(key = "query", label = qc, type = "string"), list(key = "items", label = "Judged items", type = "integer"),
                 list(key = "relevant", label = "Relevant", type = "integer"), list(key = "ndcg", label = sprintf("nDCG@%d", k), type = "number"),
                 list(key = "ap", label = "AP", type = "number"), list(key = "rr", label = sprintf("RR@%d", k), type = "number"),
                 list(key = "recall", label = sprintf("Recall@%d", k), type = "number")),
  rows = q_rows, note = if (n_q > 500) "First 500 queries." else NULL)
cutoffs <- seq_len(k_max)
charts <- list(cs_chart("at-k", "metric-at-k", "nDCG and recall at each cutoff", list(
  k = cs_col("Cutoff k", rep(c(cutoffs, cutoffs), length(systems)), "numeric"),
  value = cs_col("Mean over queries", unlist(lapply(systems, function(s) c(curves[[s]]$ndcg, curves[[s]]$recall)))),
  metric = cs_col("Metric", rep(rep(c("nDCG", "Recall"), each = k_max), length(systems)), "categorical", levels = c("nDCG", "Recall")),
  system = cs_col(if (!is.null(yc)) yc else "System", rep(systems, each = 2 * k_max), "categorical", levels = systems)),
  controls = list(k = k)))
nd_s <- character(0)
nd_v <- numeric(0)
for (s in systems) for (q in per[[s]]) if (!is.null(q) && !is.null(q$ndcg)) { nd_s <- c(nd_s, s); nd_v <- c(nd_v, q$ndcg) }
if (length(nd_v)) {
  roles <- list(y = cs_col(sprintf("nDCG@%d", k), nd_v))
  if (!is.null(yc)) roles$group <- cs_col(yc, nd_s, "categorical", levels = systems)
  charts[[length(charts) + 1L]] <- cs_chart("per-query", "box-violin", sprintf("nDCG@%d per query", k), roles)
}
lead <- if (!is.null(yc)) sprintf(" for %s", ref) else ""
summary <- sprintf("Across %d queries%s, nDCG@%d = %s (%s CI %s to %s), MAP = %s, MRR@%d = %s and recall@%d = %s.",
                   n_q, lead, k, f3(head_s$ndcg), pct, f3(head_s$ndcg_low), f3(head_s$ndcg_high), f3(head_s$map), k, f3(head_s$mrr), k, f3(head_s$recall_k))
for (cmp in comparisons) if (!is.null(cmp$diff)) summary <- paste(summary, sprintf("%s − %s: nDCG@%d %+.3f (%s CI %s to %s, %s).", cmp$system, ref, k, cmp$diff, pct,
  f3(cmp$low), f3(cmp$high), if (is.null(cmp$p)) "no test" else cs_fmt_p(cmp$p)))
cs_publish(list(
  method = "evaluate.ranking",
  methodVersion = "1.0.0",
  title = "Ranking quality",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = nrow(df),
  summary = summary,
  statistics = lapply(c("ndcg", "map", "mrr", "recall_k"), function(m) list(key = m, label = labels[[m]], value = head_s[[m]])),
  tables = tables,
  assumptions = assumptions,
  warnings = warnings,
  notes = list(paste0(sprintf("Ranked by %s (highest first); ties broken by ", sc), if (!is.null(ic)) paste0(ic, ".") else "row order.",
                      sprintf(" Relevant = %s ≥ %s; gain %s; precision@%d divides by %d. Intervals: %d query resamples on the shared seeded stream (seed %d).",
                              rc, format(threshold), if (gain_kind == "exponential") "2^rel − 1" else "rel", k, k, reps, as.integer(seed)))),
  charts = charts,
  values = values
))
Python

Across 30 queries, nDCG@5 = 0.945 (95% CI 0.918 to 0.966), MAP = 0.942, MRR@5 = 1.000 and recall@5 = 0.833.

nDCG@5
0.9448
MAP
0.9416
MRR@5
1
Recall@5
0.8327

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Judgments cover the ranked items — Rows without a relevance judgment are dropped, not treated as non-relevant; recall and nDCG use the judged items of each query.
  • Enough queries — 30 queries.

Ranking quality (95% intervals from resampling queries)

SystemQueriesnDCG@5nDCG@5 95% CIMAPMAP 95% CIMRR@5MRR@5 95% CIPrecision@5Precision@5 95% CIRecall@5Recall@5 95% CIHit rate@5Hit rate@5 95% CI
(all rows)300.94480.918 to 0.9660.94160.907 to 0.96811.000 to 1.0000.77330.700 to 0.8530.83270.762 to 0.8900.96670.900 to 1.000

Per query

queryJudged itemsRelevantnDCG@5APRR@5Recall@5
q01991110.5556
q02621111
q0311610.976210.8333
q04950.9561111
q05940.74380.916710.7500
q061190.81580.988910.5556
q07110————
q081290.9808110.5556
q091140.81810.667910.7500
q101360.96710.976210.8333
q11730.98540.916711
q12630.79600.916711
q131360.94030.800010.6667
q141280.99430.910610.6250
q151060.92180.948410.6667
q16831111
q1713100.9214110.5000
q181290.9486110.5556
q19741111
q201051111
q21731111
q22951111
q231250.93360.926710.8000
q241460.91050.883310.6667
q25740.9122111
q26720.90720.700011
q27630.97790.916711
q28641111
q2911610.944410.8333
q301030.96750.916711
  • 1 of 30 queries have no relevant judged item; they count in precision@5 and hit rate but not in recall, MRR, MAP or nDCG.
  • Ranked by score (highest first); ties broken by doc. Relevant = relevance ≥ 1; gain rel; precision@5 divides by 5. Intervals: 500 query resamples on the shared seeded stream (seed 42).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Ranking and retrieval quality
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.ranking 1.0.0 · spec 02b78a6618e22614
# Dataset: evt_ranking_one (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.errors import check_groups, check_rows
from codesplash.evaluate import ranking as rk  # twin: codesplashr cs_rank_*
from codesplash.stats import signflip

# %% Data
df = pd.read_parquet("tests/parity/fixtures/evt_ranking_one.parquet", columns=["query", "relevance", "score", "doc"])
n_input = len(df)
df["query"] = pd.Categorical(df["query"], categories=sorted(df["query"].dropna().unique()))
df["doc"] = pd.Categorical(df["doc"], categories=sorted(df["doc"].dropna().unique()))
df = df.dropna(subset=["query", "relevance", "score", "doc"])  # listwise deletion over the analysis columns
df["query"] = df["query"].cat.remove_unused_categories()
df["doc"] = df["doc"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["query", "relevance", "score", "doc"])  # infinite values stop the run (registry/errors.yaml)

# %% Rankings
# Each query's items ranked by score (highest first); ties by the item id, else by row order.
qc, rc, sc = "query", "relevance", "score"
ic = "doc"
yc = None
k = int(5)
gain_kind = "linear"  # exponential | linear
threshold = 1
reps = int(500)
conf = 0.95
seed = 42  # portable Wichmann–Hill stream: R resamples the same queries
check_rows(len(df), 2, "A ranking evaluation")
rel_all = df[rc].to_numpy(dtype=float)
if np.any(rel_all < 0):
    cs.cs_error("CS_E_INVALID_VALUES", column=rc, requirement="a relevance of 0 or more", count=int(np.sum(rel_all < 0)))
score_all = df[sc].to_numpy(dtype=float)
queries = [str(v) for v in df[qc].cat.categories]
check_groups(df[qc], qc, minimum=2)
systems = [str(v) for v in df[yc].cat.categories] if yc else ["(all rows)"]
qcol = df[qc].astype(str).to_numpy()
ycol = df[yc].astype(str).to_numpy() if yc else np.array(["(all rows)"] * len(df))
icol = df[ic].astype(str).to_numpy() if ic else None
k_max = max(k, 10)

per = {}     # system → list of per-query metric dicts (queries in level order; None when absent)
curves = {}  # system → (nDCG@j, recall@j) means over queries, j = 1..k_max
for s in systems:
    rows_s = []
    nd_c, rc_c = [], []
    for q in queries:
        m_idx = np.flatnonzero((qcol == q) & (ycol == s))
        if m_idx.size == 0:
            rows_s.append(None)
            continue
        tb = list(icol[m_idx]) if icol is not None else list(range(m_idx.size))
        o = rk.order_within(score_all[m_idx], tb)
        ranked = rel_all[m_idx][o]
        rows_s.append(rk.query_metrics(ranked, k, threshold, gain_kind))
        nd, rcv = rk.curve(ranked, k_max, threshold, gain_kind)
        nd_c.append(nd)
        rc_c.append(rcv)
    per[s] = rows_s
    curves[s] = ([rk._mean([c[j] for c in nd_c]) for j in range(k_max)], [rk._mean([c[j] for c in rc_c]) for j in range(k_max)])

# %% Summaries per system
summ = {}
for i, s in enumerate(systems):
    present = [q for q in per[s] if q is not None]
    if not present:
        cs.cs_error("CS_E_TOO_FEW_ROWS", what=f"System {s}", min=1, n=0)
    ci = rk.bootstrap_means(present, rk.METRICS, reps, seed, conf)
    summ[s] = {"n_queries": len(present), "n_no_relevant": sum(1 for q in present if q["n_relevant"] == 0),
               **{m: rk._mean([q[m] for q in present]) for m in rk.METRICS},
               **{f"{m}_low": ci[m][0] for m in rk.METRICS}, **{f"{m}_high": ci[m][1] for m in rk.METRICS}}
ref = systems[0]
head = summ[ref]
if head["n_queries"] < 2:
    cs.cs_error("CS_E_TOO_FEW_GROUPS", column=qc, min=2, k=head["n_queries"])

# %% Systems against the first (paired by query, nDCG@k)
comparisons = []
for s in systems[1:]:
    d = rk.paired_differences([q["ndcg"] if q else None for q in per[ref]], [q["ndcg"] if q else None for q in per[s]])
    lo, hi = rk.bootstrap_mean_ci(d, reps, seed, conf)
    sf = signflip.signflip_test(d, 0.0, "two-sided", reps, seed + 1) if len(d) >= 2 else None
    comparisons.append({"system": s, "n": len(d), "diff": float(np.mean(d)) if d else None, "low": lo, "high": hi,
                        "p": sf["p"] if sf else None, "how": (("exact" if sf["kind"] == "exact" else f"{sf['b']} random sign patterns") if sf else None)})

# %% Assumptions
n_q = head["n_queries"]
assumptions = [
    {"key": "judged", "label": "Judgments cover the ranked items", "status": "info",
     "detail": "Rows without a relevance judgment are dropped, not treated as non-relevant; recall and nDCG use the judged items of each query."},
    {"key": "queries", "label": "Enough queries", "status": "warn" if n_q < 25 else "pass",
     "detail": f"{n_q} queries" + ("; intervals are rough with fewer than 25." if n_q < 25 else ".")},
]
if head["n_no_relevant"]:
    warnings.append(f"{head['n_no_relevant']} of {n_q} queries have no relevant judged item; they count in precision@{k} and hit rate but not in recall, MRR, MAP or nDCG.")

# %% Result
pct = f"{conf:.0%}"
f3 = lambda v: "—" if v is None else f"{v:.3f}"
values = {"n_queries": n_q, "n_rows": int(len(df)), "k": k, "gain": gain_kind, "rel_threshold": threshold,
          "n_systems": len(systems), "reference_system": ref if yc else None, "n_no_relevant": head["n_no_relevant"],
          **{m: head[m] for m in rk.METRICS}, **{f"{m}_low": head[f"{m}_low"] for m in rk.METRICS},
          **{f"{m}_high": head[f"{m}_high"] for m in rk.METRICS}}
labels = {"ndcg": f"nDCG@{k}", "map": "MAP", "mrr": f"MRR@{k}", "precision_k": f"Precision@{k}", "recall_k": f"Recall@{k}", "hit_rate": f"Hit rate@{k}"}
tables = [{"key": "systems", "title": f"Ranking quality ({pct} intervals from resampling queries)",
           "columns": [{"key": "system", "label": yc or "System", "type": "string"}, {"key": "n_queries", "label": "Queries", "type": "integer"}]
                      + [c for m in rk.METRICS for c in ({"key": m, "label": labels[m], "type": "number"},
                                                          {"key": f"{m}_ci", "label": f"{labels[m]} {pct} CI", "type": "string"})],
           "rows": [{"system": s, "n_queries": summ[s]["n_queries"],
                     **{m: summ[s][m] for m in rk.METRICS},
                     **{f"{m}_ci": (f"{f3(summ[s][f'{m}_low'])} to {f3(summ[s][f'{m}_high'])}") for m in rk.METRICS}} for s in systems]}]
if comparisons:
    tables.append({"key": "comparisons", "title": f"nDCG@{k} against {ref} (paired by query)",
                   "columns": [{"key": "system", "label": yc, "type": "string"}, {"key": "n", "label": "Queries in both", "type": "integer"},
                               {"key": "diff", "label": "Mean difference", "type": "number"}, {"key": "low", "label": f"{pct} CI low", "type": "number"},
                               {"key": "high", "label": f"{pct} CI high", "type": "number"}, {"key": "p", "label": "p (sign flip)", "type": "pvalue"},
                               {"key": "how", "label": "Null", "type": "string"}],
                   "rows": comparisons})
q_rows = []
for q, m in zip(queries, per[ref]):
    if m is not None and len(q_rows) < 500:
        q_rows.append({"query": q, "items": m["n_items"], "relevant": m["n_relevant"], "ndcg": m["ndcg"], "ap": m["map"], "rr": m["mrr"], "recall": m["recall_k"]})
tables.append({"key": "queries", "title": f"Per query ({ref})" if yc else "Per query",
               "columns": [{"key": "query", "label": qc, "type": "string"}, {"key": "items", "label": "Judged items", "type": "integer"},
                           {"key": "relevant", "label": "Relevant", "type": "integer"}, {"key": "ndcg", "label": f"nDCG@{k}", "type": "number"},
                           {"key": "ap", "label": "AP", "type": "number"}, {"key": "rr", "label": f"RR@{k}", "type": "number"},
                           {"key": "recall", "label": f"Recall@{k}", "type": "number"}],
               "rows": q_rows, "note": "First 500 queries." if n_q > 500 else None})
cutoffs = list(range(1, k_max + 1))
charts = [cs.chart("at-k", "metric-at-k", "nDCG and recall at each cutoff", {
    "k": cs.col("Cutoff k", [j for s in systems for _ in (0, 1) for j in cutoffs], "numeric"),
    "value": cs.col("Mean over queries", [v for s in systems for v in curves[s][0] + curves[s][1]]),
    "metric": cs.col("Metric", [lab for s in systems for lab in ("nDCG",) * k_max + ("Recall",) * k_max], "categorical", levels=["nDCG", "Recall"]),
    "system": cs.col(yc or "System", [s for s in systems for _ in range(2 * k_max)], "categorical", levels=systems)},
    controls={"k": k})]
nd_vals = [(s, q["ndcg"]) for s in systems for q in per[s] if q is not None and q["ndcg"] is not None]
if nd_vals:
    charts.append(cs.chart("per-query", "box-violin", f"nDCG@{k} per query", {
        "y": cs.col(f"nDCG@{k}", [v for _, v in nd_vals]),
        **({"group": cs.col(yc, [s for s, _ in nd_vals], "categorical", levels=systems)} if yc else {})}))
lead = f" for {ref}" if yc else ""
summary = (f"Across {n_q} queries{lead}, nDCG@{k} = {f3(head['ndcg'])} ({pct} CI {f3(head['ndcg_low'])} to {f3(head['ndcg_high'])}), "
           f"MAP = {f3(head['map'])}, MRR@{k} = {f3(head['mrr'])} and recall@{k} = {f3(head['recall_k'])}.")
for c in comparisons:
    summary += f" {c['system']} − {ref}: nDCG@{k} {c['diff']:+.3f} ({pct} CI {f3(c['low'])} to {f3(c['high'])}, {cs.fmt_p(c['p']) if c['p'] is not None else 'no test'})." if c["diff"] is not None else ""
cs.publish({
    "method": "evaluate.ranking",
    "methodVersion": "1.0.0",
    "title": "Ranking quality",
    "engine": cs.engine_info("pandas", "numpy"),
    "n": int(len(df)),
    "summary": summary,
    "statistics": [{"key": m, "label": labels[m], "value": head[m]} for m in ("ndcg", "map", "mrr", "recall_k")],
    "tables": tables,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Ranked by {sc} (highest first); ties broken by " + (f"{ic}." if ic else "row order.")
              + f" Relevant = {rc} ≥ {threshold:g}; gain " + ("2^rel − 1" if gain_kind == "exponential" else "rel")
              + f"; precision@{k} divides by {k}. Intervals: {reps} query resamples on the shared seeded stream (seed {seed})."],
    "charts": charts,
    "values": values,
})

With k = 5 and linear gain, the same system scores nDCG@5 = 0.945. Neither number is wrong; they answer different questions, so report the convention with the number.

05

Detectors: two errors and a threshold

Read

A detector (fraud alert, speaker verification, a screening test) gives a score, and a threshold turns it into "accept" or "flag". Lowering the threshold trades misses for false alarms.

Predict's Evaluation tab draws this trade-off for every binary model as a DET curveDET curve (detection error tradeoff)Miss rate against false positive rate on normal-deviate axes, so small error rates are easy to compare between scorers.: miss rate against false positive rate on stretched (normal-deviate) axes, so 1% and 0.1% are as easy to tell apart as 40% and 50%.

06

Equal error rate and detection cost

Read
  • The equal error rateEqual error rate (EER)The error rate at the threshold where false alarms and misses are equally common; 0 is perfect and 0.5 is guessing. is where the curve crosses the diagonal: false alarms and misses equally common.
  • The detection costDetection cost function (DCF)Cost of misses and false alarms at a threshold, weighted by their costs and the share of positives; 1 = no better than one fixed answer. weighs each error by its cost and by how common positives are, scaled so 1 is no better than always giving one answer.
  • The minimum DCF picks the best threshold on the rows it scores, so it's optimistic. The actual DCF uses the threshold you apply, chosen in advance. Report the actual one.
07

Check yourself

Read

Check yourself

A help-desk search shows one suggested article; users stop at the first useful one. Which metric matches that?

Show the answer

Answer: b

MRR rewards the rank of the first relevant result only, which is all that matters when one answer is enough.

Check yourself

A query has one relevant item (gain 1). The system ranks it third. With DCG = Σ gain / log2(rank + 1), what is nDCG?

Show the answer

Answer: 0.5

DCG = 1 / log2(4) = 0.5; the best order puts it first, DCG = 1 / log2(2) = 1. nDCG = 0.5 / 1 = 0.5.

Check yourself

Only the documents system A returned were judged. System B returns different documents, mostly unjudged. What happens to B's recall@10?

Show the answer

Answer: b

Unjudged rows are left out, so B is scored on a different and smaller set. Judge a pooled set from both systems before comparing them.

Check yourself

Why is the minimum DCF optimistic?

Show the answer

Answer: a

Choosing and scoring on the same rows flatters the model. The actual DCF uses a threshold fixed in advance.

Concepts in this lesson