Ranking quality and detection errors
Some models are judged by the order they put things in, others by the two kinds of error at a threshold. Score rankings query by query with nDCG, MAP and MRR, and read a detector's DET curve, equal error rate and detection cost.
What runs in CodeSplash
- Ranking and retrieval quality Verified in Python and R
You will be able to
- Choose between nDCG, MAP, MRR, precision and recall at a cutoff for a ranking task
- Compare two rankers query by query, with an interval and a paired test
- Read a DET curve, the equal error rate and the minimum and actual detection cost
When the order is the answer
ReadA search box, a recommender or a triage queue doesn't hand back one prediction per row. It hands back a list per query, and people read the top of it. Accuracy can't see that: what matters is whether the relevant items come first.
Which ranking metric
ReadSo ranking metrics are computed within each query and then averaged over queries:
| Metric | What it rewards | Use it when |
|---|---|---|
| nDCG@knDCG (normalized discounted cumulative gain)How well the top k results are ordered by relevance, from 0 to 1, where 1 is the best possible order of the judged items. | relevant items high up, more relevant ones higher still | relevance has grades (0–3) |
| MAPMean average precision (MAP)The average over queries of the precision at the rank of each relevant item, so it rewards putting every relevant item early. | every relevant item early in the full list | you want all of them |
| MRR@kMean reciprocal rank (MRR)The average over queries of 1 / rank of the first relevant result (0 when none is in the top k); good when one hit is enough. | the first relevant item early | one good answer is enough |
| Recall@k | finding the relevant items within k | the list is a shortlist someone reads |
| Precision@k | a clean top k | screen space is scarce |
nDCG divides each result's gain by and compares the sum with the best possible order of that query's judged items, so 1 means "couldn't have been ordered better".
Two search systems, thirty 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,
})
The keyword system reaches nDCG@10 = 0.873 (interval 0.827 to 0.916) over 30 queries. The comparison table pairs the systems by query: each query is scored by both, so their difference is measured on the same questions, and the interval resamples whole queries.
Predict first
When the intervals resample, what is drawn with replacement?
Reveal
Queries. Items within a query aren't independent: one hard query drags all of its items down together.
Pin the conventions before you compare
ReadRanking numbers move with small choices, so the method states each one:
- Ties in the score are broken by the item id (or row order), never at random.
- Gain: exponential makes a grade-3 item worth seven grade-1 items; linear makes it worth three.
- Cutoff k: choose it before comparing systems.
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
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,
})
With k = 5 and linear gain, the same system scores nDCG@5 = 0.945. Neither number is wrong; they answer different questions, so report the convention with the number.
Detectors: two errors and a threshold
ReadA detector (fraud alert, speaker verification, a screening test) gives a score, and a threshold turns it into "accept" or "flag". Lowering the threshold trades misses for false alarms.
Predict's Evaluation tab draws this trade-off for every binary model as a DET curveDET curve (detection error tradeoff)Miss rate against false positive rate on normal-deviate axes, so small error rates are easy to compare between scorers.: miss rate against false positive rate on stretched (normal-deviate) axes, so 1% and 0.1% are as easy to tell apart as 40% and 50%.
Equal error rate and detection cost
Read- The equal error rateEqual error rate (EER)The error rate at the threshold where false alarms and misses are equally common; 0 is perfect and 0.5 is guessing. is where the curve crosses the diagonal: false alarms and misses equally common.
- The detection costDetection cost function (DCF)Cost of misses and false alarms at a threshold, weighted by their costs and the share of positives; 1 = no better than one fixed answer. weighs each error by its cost and by how common positives are, scaled so 1 is no better than always giving one answer.
- The minimum DCF picks the best threshold on the rows it scores, so it's optimistic. The actual DCF uses the threshold you apply, chosen in advance. Report the actual one.
Check yourself
ReadCheck yourself
A help-desk search shows one suggested article; users stop at the first useful one. Which metric matches that?
Show the answer
Answer: b
MRR rewards the rank of the first relevant result only, which is all that matters when one answer is enough.
Check yourself
A query has one relevant item (gain 1). The system ranks it third. With DCG = Σ gain / log2(rank + 1), what is nDCG?
Show the answer
Answer: 0.5
DCG = 1 / log2(4) = 0.5; the best order puts it first, DCG = 1 / log2(2) = 1. nDCG = 0.5 / 1 = 0.5.
Check yourself
Only the documents system A returned were judged. System B returns different documents, mostly unjudged. What happens to B's recall@10?
Show the answer
Answer: b
Unjudged rows are left out, so B is scored on a different and smaller set. Judge a pooled set from both systems before comparing them.
Check yourself
Why is the minimum DCF optimistic?
Show the answer
Answer: a
Choosing and scoring on the same rows flatters the model. The actual DCF uses a threshold fixed in advance.
Concepts in this lesson