diff --git a/spatial/baselines.py b/spatial/baselines.py new file mode 100644 index 0000000..4cf35b2 --- /dev/null +++ b/spatial/baselines.py @@ -0,0 +1,72 @@ +"""Trivial baselines, per family. + +A model is only interesting relative to the cheapest rule that fits the training +set. The plan already says a model that answers "true" everywhere would look +fine on accuracy alone; the same is true of any one-bit rule, and if such a rule +fits every training family perfectly then accuracy on those families measures +nothing at all. + +Two numbers per family: + +* ``acc_all`` -- accuracy if the rule answers every row +* ``acc_dec`` -- accuracy restricted to rows whose observation decides the + answer, i.e. the same denominator the model's ``acc`` uses +""" +from __future__ import annotations + +import sys +from collections import Counter + +from . import generator + +ANSWERS = ("true", "false", "unknown") + + +def _rule(name: str, sc) -> str: + if name == "agree": # the label itself: ceiling for any rule + return sc.label.answer + if name == "true": + return "true" + if name == "false": + return "false" + if name == "unknown": + return "unknown" + if name == "edit": # one bit: an intervention happened -> false + return "false" if sc.query.edit else "true" + raise ValueError(name) + + +def score(family: str, rule: str, seed: int, n: int) -> dict: + rows = [generator.make(family, seed=seed, index=i) for i in range(n)] + all_hit = dec_hit = dec = 0 + for sc in rows: + pred = _rule(rule, sc) + all_hit += int(pred == sc.label.answer) + if sc.label.answer != "unknown": + dec += 1 + dec_hit += int(pred == sc.label.answer) + maj = Counter(sc.label.answer for sc in rows).most_common(1)[0] + return {"n": n, "acc_all": all_hit / n, "dec": dec, + "acc_dec": dec_hit / max(1, dec), "majority": maj[0], "maj_share": maj[1] / n} + + +def main(argv=None) -> int: + argv = argv or sys.argv[1:] + n = int(argv[0]) if argv else 128 + seed = 0 + rules = ("true", "false", "unknown", "edit") + head = f"{'family':11s} {'n':>4s} {'dec':>4s} {'maj':>8s} {'share':>5s} " + \ + " ".join(f"{r:>7s}" for r in rules) + print(head) + print("-" * len(head)) + for fam in generator.FAMILIES: + cells = [score(fam, r, seed, n) for r in rules] + s = cells[0] + print(f"{fam:11s} {s['n']:4d} {s['dec']:4d} {s['majority']:>8s} {s['maj_share']:5.2f} " + + " ".join(f"{c['acc_dec']:7.3f}" for c in cells)) + print(f"\nacc_dec = accuracy on rows the observation can decide (seed {seed}, n {n})") + return 0 + + +if __name__ == "__main__": + sys.exit(main())