1 """ 2 tree: regression or classification trees over a Tab. 3 (c) 2026, Tim Menzies <timm@ieee.org>, MIT license 4 Trimmed from ezr-py/xai.py. 5 6 `bins` yields candidate (cost, at, v) splits for one column; 7 cost is the size-weighted spread of the two halves. `tree` 8 recurses the min-cost cut (default: `bin`; or `binned`, faster 9 for class trees); nodes keep their rows, their y summary `ys` 10 and its `mid`. `leaf` routes a row down; `leaves` yields them 11 all; `walk` lists the nodes; `show` prints them. 12 """ 13 import random 14 from bisect import bisect_left 15 from math import log2 16 from .lib import o, isa 17 from .data import Sym, Num, add, adds, fold, mid 18 from .stats import xpect 19 20 def bins(tbl: o, rows: list, at: int, Y, accum, leaf=3): 21 "Yield (cost, at, v) bins; both sides hold at least leaf rows" 22 xy = [(r[at], Y(r)) for r in rows if r[at] != "?"] 23 n = len(xy) 24 tot = adds((y for _,y in xy), accum()) 25 if isa(tbl.cols[at], Sym): 26 for k in {x for x,_ in xy}: 27 ys = [y for x,y in xy if x==k] 28 if leaf <= len(ys) <= n - leaf: 29 here = adds(ys, accum()) 30 yield xpect(here, fold(tot, here, -1)), at, k 31 else: 32 xy.sort(); here = accum() 33 for j,(x,y) in enumerate(xy): 34 here = add(here, y) 35 if leaf <= j+1 <= n - leaf and x != xy[j+1][0]: 36 yield xpect(here, fold(tot, here, -1)), at, x 37 38 def bin(tbl: o, rows: list, Y, accum, leaf=3): 39 "The min-cost bin over every x column (None if no legal split)" 40 return min((b for at in tbl.x 41 for b in bins(tbl, rows, at, Y, accum, leaf)), 42 default=None, key=lambda b: b[:2]) # v may mix int,str 43 44 def has(w, col, v) -> bool: 45 "Does one cell fall on the yes-side of a bin? (? = yes)" 46 return w == "?" or (v == w if isa(col, Sym) else w <= v) 47 48 def tree(tbl: o, rows: list, Y, accum=Num, leaf=3, maxd=8, lvl=0, 49 cut=None) -> o: 50 """Recursively split rows on the min-cost cut; accum=Num|Sym. 51 cut(rows) -> (cost, at, v) or None; default: bin""" 52 cut = cut or (lambda rs: bin(tbl, rs, Y, accum, leaf)) 53 all = adds((Y(r) for r in rows), accum()) 54 t = o(at=None, v=None, ys=all, mid=mid(all), n=len(rows), rows=rows, 55 yes=None, no=None) 56 if len(rows) >= 2*leaf and lvl < maxd: 57 if b := cut(rows): 58 _, at, v = b 59 yes, no = [], [] 60 for r in rows: 61 (yes if has(r[at], tbl.cols[at], v) else no).append(r) 62 if yes and no: 63 t.at, t.v = at, v 64 t.yes = tree(tbl, yes, Y, accum, leaf, maxd, lvl+1, cut) 65 t.no = tree(tbl, no, Y, accum, leaf, maxd, lvl+1, cut) 66 return t 67 68 def node(tbl: o, t: o, row: list) -> o: 69 "Walk a row down to its leaf node" 70 while t.at is not None: 71 t = t.yes if has(row[t.at], tbl.cols[t.at], t.v) else t.no 72 return t 73 74 def leaf(tbl: o, t: o, row: list): 75 "The mid of a row's leaf" 76 return node(tbl, t, row).mid 77 78 def leaves(t: o): 79 if t.at is None: yield t 80 else: yield from leaves(t.yes); yield from leaves(t.no) 81 82 def walk(tbl: o, t: o, lvl=0, test=None): 83 "Yield (lvl, test, mid, n) per node, parents first; test = the cut here" 84 yield lvl, test, t.mid, t.n 85 if t.at is not None: 86 sym, at = isa(tbl.cols[t.at], Sym), tbl.names[t.at] 87 yield from walk(tbl, t.yes, lvl+1, f"{at} {'==' if sym else '<='} {t.v}") 88 yield from walk(tbl, t.no, lvl+1, f"{at} {'!=' if sym else '>'} {t.v}") 89 90 def show(tbl: o, t: o) -> None: 91 "One line per node: mid, n, then the cut that leads here" 92 for lvl, test, m, n in walk(tbl, t): 93 print("%6s %5s %s%s" % (m if isa(m, str) else round(m, 2), n, 94 "| " * lvl, test or "")) 95 96 #-- binned: class trees on rows coded once into bins -------------- 97 def ent(cs: list) -> float: 98 "Entropy of a list of counts" 99 n = sum(cs) 100 return -sum(c/n * log2(c/n) for c in cs if c) 101 102 def quantiles(rows: list, at: int, q: int) -> list: 103 "Up to q-1 equal-frequency edges of column at" 104 xs = sorted(r[at] for r in rows if r[at] != "?") 105 return sorted({xs[j*len(xs)//q] for j in range(1, q)}) if xs else [] 106 107 def binned(tbl: o, rows: list, Y, q=8, leaf=3, rf=False): 108 """A cut for class trees. Once: code each row as ints (per x, its 109 bin among q quantiles, or its sym value; -1 = ?), then its class. 110 Per call: count classes per bin, sweep, min entropy (x <= edge, 111 or sym == v). rf: just sqrt(#x) random cols per call""" 112 ks = {k: i for i, k in enumerate({Y(r) for r in rows})} 113 vals = {at: (sorted({r[at] for r in rows if r[at] != "?"}, key=str) 114 if isa(tbl.cols[at], Sym) else quantiles(rows, at, q)) 115 for at in tbl.x} 116 def idx(at, x): 117 if x == "?": return -1 118 if isa(tbl.cols[at], Sym): 119 return vals[at].index(x) if x in vals[at] else -1 120 return bisect_left(vals[at], x) 121 code = {id(r): [idx(at, r[at]) for at in tbl.x] + [ks[Y(r)]] for r in rows} 122 m = max(1, round(len(tbl.x) ** .5)) 123 def cut(rs): 124 best, cs = None, [code[id(r)] for r in rs] 125 for j in (sorted(random.sample(range(len(tbl.x)), m)) if rf 126 else range(len(tbl.x))): 127 at, sym = tbl.x[j], isa(tbl.cols[tbl.x[j]], Sym) 128 n, all = [[0]*len(ks) for _ in range(len(vals[at]) + 1)], [0]*len(ks) 129 for c in cs: 130 if c[j] >= 0: n[c[j]][c[-1]] += 1; all[c[-1]] += 1 131 yes = [0]*len(ks) 132 for b, v in enumerate(vals[at]): # bins: add up; syms: just b 133 yes = n[b] if sym else [y + k for y, k in zip(yes, n[b])] 134 no = [a - y for a, y in zip(all, yes)] 135 ny, nn = sum(yes), sum(no) 136 if min(ny, nn) >= leaf: 137 e = (ny*ent(yes) + nn*ent(no)) / (ny + nn) 138 if best is None or e < best[0]: best = (e, at, v) 139 return best 140 return cut 141