HEvaluate predictions · evaluate.ranking
Ranking and retrieval quality
How well does a ranking put the relevant items at the top, query by query?
Scores rankings against relevance judgments, one query at a time: nDCG at a cutoff, mean average precision, mean reciprocal rank, precision, recall and hit rate, averaged over queries with intervals from resampling queries. With a system column it compares each system with the first, paired by query.
A real result
Example “Two systems”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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
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).
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).
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Two systemsevt_ranking · item: doc · query: query · relevance: relevance · score: score · system: system
- One system k5 linearevt_ranking_one · item: doc · query: query · relevance: relevance · score: score
- Threshold 2 row tiesevt_ranking · query: query · relevance: relevance · score: score · system: system
- Perfect rankingevt_ranking · item: doc · query: query · relevance: relevance · score: ideal · system: system
- Degenerate constantevt_ranking_one · item: doc · query: query · relevance: relevance · score: score
- Degenerate n1evt_ranking_one · item: doc · query: query · relevance: relevance · score: score
- Degenerate n2evt_ranking_one · item: doc · query: query · relevance: relevance · score: score
- Degenerate n3evt_ranking_one · item: doc · query: query · relevance: relevance · score: score
In the guides
Where it sits in the decision guides
- Predict: regression MAE, RMSE, R²; classification accuracy, precision, recall, F1, AUC; calibration, lift, log loss · DS & ML Decision Guide · How to evaluate — common metrics by question type
What you need
- Querycategorical · 1 column
- Which search, user or request each row belongs to; items are ranked within each query.
- Relevance judgmentnumeric / boolean · 1 column
- How relevant the item is (0 = not relevant; grades such as 0–3 work), or true/false. Rows without a judgment are left out.
- Ranking scorenumeric · 1 column
- The system's score for the item; higher scores are ranked first.
- Item id (optional)categorical · 0–1 column
- The document or product id; tied scores are ordered by it so results don't depend on row order.
- System (optional)categorical · 0–1 column · 1–20 levels
- Several systems ranking the same queries; each is compared with the first, paired by query.
Choices you make
hypothesis
- Cutoff kdefault 10
Only the top k items count for nDCG, precision, recall, hit rate and reciprocal rank.
- Confidence leveldefault 0.95
How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.
options
- Gain of a relevance gradedefault exponential
How much each relevance grade is worth in nDCG; it only matters with graded relevance.
- Exponential (2^rel − 1)(default) — Highly relevant items count much more (Burges et al. 2005; most search benchmarks).
- Linear (rel) — Each grade counts its value (scikit-learn's ndcg_score).
- Relevant from gradedefault 1
Items with relevance at or above this count as relevant for MAP, MRR, precision, recall and hit rate.
statistics
- Query resamplesdefault 2000
Bootstrap resamples of whole queries for the intervals, and sign flips for comparisons.
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Judgments cover the ranked itemsNot checked from data: state why it holds
Unjudged items are dropped, not counted as non-relevant; sparse judgments make recall and nDCG look better than they are.
Enough queries
Queries are the unit of resampling; with fewer than 25 the intervals are rough.
What it reports
- n_queries
- Queries with at least one judged item for the first system; queries are the unit the intervals resample.
- n_rows
- Rows with a query, a relevance judgment and a score, across every system.
- k
- Only the top k items of each query count for nDCG, precision, recall, hit rate and reciprocal rank.
- gain
- exponential (2^rel − 1) or linear (rel): what each relevance grade is worth in nDCG.
- rel_threshold
- Items with relevance at or above this count as relevant for MAP, MRR, precision, recall and hit rate.
- n_systems
- How many systems were scored (1 without a system column).
- reference_system
- The first system: the headline numbers are its, and the others are compared with it query by query.
- n_no_relevant
- Queries whose judged items are all below the relevance threshold; they count in precision and hit rate only.
- ndcg
- Mean nDCG at the cutoff over queries with a relevant item, with a percentile interval from resampling queries.
- ndcg_low
- Mean nDCG at the cutoff over queries with a relevant item, with a percentile interval from resampling queries.
- ndcg_high
- Mean nDCG at the cutoff over queries with a relevant item, with a percentile interval from resampling queries.
- map
- Mean average precision over queries with a relevant item (full ranked list), with a query-resampling interval.
- map_low
- Mean average precision over queries with a relevant item (full ranked list), with a query-resampling interval.
- map_high
- Mean average precision over queries with a relevant item (full ranked list), with a query-resampling interval.
- mrr
- Mean of 1 / rank of the first relevant item within the top k (0 when none), with a query-resampling interval.
- mrr_low
- Mean of 1 / rank of the first relevant item within the top k (0 when none), with a query-resampling interval.
- mrr_high
- Mean of 1 / rank of the first relevant item within the top k (0 when none), with a query-resampling interval.
- precision_k
- Mean share of the top k items that are relevant (always divided by k), with a query-resampling interval.
- precision_k_low
- Mean share of the top k items that are relevant (always divided by k), with a query-resampling interval.
- precision_k_high
- Mean share of the top k items that are relevant (always divided by k), with a query-resampling interval.
- recall_k
- Mean share of each query's relevant judged items found in the top k, with a query-resampling interval.
- recall_k_low
- Mean share of each query's relevant judged items found in the top k, with a query-resampling interval.
- recall_k_high
- Mean share of each query's relevant judged items found in the top k, with a query-resampling interval.
- hit_rate
- Share of queries with at least one relevant item in the top k, with a query-resampling interval.
- hit_rate_low
- Share of queries with at least one relevant item in the top k, with a query-resampling interval.
- hit_rate_high
- Share of queries with at least one relevant item in the top k, with a query-resampling interval.
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- Both engines rank with the same pinned tie rule and resample the same queries from the shared Wichmann–Hill stream; sums can differ in the last bits (summation order).
The exact script CodeSplash ran for example “Two systems” · 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 exact script CodeSplash ran for example “Two systems” · 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
))
Sources
- Järvelin, K., & Kekäläinen, J. (2002). Cumulated gain-based evaluation of IR techniques. ACM Transactions on Information Systems, 20(4), 422–446.
- Voorhees, E. M. (1999). The TREC-8 question answering track report. Proceedings of TREC-8, 77–82.
- Burges, C., et al. (2005). Learning to rank using gradient descent. Proceedings of ICML, 89–96.
- Manning, C. D., Raghavan, P., & Schütze, H. (2008). Introduction to Information Retrieval, ch. 8. Cambridge University Press.
- Sakai, T. (2014). Statistical reform in information retrieval? SIGIR Forum, 48(1), 3–12.
From the CodeSplash method registry · evaluate.ranking v1.0.0.