"""tabUM on ordinary tables: split, predict in context, compare with fitted baselines, explain.""" from __future__ import annotations import time import numpy as np import pandas as pd from sklearn.compose import ColumnTransformer from sklearn.ensemble import HistGradientBoostingClassifier, HistGradientBoostingRegressor from sklearn.impute import SimpleImputer from sklearn.linear_model import LogisticRegression, Ridge from sklearn.metrics import accuracy_score, r2_score from sklearn.pipeline import make_pipeline from sklearn.preprocessing import OneHotEncoder, StandardScaler from tabum.inference.encoding import to_numeric def neighbors(m, X: np.ndarray, k: int): """The k training rows the classifier's retrieval head weighted most for each row of X (the votes it counted).""" import torch n = m._X.shape[0] x = torch.from_numpy(np.concatenate([m._X, np.asarray(X, np.float32)], 0)).unsqueeze(0).to(m.device) mask = torch.zeros(1, x.shape[1], dtype=torch.bool, device=m.device) mask[:, :n] = True y = torch.zeros(1, x.shape[1], dtype=torch.int64, device=m.device) y[:, :n] = torch.from_numpy(m._y_enc.astype(np.int64)) with torch.inference_mode(): emb = m.model.embed_rows(x, y, mask, n, "classification") w, idx = m.model.cls_head.top_neighbors(emb[:, n:], emb[:, :n], top_k=k) return idx[0].cpu().numpy(), w[0].float().cpu().numpy() def is_regression(y: pd.Series) -> bool: return pd.api.types.is_numeric_dtype(y) and y.nunique() > 20 def split(df: pd.DataFrame, target: str, n_train: int, n_test: int, seed: int = 0): df = df[df[target].notna()].reset_index(drop=True) rng = np.random.default_rng(seed) order = rng.permutation(len(df)) n_train = min(n_train, len(df) - min(n_test, len(df) // 4)) tr, te = order[:n_train], order[n_train:n_train + n_test] return df.iloc[tr].reset_index(drop=True), df.iloc[te].reset_index(drop=True) def encode(train: pd.DataFrame, others: list[pd.DataFrame], target: str): """Encode feature columns of train and other frames jointly, so category codes agree.""" feats = [c for c in train.columns if c != target] allx = pd.concat([train[feats]] + [o[feats] for o in others], ignore_index=True) for c in feats: if not pd.api.types.is_numeric_dtype(allx[c]): allx[c] = allx[c].astype("string") X = to_numeric(allx) cuts = np.cumsum([len(train)] + [len(o) for o in others]) return feats, np.split(X, cuts[:-1]) def _baselines(train: pd.DataFrame, test: pd.DataFrame, target: str, reg: bool) -> dict[str, float]: feats = [c for c in train.columns if c != target] num = [c for c in feats if pd.api.types.is_numeric_dtype(train[c])] cat = [c for c in feats if c not in num] Xtr, Xte = train[feats].copy(), test[feats].copy() for c in cat: Xtr[c], Xte[c] = Xtr[c].astype(str), Xte[c].astype(str) lin_pre = ColumnTransformer([("n", make_pipeline(SimpleImputer(), StandardScaler()), num), ("c", OneHotEncoder(handle_unknown="ignore"), cat)]) ytr, yte = train[target], test[target] out = {} lin = make_pipeline(lin_pre, Ridge() if reg else LogisticRegression(max_iter=2000)) out["linear"] = _score(lin.fit(Xtr, ytr if reg else ytr.astype(str)).predict(Xte), yte, reg) codes_tr, codes_te = Xtr.copy(), Xte.copy() for c in cat: cats = pd.Categorical(pd.concat([Xtr[c], Xte[c]])).categories codes_tr[c] = pd.Categorical(Xtr[c], categories=cats).codes codes_te[c] = pd.Categorical(Xte[c], categories=cats).codes mask = [c in cat for c in feats] gb = (HistGradientBoostingRegressor if reg else HistGradientBoostingClassifier)( categorical_features=mask if any(mask) else None, random_state=0, early_stopping=False) out["boosting"] = _score(gb.fit(codes_tr, ytr if reg else ytr.astype(str)).predict(codes_te), yte, reg) return out def _score(pred, y, reg: bool) -> float: if reg: return float(r2_score(np.asarray(y, float), np.asarray(pred, float))) return float(accuracy_score(np.asarray(y).astype(str), np.asarray(pred).astype(str))) def run(make_clf, make_reg, df: pd.DataFrame, target: str, n_train: int, n_test: int, extra: pd.DataFrame | None = None, baselines: bool = True, importances: bool = True) -> dict: reg = is_regression(df[target]) train, test = split(df, target, n_train, n_test) others = [test] + ([extra] if extra is not None else []) feats, (Xtr, Xte, *rest) = encode(train, others, target) t = time.time() if reg: m = make_reg().fit(Xtr, train[target].to_numpy(float)) o = m._out(Xte) pred = m.model.predict_mean(o)[0].float().cpu().numpy() lo = m.model.predict_quantile(o, 0.1)[0].float().cpu().numpy() hi = m.model.predict_quantile(o, 0.9)[0].float().cpu().numpy() res = {"pred": pred, "lo": lo, "hi": hi, "score": _score(pred, test[target], True)} else: m = make_clf().fit(Xtr, train[target].astype(str).to_numpy()) proba = m.predict_proba(Xte) pred = m.classes_[proba.argmax(1)] res = {"proba": proba, "classes": list(m.classes_), "pred": pred, "score": _score(pred, test[target], False)} res["seconds"] = time.time() - t if importances: imp = m.feature_importances(Xte[: min(200, len(Xte))]) res["importances"] = dict(sorted(zip(feats, map(float, imp)), key=lambda kv: -kv[1])) if extra is not None: Xe = rest[0] if reg: o = m._out(Xe) res["extra"] = {"pred": float(m.model.predict_mean(o)[0][0]), "lo": float(m.model.predict_quantile(o, 0.1)[0][0]), "hi": float(m.model.predict_quantile(o, 0.9)[0][0])} else: idx, w = neighbors(m, Xe, 5) res["extra"] = {"proba": m.predict_proba(Xe)[0], "neighbors": idx[0], "weights": w[0]} if baselines: res["baselines"] = _baselines(train, test, target, reg) res.update(reg=reg, train=train, test=test, target=target, features=feats) return res