Scoring a retriever: recall@k, MRR and nDCG
Judge rankings with relevance labels per query. Compute nDCG by hand, read recall@k, MRR and MAP with intervals over queries, and compare two systems on the same queries, minding unjudged items, gains and cutoffs.
What runs in CodeSplash
- EVA036Recall@k, MRR, and nDCG for retrieval Runs in CodeSplash
- Ranking and retrieval quality Verified in Python and R
You will be able to
- Compute nDCG@k from graded relevance labels
- Choose between recall@k, MRR, MAP and nDCG for a retrieval task
- Explain why queries, not items, are the units for intervals and comparisons
- Compare two retrievers on the same judged queries
Judgments first
ReadTo score a retriever you need, for each query, relevance judgments on the items it returned: relevant or not, or graded (0 not, 1 partly, 2 highly relevant). Every metric is computed per query and then averaged over queries.
Different questions call for different metrics:
- Recall@k: what share of a query's relevant items appear in the top k? Matters when a later step, such as a reader or a person, needs all of them.
- Reciprocal rank: one over the rank of the first relevant item. MRRMean 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. averages it; good when one right answer is enough.
- MAP: precision averaged over the ranks of every relevant item.
nDCG: graded and position-aware
ReadnDCG@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. gives each item a gain from its grade and discounts it by its rank, then divides by the best possible ordering:
The reference program ranks items graded 0, 2, 1, 0 and scores the top three: nDCG@3 = 0.659. The best item sits second instead of first. With linear gains (rel instead of 2^rel − 1) grade 2 counts twice grade 1 instead of three times: say which gain you used.
DExplorable · Retrieval: BM25, dense vectors and late interaction
When does matching words beat matching meanings, and how do we score a ranking?
Query
Each query has graded relevance labels for the ten documents.
Method
BM25 and TF-IDF match words; the toy dense vectors and MaxSim match themes.
Metrics look at the top k documents.
How fast repeated words stop adding score.
How much long documents are penalized.
- 1●○Car insurance prices rise again this year2.12
- 2●●How much does vehicle maintenance cost per year2.01
- 3○○Bayesian priors and posterior distributions explained0.00
- 4○○Weather forecast: heavy rain and strong wind expected tomorrow0.00
- 5○○A beginner's guide to the p-value and multiple testing correction0.00
- 6○○Baking bread at home: flour, water, yeast and salt0.00
- 7○○Storm warning issued as rainfall totals climb0.00
- 8●●Fixing an automobile engine: a mechanic explains common repairs0.00
- 9○○Bonferroni and Holm corrections control the familywise error rate0.00
- 10○○Sourdough starter tips for better loaves0.00
- nDCG@3
- Recall@3
- nDCG@k
- 0.601
- Recall@k
- 0.667
- Precision@k
- 0.667
- Reciprocal rank
- 1.000
- Puzzle: For “car repair cost”, find a method that puts both very relevant documents in the top 3.
- Puzzle: For the query “holm”, find a method with reciprocal rank 1.
BM25 for “car repair cost”: nDCG@3 0.601, recall@3 0.67, reciprocal rank 1.00. The top document is “Car insurance prices rise again this year”. The dense vectors here are a hand-made toy with four themes, not a trained encoder.
One system
ReadAcross 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
View data
| Cutoff k | Metric | System | Mean over queries |
|---|---|---|---|
| 1 | nDCG | (all rows) | 0.9368 |
| 2 | nDCG | (all rows) | 0.9323 |
| 3 | nDCG | (all rows) | 0.9071 |
| 4 | nDCG | (all rows) | 0.9338 |
| 5 | nDCG | (all rows) | 0.9448 |
| 6 | nDCG | (all rows) | 0.9439 |
| 7 | nDCG | (all rows) | 0.9539 |
| 8 | nDCG | (all rows) | 0.9530 |
| 9 | nDCG | (all rows) | 0.9566 |
| 10 | nDCG | (all rows) | 0.9602 |
| 1 | Recall | (all rows) | 0.2317 |
| 2 | Recall | (all rows) | 0.4375 |
| 3 | Recall | (all rows) | 0.5802 |
| 4 | Recall | (all rows) | 0.7274 |
| 5 | Recall | (all rows) | 0.8327 |
| 6 | Recall | (all rows) | 0.8784 |
| 7 | Recall | (all rows) | 0.9274 |
| 8 | Recall | (all rows) | 0.9462 |
| 9 | Recall | (all rows) | 0.9726 |
| 10 | Recall | (all rows) | 0.9899 |
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)
| System | Queries | nDCG@5 | nDCG@5 95% CI | MAP | MAP 95% CI | MRR@5 | MRR@5 95% CI | Precision@5 | Precision@5 95% CI | Recall@5 | Recall@5 95% CI | Hit rate@5 | Hit rate@5 95% CI |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| (all rows) | 30 | 0.9448 | 0.918 to 0.966 | 0.9416 | 0.907 to 0.968 | 1 | 1.000 to 1.000 | 0.7733 | 0.700 to 0.853 | 0.8327 | 0.762 to 0.890 | 0.9667 | 0.900 to 1.000 |
Per query
| query | Judged items | Relevant | nDCG@5 | AP | RR@5 | Recall@5 |
|---|---|---|---|---|---|---|
| q01 | 9 | 9 | 1 | 1 | 1 | 0.5556 |
| q02 | 6 | 2 | 1 | 1 | 1 | 1 |
| q03 | 11 | 6 | 1 | 0.9762 | 1 | 0.8333 |
| q04 | 9 | 5 | 0.9561 | 1 | 1 | 1 |
| q05 | 9 | 4 | 0.7438 | 0.9167 | 1 | 0.7500 |
| q06 | 11 | 9 | 0.8158 | 0.9889 | 1 | 0.5556 |
| q07 | 11 | 0 | — | — | — | — |
| q08 | 12 | 9 | 0.9808 | 1 | 1 | 0.5556 |
| q09 | 11 | 4 | 0.8181 | 0.6679 | 1 | 0.7500 |
| q10 | 13 | 6 | 0.9671 | 0.9762 | 1 | 0.8333 |
| q11 | 7 | 3 | 0.9854 | 0.9167 | 1 | 1 |
| q12 | 6 | 3 | 0.7960 | 0.9167 | 1 | 1 |
| q13 | 13 | 6 | 0.9403 | 0.8000 | 1 | 0.6667 |
| q14 | 12 | 8 | 0.9943 | 0.9106 | 1 | 0.6250 |
| q15 | 10 | 6 | 0.9218 | 0.9484 | 1 | 0.6667 |
| q16 | 8 | 3 | 1 | 1 | 1 | 1 |
| q17 | 13 | 10 | 0.9214 | 1 | 1 | 0.5000 |
| q18 | 12 | 9 | 0.9486 | 1 | 1 | 0.5556 |
| q19 | 7 | 4 | 1 | 1 | 1 | 1 |
| q20 | 10 | 5 | 1 | 1 | 1 | 1 |
| q21 | 7 | 3 | 1 | 1 | 1 | 1 |
| q22 | 9 | 5 | 1 | 1 | 1 | 1 |
| q23 | 12 | 5 | 0.9336 | 0.9267 | 1 | 0.8000 |
| q24 | 14 | 6 | 0.9105 | 0.8833 | 1 | 0.6667 |
| q25 | 7 | 4 | 0.9122 | 1 | 1 | 1 |
| q26 | 7 | 2 | 0.9072 | 0.7000 | 1 | 1 |
| q27 | 6 | 3 | 0.9779 | 0.9167 | 1 | 1 |
| q28 | 6 | 4 | 1 | 1 | 1 | 1 |
| q29 | 11 | 6 | 1 | 0.9444 | 1 | 0.8333 |
| q30 | 10 | 3 | 0.9675 | 0.9167 | 1 | 1 |
- 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
))
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)
| System | Queries | nDCG@5 | nDCG@5 95% CI | MAP | MAP 95% CI | MRR@5 | MRR@5 95% CI | Precision@5 | Precision@5 95% CI | Recall@5 | Recall@5 95% CI | Hit rate@5 | Hit rate@5 95% CI |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| (all rows) | 30 | 0.9448 | 0.918 to 0.966 | 0.9416 | 0.907 to 0.968 | 1 | 1.000 to 1.000 | 0.7733 | 0.700 to 0.853 | 0.8327 | 0.762 to 0.890 | 0.9667 | 0.900 to 1.000 |
Per query
| query | Judged items | Relevant | nDCG@5 | AP | RR@5 | Recall@5 |
|---|---|---|---|---|---|---|
| q01 | 9 | 9 | 1 | 1 | 1 | 0.5556 |
| q02 | 6 | 2 | 1 | 1 | 1 | 1 |
| q03 | 11 | 6 | 1 | 0.9762 | 1 | 0.8333 |
| q04 | 9 | 5 | 0.9561 | 1 | 1 | 1 |
| q05 | 9 | 4 | 0.7438 | 0.9167 | 1 | 0.7500 |
| q06 | 11 | 9 | 0.8158 | 0.9889 | 1 | 0.5556 |
| q07 | 11 | 0 | — | — | — | — |
| q08 | 12 | 9 | 0.9808 | 1 | 1 | 0.5556 |
| q09 | 11 | 4 | 0.8181 | 0.6679 | 1 | 0.7500 |
| q10 | 13 | 6 | 0.9671 | 0.9762 | 1 | 0.8333 |
| q11 | 7 | 3 | 0.9854 | 0.9167 | 1 | 1 |
| q12 | 6 | 3 | 0.7960 | 0.9167 | 1 | 1 |
| q13 | 13 | 6 | 0.9403 | 0.8000 | 1 | 0.6667 |
| q14 | 12 | 8 | 0.9943 | 0.9106 | 1 | 0.6250 |
| q15 | 10 | 6 | 0.9218 | 0.9484 | 1 | 0.6667 |
| q16 | 8 | 3 | 1 | 1 | 1 | 1 |
| q17 | 13 | 10 | 0.9214 | 1 | 1 | 0.5000 |
| q18 | 12 | 9 | 0.9486 | 1 | 1 | 0.5556 |
| q19 | 7 | 4 | 1 | 1 | 1 | 1 |
| q20 | 10 | 5 | 1 | 1 | 1 | 1 |
| q21 | 7 | 3 | 1 | 1 | 1 | 1 |
| q22 | 9 | 5 | 1 | 1 | 1 | 1 |
| q23 | 12 | 5 | 0.9336 | 0.9267 | 1 | 0.8000 |
| q24 | 14 | 6 | 0.9105 | 0.8833 | 1 | 0.6667 |
| q25 | 7 | 4 | 0.9122 | 1 | 1 | 1 |
| q26 | 7 | 2 | 0.9072 | 0.7000 | 1 | 1 |
| q27 | 6 | 3 | 0.9779 | 0.9167 | 1 | 1 |
| q28 | 6 | 4 | 1 | 1 | 1 | 1 |
| q29 | 11 | 6 | 1 | 0.9444 | 1 | 0.8333 |
| q30 | 10 | 3 | 0.9675 | 0.9167 | 1 | 1 |
- 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,
})
Over 30 judged queries with linear gains, nDCG@5 is 0.945 (95% interval 0.918 to 0.966), MRR is 1.00 and recall@5 is 0.833. The first relevant item always comes first, yet some relevant items fall below rank 5.
Intervals resample whole queries, because items within a query aren't independent.
Two systems, same queries
ReadAcross 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
View data
| Cutoff k | Metric | system | Mean over queries |
|---|---|---|---|
| 1 | nDCG | keyword | 0.6667 |
| 2 | nDCG | keyword | 0.7783 |
| 3 | nDCG | keyword | 0.8082 |
| 4 | nDCG | keyword | 0.8315 |
| 5 | nDCG | keyword | 0.8400 |
| 6 | nDCG | keyword | 0.8470 |
| 7 | nDCG | keyword | 0.8607 |
| 8 | nDCG | keyword | 0.8641 |
| 9 | nDCG | keyword | 0.8702 |
| 10 | nDCG | keyword | 0.8731 |
| 1 | Recall | keyword | 0.1857 |
| 2 | Recall | keyword | 0.4059 |
| 3 | Recall | keyword | 0.5543 |
| 4 | Recall | keyword | 0.6785 |
| 5 | Recall | keyword | 0.7662 |
| 6 | Recall | keyword | 0.8295 |
| 7 | Recall | keyword | 0.8865 |
| 8 | Recall | keyword | 0.9256 |
| 9 | Recall | keyword | 0.9635 |
| 10 | Recall | keyword | 0.9765 |
| 1 | nDCG | semantic | 0.9080 |
| 2 | nDCG | semantic | 0.9099 |
| 3 | nDCG | semantic | 0.8939 |
| 4 | nDCG | semantic | 0.9274 |
| 5 | nDCG | semantic | 0.9367 |
| 6 | nDCG | semantic | 0.9390 |
| 7 | nDCG | semantic | 0.9465 |
| 8 | nDCG | semantic | 0.9462 |
| 9 | nDCG | semantic | 0.9491 |
| 10 | nDCG | semantic | 0.9510 |
| 1 | Recall | semantic | 0.2317 |
| 2 | Recall | semantic | 0.4375 |
| 3 | Recall | semantic | 0.5802 |
| 4 | Recall | semantic | 0.7274 |
| 5 | Recall | semantic | 0.8327 |
| 6 | Recall | semantic | 0.8784 |
| 7 | Recall | semantic | 0.9274 |
| 8 | Recall | semantic | 0.9462 |
| 9 | Recall | semantic | 0.9726 |
| 10 | Recall | semantic | 0.9899 |
View data
| system | nDCG@10 |
|---|---|
| keyword | 0.9794 |
| keyword | 0.6399 |
| keyword | 0.9525 |
| keyword | 0.9763 |
| keyword | 0.9781 |
| keyword | 0.7775 |
| keyword | 0.9766 |
| keyword | 0.9924 |
| keyword | 0.9050 |
| keyword | 0.8428 |
| keyword | 0.9515 |
| keyword | 0.9966 |
| keyword | 0.7171 |
| keyword | 0.6193 |
| keyword | 0.8308 |
| keyword | 0.9562 |
| keyword | 1 |
| keyword | 0.9539 |
| keyword | 0.9383 |
| keyword | 0.8428 |
| keyword | 0.8505 |
| keyword | 0.9605 |
| keyword | 0.9900 |
| keyword | 0.7420 |
| keyword | 0.6590 |
| keyword | 0.7865 |
| keyword | 0.8592 |
| keyword | 0.9911 |
| keyword | 0.6546 |
| semantic | 1 |
| semantic | 1 |
| semantic | 0.9975 |
| semantic | 0.9296 |
| semantic | 0.7327 |
| semantic | 0.8412 |
| semantic | 0.9756 |
| semantic | 0.9174 |
| semantic | 0.9634 |
| semantic | 0.9926 |
| semantic | 0.7076 |
| semantic | 0.9691 |
| semantic | 0.9733 |
| semantic | 0.9942 |
| semantic | 1 |
| semantic | 0.9432 |
| semantic | 0.9908 |
| semantic | 1 |
| semantic | 1 |
| semantic | 1 |
| semantic | 1 |
| semantic | 0.9889 |
| semantic | 0.9692 |
| semantic | 0.8152 |
| semantic | 0.9328 |
| semantic | 0.9832 |
| semantic | 1 |
| semantic | 0.9927 |
| semantic | 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)
| system | Queries | nDCG@10 | nDCG@10 95% CI | MAP | MAP 95% CI | MRR@10 | MRR@10 95% CI | Precision@10 | Precision@10 95% CI | Recall@10 | Recall@10 95% CI | Hit rate@10 | Hit rate@10 95% CI |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| keyword | 30 | 0.8731 | 0.827 to 0.916 | 0.8710 | 0.816 to 0.921 | 0.9483 | 0.883 to 1.000 | 0.4900 | 0.410 to 0.573 | 0.9765 | 0.955 to 0.994 | 0.9667 | 0.900 to 1.000 |
| semantic | 30 | 0.9510 | 0.922 to 0.976 | 0.9416 | 0.908 to 0.969 | 1 | 1.000 to 1.000 | 0.5000 | 0.417 to 0.587 | 0.9899 | 0.975 to 1.000 | 0.9667 | 0.900 to 1.000 |
nDCG@10 against keyword (paired by query)
| system | Queries in both | Mean difference | 95% CI low | 95% CI high | p (sign flip) | Null |
|---|---|---|---|---|---|---|
| semantic | 29 | 0.0778 | 0.0249 | 0.1313 | .008 | 2000 random sign patterns |
Per query (keyword)
| query | Judged items | Relevant | nDCG@10 | AP | RR@10 | Recall@10 |
|---|---|---|---|---|---|---|
| q01 | 9 | 9 | 0.9794 | 1 | 1 | 1 |
| q02 | 6 | 2 | 0.6399 | 0.5000 | 0.5000 | 1 |
| q03 | 11 | 6 | 0.9525 | 0.8502 | 1 | 0.8333 |
| q04 | 9 | 5 | 0.9763 | 0.8850 | 1 | 1 |
| q05 | 9 | 4 | 0.9781 | 0.8167 | 1 | 1 |
| q06 | 11 | 9 | 0.7775 | 0.9675 | 1 | 0.8889 |
| q07 | 11 | 0 | — | — | — | — |
| q08 | 12 | 9 | 0.9766 | 0.9017 | 1 | 0.8889 |
| q09 | 11 | 4 | 0.9924 | 0.9167 | 1 | 1 |
| q10 | 13 | 6 | 0.9050 | 0.6759 | 1 | 0.8333 |
| q11 | 7 | 3 | 0.8428 | 1 | 1 | 1 |
| q12 | 6 | 3 | 0.9515 | 0.8056 | 1 | 1 |
| q13 | 13 | 6 | 0.9966 | 0.9444 | 1 | 1 |
| q14 | 12 | 8 | 0.7171 | 0.9583 | 1 | 0.8750 |
| q15 | 10 | 6 | 0.6193 | 0.8819 | 1 | 1 |
| q16 | 8 | 3 | 0.8308 | 0.8667 | 1 | 1 |
| q17 | 13 | 10 | 0.9562 | 1 | 1 | 1 |
| q18 | 12 | 9 | 1 | 1 | 1 | 1 |
| q19 | 7 | 4 | 0.9539 | 0.7929 | 1 | 1 |
| q20 | 10 | 5 | 0.9383 | 1 | 1 | 1 |
| q21 | 7 | 3 | 0.8428 | 1 | 1 | 1 |
| q22 | 9 | 5 | 0.8505 | 0.9429 | 1 | 1 |
| q23 | 12 | 5 | 0.9605 | 0.9429 | 1 | 1 |
| q24 | 14 | 6 | 0.9900 | 0.8972 | 1 | 1 |
| q25 | 7 | 4 | 0.7420 | 0.8875 | 1 | 1 |
| q26 | 7 | 2 | 0.6590 | 0.5833 | 0.5000 | 1 |
| q27 | 6 | 3 | 0.7865 | 0.8333 | 1 | 1 |
| q28 | 6 | 4 | 0.8592 | 1 | 1 | 1 |
| q29 | 11 | 6 | 0.9911 | 0.9333 | 1 | 1 |
| q30 | 10 | 3 | 0.6546 | 0.4762 | 0.5000 | 1 |
- 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
))
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)
| system | Queries | nDCG@10 | nDCG@10 95% CI | MAP | MAP 95% CI | MRR@10 | MRR@10 95% CI | Precision@10 | Precision@10 95% CI | Recall@10 | Recall@10 95% CI | Hit rate@10 | Hit rate@10 95% CI |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| keyword | 30 | 0.8731 | 0.827 to 0.916 | 0.8710 | 0.816 to 0.921 | 0.9483 | 0.883 to 1.000 | 0.4900 | 0.410 to 0.573 | 0.9765 | 0.955 to 0.994 | 0.9667 | 0.900 to 1.000 |
| semantic | 30 | 0.9510 | 0.922 to 0.976 | 0.9416 | 0.908 to 0.969 | 1 | 1.000 to 1.000 | 0.5000 | 0.417 to 0.587 | 0.9899 | 0.975 to 1.000 | 0.9667 | 0.900 to 1.000 |
nDCG@10 against keyword (paired by query)
| system | Queries in both | Mean difference | 95% CI low | 95% CI high | p (sign flip) | Null |
|---|---|---|---|---|---|---|
| semantic | 29 | 0.0778 | 0.0249 | 0.1313 | .008 | 2000 random sign patterns |
Per query (keyword)
| query | Judged items | Relevant | nDCG@10 | AP | RR@10 | Recall@10 |
|---|---|---|---|---|---|---|
| q01 | 9 | 9 | 0.9794 | 1 | 1 | 1 |
| q02 | 6 | 2 | 0.6399 | 0.5000 | 0.5000 | 1 |
| q03 | 11 | 6 | 0.9525 | 0.8502 | 1 | 0.8333 |
| q04 | 9 | 5 | 0.9763 | 0.8850 | 1 | 1 |
| q05 | 9 | 4 | 0.9781 | 0.8167 | 1 | 1 |
| q06 | 11 | 9 | 0.7775 | 0.9675 | 1 | 0.8889 |
| q07 | 11 | 0 | — | — | — | — |
| q08 | 12 | 9 | 0.9766 | 0.9017 | 1 | 0.8889 |
| q09 | 11 | 4 | 0.9924 | 0.9167 | 1 | 1 |
| q10 | 13 | 6 | 0.9050 | 0.6759 | 1 | 0.8333 |
| q11 | 7 | 3 | 0.8428 | 1 | 1 | 1 |
| q12 | 6 | 3 | 0.9515 | 0.8056 | 1 | 1 |
| q13 | 13 | 6 | 0.9966 | 0.9444 | 1 | 1 |
| q14 | 12 | 8 | 0.7171 | 0.9583 | 1 | 0.8750 |
| q15 | 10 | 6 | 0.6193 | 0.8819 | 1 | 1 |
| q16 | 8 | 3 | 0.8308 | 0.8667 | 1 | 1 |
| q17 | 13 | 10 | 0.9562 | 1 | 1 | 1 |
| q18 | 12 | 9 | 1 | 1 | 1 | 1 |
| q19 | 7 | 4 | 0.9539 | 0.7929 | 1 | 1 |
| q20 | 10 | 5 | 0.9383 | 1 | 1 | 1 |
| q21 | 7 | 3 | 0.8428 | 1 | 1 | 1 |
| q22 | 9 | 5 | 0.8505 | 0.9429 | 1 | 1 |
| q23 | 12 | 5 | 0.9605 | 0.9429 | 1 | 1 |
| q24 | 14 | 6 | 0.9900 | 0.8972 | 1 | 1 |
| q25 | 7 | 4 | 0.7420 | 0.8875 | 1 | 1 |
| q26 | 7 | 2 | 0.6590 | 0.5833 | 0.5000 | 1 |
| q27 | 6 | 3 | 0.7865 | 0.8333 | 1 | 1 |
| q28 | 6 | 4 | 0.8592 | 1 | 1 | 1 |
| q29 | 11 | 6 | 0.9911 | 0.9333 | 1 | 1 |
| q30 | 10 | 3 | 0.6546 | 0.4762 | 0.5000 | 1 |
- 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,
})
Add a System column and both systems are scored on the same 30 queries. The keyword system's nDCG@10 is 0.873; the card then reports semantic minus keyword per query, with an interval and a p-value from a sign-flip testSign-flip testFlips the signs of paired differences in every possible way; exact when the differences are symmetric about zero. over queries.
Pairing by query removes the large differences between easy and hard queries, so a real gap shows up with fewer queries than two separate averages would need.
Why pairing helps
ExploreBExplorable · Flipping signs in paired data
How do you build a null distribution when each subject is their own control?
Which analysis gives the smaller p-value?
Under the null, "after" and "before" are interchangeable within a pair, so each difference could have had either sign. There are 1024 equally likely arrangements.
Commit your prediction above to see the result
Make your prediction to see the result.
Think of each pair as one query scored by two systems. Raise Spread between subjects, the way easy and hard queries differ, and compare the sign-flip and unpaired p-values: pairing removes that spread, so the same difference between systems stands out.
Unjudged is not irrelevant
PredictPredict first
A new retriever returns a document no one has judged. What does Ranking and retrieval quality do with it?
Reveal
It is dropped: rows without a judgment are not treated as non-relevant. Counting them as irrelevant would punish a new system for finding documents the old judgments never covered. Judge the top results of every system you compare.
Where it stands in CodeSplash
Read| Entry | In CodeSplash |
|---|---|
| Recall@k, MRR, nDCG (EVA036) | Runs in CodeSplash: Ranking and retrieval quality, query-resampled intervals and paired comparisons |
Check: scoring retrieval
CheckpointCheck yourself
A ranking's top three items have grades 0, 2, 1 (exponential gains, log2(rank + 1) discount); the best possible top three would be 2, 1, 0. What is nDCG@3, to three decimals?
Show the answer
Answer: 0.6590018048024133
DCG = 0 + 3/log23 + 1/2 ≈ 2.393; the ideal is 3 + 1/log23 ≈ 3.631; their ratio is about 0.659.
Check yourself
A support search shows one answer, and users read only the first result. Which metric fits best?
Show the answer
Answer: a
If only the first result is read, what matters is how high the first relevant item ranks.
Check yourself
A retriever feeds its top 20 passages to a reader that writes an answer from all of them. Which metric matters most for the retriever?
Show the answer
Answer: b
The reader sees all 20, so order within them matters less than whether the needed passages are there at all.
Check yourself
Why does CodeSplash compare two retrievers by flipping signs of per-query differences, instead of treating every judged item as a separate observation?
Show the answer
Answer: b
Each query contributes one difference. Pairing by query and resampling queries keeps the evidence honest.
Check yourself
Two papers report nDCG@10 for the same system, 0.71 and 0.68. Before suspecting a bug, what should you check?
Show the answer
Answer: a
nDCG has several conventions. Results compare only when gains, cutoffs, ties and unjudged items are handled the same way.
Recap
Recap- Metrics need per-query relevance judgments and are averaged over queries.
- Recall@k for coverage, MRR for the first hit, MAP for all hits, nDCG for graded, position-aware quality; state the gain and cutoff.
- Intervals and comparisons resample or pair by query.
- Ranking and retrieval quality drops unjudged rows and compares systems on the same queries, in Python and R.
Concepts in this lesson