Skip to content

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.

Applied ~15 min9 steps

What runs in CodeSplash

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

Read first

01

Judgments first

Read

To 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.
02

nDCG: graded and position-aware

Read

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. gives each item a gain from its grade and discounts it by its rank, then divides by the best possible ordering:

DCG@k=∑r=1k2relr−1log⁡2(r+1),nDCG@k=DCG@kIDCG@k\mathrm{DCG@}k = \sum_{r=1}^{k}\frac{2^{\mathrm{rel}_r}-1}{\log_2(r+1)}, \qquad \mathrm{nDCG@}k = \frac{\mathrm{DCG@}k}{\mathrm{IDCG@}k}

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.

3

Metrics look at the top k documents.

1.2

How fast repeated words stop adding score.

0.75

How much long documents are penalized.

  1. 1●○Car insurance prices rise again this year2.12
  2. 2●●How much does vehicle maintenance cost per year2.01
  3. 3○○Bayesian priors and posterior distributions explained0.00
  4. 4○○Weather forecast: heavy rain and strong wind expected tomorrow0.00
  5. 5○○A beginner's guide to the p-value and multiple testing correction0.00
  6. 6○○Baking bread at home: flour, water, yeast and salt0.00
  7. 7○○Storm warning issued as rainfall totals climb0.00
  8. 8●●Fixing an automobile engine: a mechanic explains common repairs0.00
  9. 9○○Bonferroni and Holm corrections control the familywise error rate0.00
  10. 10○○Sourdough starter tips for better loaves0.00
BM250.60 / 0.67TF-IDF cosine0.60 / 0.67Toy dense vectors0.97 / 1.00Late interaction (MaxSim)0.97 / 1.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.

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.

03

One system

Read
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,
})

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.

04

Two systems, same 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,
})

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.

05

Why pairing helps

Explore

BExplorable · 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?

How sure?
0.80
10
0.2
observedmirror

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 first; the figure appears when you commit.

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.

06

Unjudged is not irrelevant

Predict

Predict first

A new retriever returns a document no one has judged. What does Ranking and retrieval quality do with it?

It is counted as not relevantIt is dropped from the scoringIt is counted as relevant
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.

07

Where it stands in CodeSplash

Read
EntryIn CodeSplash
Recall@k, MRR, nDCG (EVA036)Runs in CodeSplash: Ranking and retrieval quality, query-resampled intervals and paired comparisons
Reference · EVA036 · Runs in CodeSplashRecall@k, MRR, and nDCG for retrievalEvaluate whether ranked documents, images, audio clips, or video clips place relevant items near the top.
08

Check: scoring retrieval

Checkpoint

Check 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.

09

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