177 lines
6.0 KiB
Python
177 lines
6.0 KiB
Python
"""Offline recommendation quality metrics.
|
|
|
|
Ground truth comes from ``reco_feedback`` for each mood preset. With
|
|
``--implicit``, favorites and ratings >= 8 are also treated as relevant.
|
|
|
|
python tools/evaluate_reco.py --implicit
|
|
python tools/evaluate_reco.py --implicit --save data/reco-baseline.json
|
|
python tools/evaluate_reco.py --implicit --compare data/reco-baseline.json
|
|
|
|
The snapshot is a plain JSON file; keep it in ``data/`` (not committed).
|
|
"""
|
|
|
|
import argparse
|
|
import json
|
|
import math
|
|
import os
|
|
import sys
|
|
from datetime import datetime, timezone
|
|
|
|
for stream in (sys.stdout, sys.stderr):
|
|
try:
|
|
stream.reconfigure(encoding="utf-8")
|
|
except Exception:
|
|
pass
|
|
|
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
|
|
import db
|
|
import reco
|
|
|
|
VERDICT_RELEVANCE = {"like": 3, "played": 1, "dislike": 0, "ignore": 0}
|
|
|
|
|
|
def dcg(relevances):
|
|
return sum((2 ** relevance - 1) / math.log2(index + 2)
|
|
for index, relevance in enumerate(relevances))
|
|
|
|
|
|
def ndcg_at_k(results, labels, k):
|
|
rels = [labels.get(appid, 0) for appid in results[:k]]
|
|
ideal = sorted(labels.values(), reverse=True)[:k]
|
|
denominator = dcg(ideal)
|
|
return dcg(rels) / denominator if denominator else 0.0
|
|
|
|
|
|
def precision_at_k(results, labels, k):
|
|
if not results:
|
|
return 0.0
|
|
hits = sum(1 for appid in results[:k] if labels.get(appid, 0) > 0)
|
|
return hits / min(k, len(results))
|
|
|
|
|
|
def recall_at_k(results, labels, k):
|
|
relevant = {appid for appid, value in labels.items() if value > 0}
|
|
if not relevant:
|
|
return 0.0
|
|
hits = sum(1 for appid in results[:k] if labels.get(appid, 0) > 0)
|
|
return hits / len(relevant)
|
|
|
|
|
|
def labels_for(con, mood_key, implicit=False):
|
|
labels = {}
|
|
for row in con.execute(
|
|
"SELECT appid, verdict FROM reco_feedback WHERE mood_key = ?", (mood_key,)):
|
|
labels[row["appid"]] = VERDICT_RELEVANCE.get(row["verdict"], 0)
|
|
if implicit:
|
|
for row in con.execute("SELECT appid, favorite, rating FROM personal"):
|
|
relevance = 2 if row["favorite"] else 1 if (row["rating"] or 0) >= 8 else 0
|
|
if relevance > labels.get(row["appid"], 0):
|
|
labels[row["appid"]] = relevance
|
|
return labels
|
|
|
|
|
|
def evaluate(con, limit=20, presets=None, implicit=False):
|
|
names = presets or [r["name"] for r in con.execute("SELECT name FROM moods ORDER BY name")]
|
|
results = {}
|
|
for name in names:
|
|
try:
|
|
mood = reco.load_mood(con, preset=name)
|
|
except KeyError:
|
|
continue
|
|
key = reco.mood_key(mood)
|
|
labels = labels_for(con, key, implicit)
|
|
if not any(value > 0 for value in labels.values()):
|
|
continue
|
|
_, games = reco.recommend(con, mood, limit=limit, feedback_key=None)
|
|
appids = [game["appid"] for game in games]
|
|
results[name] = {
|
|
"ndcg": round(ndcg_at_k(appids, labels, limit), 4),
|
|
"precision": round(precision_at_k(appids, labels, limit), 4),
|
|
"recall": round(recall_at_k(appids, labels, limit), 4),
|
|
"relevant": sum(1 for value in labels.values() if value > 0),
|
|
"returned": len(appids),
|
|
}
|
|
return results
|
|
|
|
|
|
def aggregate(results):
|
|
if not results:
|
|
return {"presets": 0, "ndcg": 0.0, "precision": 0.0, "recall": 0.0}
|
|
count = len(results)
|
|
return {
|
|
"presets": count,
|
|
"ndcg": round(sum(item["ndcg"] for item in results.values()) / count, 4),
|
|
"precision": round(sum(item["precision"] for item in results.values()) / count, 4),
|
|
"recall": round(sum(item["recall"] for item in results.values()) / count, 4),
|
|
}
|
|
|
|
|
|
def print_results(results):
|
|
if not results:
|
|
print("No labeled presets: add feedback or run with --implicit")
|
|
return
|
|
print(f"{'preset':28} {'NDCG':>7} {'P@k':>7} {'R@k':>7} relevant")
|
|
for name, item in results.items():
|
|
print(f"{name:28} {item['ndcg']:7.3f} {item['precision']:7.3f} "
|
|
f"{item['recall']:7.3f} {item['relevant']}")
|
|
|
|
|
|
def compare(baseline, current):
|
|
base = baseline.get("presets", {})
|
|
if not base:
|
|
return
|
|
print("\nbaseline → current (Δ NDCG):")
|
|
for name, item in current.items():
|
|
old = base.get(name)
|
|
if not old:
|
|
continue
|
|
print(f"{name:28} {old['ndcg']:.3f} → {item['ndcg']:.3f} "
|
|
f"({item['ndcg'] - old['ndcg']:+.3f})")
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser(description="Evaluate recommendation ranking offline")
|
|
ap.add_argument("--db", default=db.DEFAULT_DB)
|
|
ap.add_argument("--limit", type=int, default=20)
|
|
ap.add_argument("--preset", action="append", help="preset name (repeatable)")
|
|
ap.add_argument("--implicit", action="store_true",
|
|
help="treat favorites and ratings >= 8 as relevant")
|
|
ap.add_argument("--save", help="write JSON snapshot")
|
|
ap.add_argument("--compare", help="compare with a JSON snapshot")
|
|
args = ap.parse_args()
|
|
|
|
con = db.connect(args.db)
|
|
db.init(con)
|
|
try:
|
|
results = evaluate(con, limit=args.limit, presets=args.preset,
|
|
implicit=args.implicit)
|
|
finally:
|
|
con.close()
|
|
|
|
print_results(results)
|
|
summary = aggregate(results)
|
|
print(f"aggregate: presets={summary['presets']} ndcg={summary['ndcg']:.3f} "
|
|
f"precision={summary['precision']:.3f} recall={summary['recall']:.3f}")
|
|
|
|
snapshot = {
|
|
"generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
|
"limit": args.limit,
|
|
"implicit": args.implicit,
|
|
"aggregate": summary,
|
|
"presets": results,
|
|
}
|
|
if args.save:
|
|
os.makedirs(os.path.dirname(os.path.abspath(args.save)), exist_ok=True)
|
|
with open(args.save, "w", encoding="utf-8") as fh:
|
|
json.dump(snapshot, fh, ensure_ascii=False, indent=2)
|
|
print(f"saved: {args.save}")
|
|
if args.compare:
|
|
with open(args.compare, encoding="utf-8") as fh:
|
|
baseline = json.load(fh)
|
|
compare(baseline, results)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|