An open source, non-profit web search engine
Score each query against one gold ranking, not several dates concatenated
Daoud Clarke9c1979a7b214
diff --git a/mwmbl/rankeval/evaluation/evaluate.py b/mwmbl/rankeval/evaluation/evaluate.pyindex 97a16a1..b06acd2 100644--- a/mwmbl/rankeval/evaluation/evaluate.py+++ b/mwmbl/rankeval/evaluation/evaluate.py@@ -29,6 +29,32 @@ class RankingModel(ABC):pass+def latest_ranking(rankings):+ """The most recent scrape of one query's results, in rank order.++ The rankings dataset holds several scrapes of the same query taken on different+ dates - 1,135 of the 5,969 test queries, up to 16 dates each - and their rows sit+ consecutively under the one query. Taking the first ten rows therefore mixes dates:+ the ten are not one ranking, and a URL that appears in two scrapes appears twice at+ two different ranks. Keeping only the latest date makes the gold set what it is meant+ to be - one ranking per query.+ """+ latest = rankings["date_retrieved"].max()+ return rankings[rankings["date_retrieved"] == latest].sort_values("rank")+++def gold_scores_for(rankings) -> dict[str, float]:+ """The gold URL -> click-weight map for one query's rows of the rankings dataset.++ Duplicate URLs are dropped keeping the best rank, because the map is keyed by URL:+ left in, the *worse* rank's weight is the one that would survive.+ """+ ranking = latest_ranking(rankings).drop_duplicates(subset="url", keep="first")+ top_ranked = ranking[["url"]].iloc[:NUM_RESULTS_FOR_EVAL].copy()+ top_ranked["score"] = CLICK_PROPORTIONS[:len(top_ranked)]+ return top_ranked.set_index("url")["score"].to_dict()++def evaluate(ranking_model: RankingModel, fraction: float = 1.0, use_test=False):# TODO:# - output feature importances from XGBoost@@ -57,9 +83,7 @@ def evaluate(ranking_model: RankingModel, fraction: float = 1.0, use_test=False)if query not in random_queries:continue- top_ranked = rankings[['url']].iloc[:NUM_RESULTS_FOR_EVAL]- top_ranked['score'] = CLICK_PROPORTIONS[:len(top_ranked)]- scores = top_ranked.set_index('url')['score'].to_dict()+ scores = gold_scores_for(rankings)print(f"Query: '{query}'", scores)start_time = time.perf_counter()diff --git a/mwmbl/rankeval/evaluation/evaluate_fallback.py b/mwmbl/rankeval/evaluation/evaluate_fallback.pyindex a34d1aa..261cce2 100644--- a/mwmbl/rankeval/evaluation/evaluate_fallback.py+++ b/mwmbl/rankeval/evaluation/evaluate_fallback.py@@ -53,7 +53,7 @@ django.setup()import mwmbl.rankeval.evaluation.evaluate_super_search as ss_module # noqa: E402from mwmbl.rankeval.evaluation.evaluate import ( # noqa: E402- CLICK_PROPORTIONS, NUM_RESULTS_FOR_EVAL, RankingModel)+ NUM_RESULTS_FOR_EVAL, RankingModel, gold_scores_for)from mwmbl.rankeval.evaluation.evaluate_ranker import DummyCompleter, MwmblRankingModel # noqa: E402from mwmbl.rankeval.evaluation.evaluate_super_search import SuperSearchRankingModel # noqa: E402from mwmbl.rankeval.evaluation.remote_index import RemoteIndex # noqa: E402@@ -166,9 +166,7 @@ def run():for query, rankings in dataset.groupby("query"):if query not in sampled:continue- top_ranked = rankings[["url"]].iloc[:NUM_RESULTS_FOR_EVAL].copy()- top_ranked["score"] = CLICK_PROPORTIONS[:len(top_ranked)]- gold_scores = top_ranked.set_index("url")["score"].to_dict()+ gold_scores = gold_scores_for(rankings)std_results = standard.predict(query)standard_count[query] = len(std_results)diff --git a/test/test_rankeval_gold.py b/test/test_rankeval_gold.pynew file mode 100644index 0000000..6578202--- /dev/null+++ b/test/test_rankeval_gold.py@@ -0,0 +1,73 @@+"""The gold ranking a query is scored against.++The rankings dataset holds several scrapes of the same query, taken on different dates+and stored as consecutive rows under the one query - 1,135 of the 5,969 test queries.+Every harness that scores against it goes through gold_scores_for, so this is where the+"one query, one ranking" rule has to hold.+"""+import pandas as pd++from mwmbl.rankeval.evaluation.evaluate import (+ CLICK_PROPORTIONS, gold_scores_for, latest_ranking)+++def _rankings(rows):+ return pd.DataFrame(rows, columns=["query", "url", "rank", "date_retrieved"])+++def test_latest_ranking_keeps_only_the_most_recent_scrape():+ rankings = _rankings([+ ("piles", "https://old-first", 1, "2025-07-20"),+ ("piles", "https://old-second", 2, "2025-07-20"),+ ("piles", "https://new-first", 1, "2026-01-29"),+ ("piles", "https://new-second", 2, "2026-01-29"),+ ])++ assert list(latest_ranking(rankings)["url"]) == ["https://new-first", "https://new-second"]+++def test_latest_ranking_sorts_by_rank():+ rankings = _rankings([+ ("piles", "https://second", 2, "2026-01-29"),+ ("piles", "https://first", 1, "2026-01-29"),+ ])++ assert list(latest_ranking(rankings)["url"]) == ["https://first", "https://second"]+++def test_gold_scores_ignore_an_earlier_scrape():+ # Without this the first ten rows would be the older scrape's, and a URL appearing in+ # both would take the weight of whichever row came second - the *worse* rank.+ rankings = _rankings([+ ("piles", "https://nhs", 5, "2025-07-20"),+ ("piles", "https://nhs", 1, "2026-01-29"),+ ("piles", "https://mayo", 2, "2026-01-29"),+ ])++ assert gold_scores_for(rankings) == {+ "https://nhs": CLICK_PROPORTIONS[0],+ "https://mayo": CLICK_PROPORTIONS[1],+ }+++def test_gold_scores_drop_a_duplicate_url_keeping_the_best_rank():+ rankings = _rankings([+ ("piles", "https://nhs", 1, "2026-01-29"),+ ("piles", "https://mayo", 2, "2026-01-29"),+ ("piles", "https://nhs", 3, "2026-01-29"),+ ])++ assert gold_scores_for(rankings) == {+ "https://nhs": CLICK_PROPORTIONS[0],+ "https://mayo": CLICK_PROPORTIONS[1],+ }+++def test_gold_scores_take_at_most_ten_results():+ rankings = _rankings([("piles", f"https://result-{i}", i, "2026-01-29")+ for i in range(1, 16)])++ scores = gold_scores_for(rankings)+ assert len(scores) == len(CLICK_PROPORTIONS)+ assert scores["https://result-1"] == CLICK_PROPORTIONS[0]+ assert "https://result-11" not in scores