Download src/axiom_effect/inference.py from liminalplanes/axiom-effect: direct link, hf CLI and curl.
- Browser
- Download file 26.6 kB
-
https://huggingface.co/liminalplanes/axiom-effect/resolve/main/src/axiom_effect/inference.py
- Command line
-
hf download hf://liminalplanes/axiom-effect/src/axiom_effect/inference.py
-
curl -L -o inference.py https://huggingface.co/liminalplanes/axiom-effect/resolve/main/src/axiom_effect/inference.py
26.6 kB
| """ | |
| The table-level call: AxiomEffect on a real table, in the data's own units. | |
| r = model.effect(df, treatment="price", outcome="sales") # no graph | |
| r = model.effect(df, "price", "sales", graph=[("age", "price"), ...]) # a DAG you trust | |
| r = model.effect(df, "price", "sales", graph=Axiom(...).discover(df)) # a discovered graph | |
| print(r) | |
| r.ate, r.att, r.cate, r.curve, r.debiased | |
| What the graph does: | |
| none every other column (or `covariates`) is taken as pre-treatment: none of them | |
| may be caused by the treatment. Their roles are unknown to the model. | |
| a DAG taken as true: the treatment's descendants (mediators, colliders, ...) are | |
| dropped, since adjusting for them biases the effect, and the model is told every | |
| remaining covariate's role (confounder, instrument, precision variable, noise). | |
| No directed path from the treatment to the outcome: every effect is exactly 0. | |
| discovered a discover() result from Axiom (axiom-discovery): its pair probabilities give each | |
| covariate's role probabilities (averaged over DAGs sampled from them), and the | |
| model reads them; nothing is dropped, since a discovered edge can be wrong. | |
| For large tables (more than TRAIN_N[1] rows), inference keeps memory small (< 1 GB) by | |
| partitioning the table into disjoint i.i.d. subsets of at most TRAIN_N[1] rows (stratified | |
| by treatment arm for binary treatments so every subset preserves prevalence) and combining | |
| their independent estimates. | |
| """ | |
| import warnings | |
| from dataclasses import dataclass, field | |
| from statistics import NormalDist | |
| import numpy as np | |
| from .graph import CONF, N_ROLES, ROLE_NAMES, descendants, discovered_roles, is_dag, roles | |
| from .model import MID, N_FEATURES, QUANTILES | |
| TRAIN_N = (128, 1536) # context rows; larger tables are split into strata of at most TRAIN_N[1] rows | |
| TRAIN_COVARIATES = 84 # covariates seen in training (network accepts any number natively) | |
| WIDE_N = TRAIN_N[1] # kept for compatibility with export_effect_hf / train_effect | |
| NARROW_COVARIATES = 34 | |
| MIN_LEVELS = 10 # a continuous treatment needs at least this many distinct values | |
| TRAIN_LEVELS = (0.02, 0.98) # continuous treatment values were asked about between these quantiles | |
| CURVE_LEVELS = (0.1, 0.25, 0.5, 0.75, 0.9) | |
| CONTRAST_LEVELS = (0.25, 0.75) | |
| E_CLIP = 0.01 # propensities clipped to [E_CLIP, 1 - E_CLIP] in the doubly robust estimate | |
| PROPENSITY_FOLDS, PROPENSITY_RIDGE = 5, 1.0 # cross-fitted logistic propensity | |
| Z90 = NormalDist().inv_cdf(0.95) | |
| class EffectResult: | |
| """Result of `effect`, in the outcome's units throughout. Quantiles are QUANTILES (5, 25, | |
| 50, 75, 95%): the median is the estimate, the outer pair a 90% interval, the inner 50%.""" | |
| treatment: str | |
| outcome: str | |
| binary: bool | |
| covariates: list # the columns adjusted for | |
| dropped: list # columns a DAG marked as the treatment's descendants | |
| graph: str # "none", "dag" or "discovered" | |
| contrast: tuple # (a, b): the treatment values of the headline effect | |
| quantiles: dict # estimand -> (len(QUANTILES),): "contrast", binary "att" / "atc" | |
| cate: np.ndarray # (n,) each row's effect of moving the treatment from a to b | |
| values: np.ndarray = None # continuous: the curve's treatment values | |
| reference: float = None # continuous: where the curve starts | |
| curve: np.ndarray = None # continuous: (K, len(QUANTILES)) effect of reference -> value | |
| propensity: np.ndarray = None # binary: (n,) P(treated | covariates), cross-fitted logistic | |
| debiased: dict = None # binary: {"ate"/"att": (estimate, lo, hi)}, AIPW, 90% | |
| roles: dict = field(default_factory=dict) # covariate -> role probabilities (ROLE_NAMES), with a graph | |
| zero_by_graph: bool = False | |
| n_rows: int = 0 | |
| n_subsets: int = 1 | |
| def estimate(self): | |
| return float(self.quantiles["contrast"][MID]) | |
| def interval(self): | |
| q = self.quantiles["contrast"] | |
| return float(q[0]), float(q[-1]) | |
| def interval50(self): | |
| q = self.quantiles["contrast"] | |
| return float(q[1]), float(q[-2]) | |
| def ate(self): | |
| """(estimate, lo, hi) of the average effect over all rows, 90%.""" | |
| q = self.quantiles["contrast"] | |
| return float(q[MID]), float(q[0]), float(q[-1]) | |
| def att(self): | |
| """Binary: (estimate, lo, hi) of the average effect on the treated, 90%.""" | |
| q = self.quantiles.get("att") | |
| return None if q is None else (float(q[MID]), float(q[0]), float(q[-1])) | |
| def to_frame(self): | |
| """The estimands (binary) or the dose-response curve (continuous), as a DataFrame.""" | |
| import pandas as pd | |
| if self.binary: | |
| return pd.DataFrame([{"estimand": k, **{f"q{int(p * 100)}": float(v) for p, v in zip(QUANTILES, q)}} | |
| for k, q in self.quantiles.items()]) | |
| return pd.DataFrame({self.treatment: self.values, **{f"q{int(p * 100)}": self.curve[:, k] | |
| for k, p in enumerate(QUANTILES)}}) | |
| def __repr__(self): | |
| g = lambda v: f"{v:.4g}" | |
| sig = lambda v: ("+" if v > 0 else "") + g(v) | |
| adj = ", ".join(self.covariates) or "nothing" | |
| rows = f"{self.n_rows} rows" + (f" in {self.n_subsets} strata" if self.n_subsets > 1 else "") | |
| head = [f"Effect of {self.treatment} on {self.outcome} ({rows}; graph: {self.graph}; adjusted for {adj})"] | |
| if self.dropped: | |
| head.append(f" not adjusted for (the graph says the treatment causes them): {', '.join(self.dropped)}") | |
| if self.zero_by_graph: | |
| return "\n".join(head + [f" 0: the graph has no directed path from {self.treatment} to {self.outcome}"]) | |
| iv = lambda q: f"{sig(q[MID])} 90% [{g(q[0])}, {g(q[-1])}] 50% [{g(q[1])}, {g(q[-2])}]" | |
| a, b = self.contrast | |
| if self.binary: | |
| lines = head + [f" ATE ({g(a)} -> {g(b)}): {iv(self.quantiles['contrast'])}", | |
| f" ATT (the treated): {iv(self.quantiles['att'])}", | |
| f" ATC (the controls): {iv(self.quantiles['atc'])}"] | |
| if self.debiased: | |
| lines += [f" doubly robust (AIPW, logistic propensity): ATE {sig(e)} [{g(lo)}, {g(hi)}], " | |
| f"ATT {sig(f)} [{g(flo)}, {g(fhi)}]" | |
| for (e, lo, hi), (f, flo, fhi) in [(self.debiased["ate"], self.debiased["att"])]] | |
| else: | |
| lines = head + [f" {self.treatment} {g(a)} -> {g(b)}: {iv(self.quantiles['contrast'])}", | |
| f" dose-response, from {self.treatment} = {g(self.reference)}:"] | |
| lines += [f" {g(v):>10s} {sig(q[MID])} 90% [{g(q[0])}, {g(q[-1])}]" | |
| for v, q in zip(self.values, self.curve)] | |
| lines.append(f" per-row effects (CATE): median {sig(np.median(self.cate))}, " | |
| f"10-90% {g(np.quantile(self.cate, 0.1))} to {g(np.quantile(self.cate, 0.9))}") | |
| return "\n".join(lines) | |
| def _table(data, names): | |
| """(n, d) float64 values and column names from a DataFrame or an array.""" | |
| if hasattr(data, "columns") and hasattr(data, "to_numpy"): | |
| names = list(map(str, data.columns)) if names is None else list(names) | |
| data = data.to_numpy(dtype=np.float64, na_value=np.nan) | |
| X = np.asarray(data, dtype=np.float64) | |
| if X.ndim != 2 or X.shape[1] < 2: | |
| raise ValueError(f"expected an (n, d) table with d >= 2, got shape {X.shape}") | |
| names = [f"X{k + 1}" for k in range(X.shape[1])] if names is None else list(map(str, names)) | |
| if len(names) != X.shape[1] or len(set(names)) != len(names): | |
| raise ValueError(f"need {X.shape[1]} distinct column names; got {names}") | |
| return X, names | |
| def _column(v, names, what): | |
| if isinstance(v, (int, np.integer)) and not isinstance(v, bool): | |
| if not 0 <= v < len(names): | |
| raise ValueError(f"{what} index {v} is out of range for {len(names)} columns") | |
| return int(v) | |
| if str(v) not in names: | |
| raise ValueError(f"{what} {v!r} is not a column; columns are {names}") | |
| return names.index(str(v)) | |
| def _reorder(M, graph_names, names): | |
| """A (d, d, ...) array over graph_names in the table's column order.""" | |
| graph_names = list(map(str, graph_names)) | |
| if sorted(graph_names) != sorted(names): | |
| raise ValueError(f"the graph's variables {graph_names} are not the table's columns {names}") | |
| p = [graph_names.index(name) for name in names] | |
| return np.asarray(M)[np.ix_(p, p)] | |
| def _is_discovered(graph): | |
| """Whether the graph is a discover() result (axiom's CausalGraph), read by its attributes.""" | |
| return hasattr(graph, "probs") and hasattr(graph, "names") | |
| def _adjacency(graph, names): | |
| """(d, d) 0/1 DAG in the table's column order from an edge list of (cause, effect) names, | |
| a (d, d) matrix or an adjacency DataFrame.""" | |
| d, index = len(names), {name: k for k, name in enumerate(names)} | |
| if hasattr(graph, "columns") and hasattr(graph, "index"): | |
| if list(map(str, graph.index)) != list(map(str, graph.columns)): | |
| raise ValueError("an adjacency DataFrame needs the same variables, in the same order, as index and columns") | |
| A = _reorder(graph.to_numpy(), graph.columns, names) | |
| elif isinstance(graph, (list, tuple)) and all( | |
| isinstance(e, (list, tuple)) and len(e) == 2 and all(isinstance(v, str) for v in e) for e in graph): | |
| A = np.zeros((d, d), dtype=np.int64) | |
| for a, b in graph: | |
| for v in (a, b): | |
| if v not in index: | |
| raise ValueError(f"edge ({a!r}, {b!r}): {v!r} is not a column; columns are {names}") | |
| A[index[a], index[b]] = 1 | |
| else: | |
| A = np.asarray(graph) | |
| if A.shape != (d, d): | |
| raise ValueError(f"a {d}-column table needs a ({d}, {d}) adjacency matrix; got shape {A.shape}") | |
| A = (np.asarray(A, dtype=float) != 0).astype(np.int64) | |
| if np.any(np.diag(A)): | |
| raise ValueError("the graph has a self-loop") | |
| if not is_dag(A): | |
| raise ValueError("the graph has a directed cycle; the effect model needs a DAG") | |
| return A | |
| def _standardize(v): | |
| mu, sd = v.mean(0), v.std(0) | |
| return (v - mu) / np.where(sd > 0, sd, 1.0), mu, np.where(sd > 0, sd, 1.0) | |
| def _combine(qs, counts): | |
| """Quantiles of one estimand from disjoint query strata: the count-weighted mean of the | |
| medians, and each quantile's distance from the median combined as for a mean of | |
| independent estimates, sqrt(sum (m_k d_k)^2) / sum m_k.""" | |
| qs, m = np.asarray(qs), np.asarray(counts, dtype=float) | |
| if len(qs) == 1: | |
| return qs[0] | |
| mid = (m * qs[:, MID]).sum() / m.sum() | |
| off = qs - qs[:, MID:MID + 1] | |
| return mid + np.sign(off.mean(0)) * np.sqrt(((m[:, None] * off) ** 2).sum(0)) / m.sum() | |
| def _disjoint_strata(T, binary, max_ctx, rng): | |
| """Partition `n` rows into disjoint i.i.d. subsets of at most `max_ctx` rows (stratified by | |
| treatment arm for binary treatments so every subset preserves prevalence). | |
| Returns [(rows, rows)].""" | |
| n = len(T) | |
| if n <= max_ctx: | |
| all_rows = np.arange(n) | |
| return [(all_rows, all_rows)] | |
| n_strata = -(-n // max_ctx) | |
| if binary: | |
| mid = (T.min() + T.max()) / 2 | |
| tr = rng.permutation(np.flatnonzero(T > mid)) | |
| ct = rng.permutation(np.flatnonzero(T <= mid)) | |
| parts = [np.concatenate([a, b]) for a, b in zip(np.array_split(tr, n_strata), np.array_split(ct, n_strata))] | |
| else: | |
| parts = np.array_split(rng.permutation(n), n_strata) | |
| return [(p, p) for p in parts] | |
| def _kmeans_clusters(Z, k, rng, iters=15): | |
| """Partition rows of `Z` (n, p) into up to `k` clusters via k-means++ and Lloyd iterations.""" | |
| n, p = Z.shape | |
| z_norm = (Z * Z).sum(1) | |
| centers = np.empty((k, p), dtype=Z.dtype) | |
| centers[0] = Z[rng.integers(n)] | |
| min_d2 = np.maximum(z_norm + float((centers[0] ** 2).sum()) - 2.0 * (Z @ centers[0]), 0.0) | |
| for j in range(1, k): | |
| total = float(min_d2.sum()) | |
| idx = int(rng.choice(n, p=min_d2 / total)) if total > 0.0 else int(rng.integers(n)) | |
| centers[j] = Z[idx] | |
| d2 = np.maximum(z_norm + float((centers[j] ** 2).sum()) - 2.0 * (Z @ centers[j]), 0.0) | |
| min_d2 = np.minimum(min_d2, d2) | |
| prev = None | |
| for _ in range(iters): | |
| c_norm = (centers * centers).sum(1) | |
| labels = (z_norm[:, None] + c_norm[None, :] - 2.0 * (Z @ centers.T)).argmin(1) | |
| if prev is not None and np.array_equal(labels, prev): | |
| break | |
| prev = labels | |
| for j in range(k): | |
| mask = labels == j | |
| if mask.any(): | |
| centers[j] = Z[mask].mean(0) | |
| return [np.flatnonzero(labels == j) for j in range(k) if (labels == j).any()] | |
| def _local_strata(C, T, binary, max_ctx, rng, global_frac=0.25): | |
| """Partition `n` rows into disjoint covariate-space query clusters and pair each cluster with | |
| a `max_ctx` context mixing `global_frac` globally stratified anchor rows (preserving full-table | |
| covariate support, scaling, and correlations) and `1 - global_frac` nearest neighbors (for | |
| local nonlinear / CATE resolution). Falls back to `_disjoint_strata` when `n <= max_ctx` or | |
| there are no varying covariates.""" | |
| n = len(T) | |
| if n <= max_ctx: | |
| all_rows = np.arange(n) | |
| return [(all_rows, all_rows)] | |
| if C.shape[1] == 0: | |
| return _disjoint_strata(T, binary, max_ctx, rng) | |
| sd = C.std(0) | |
| Z = np.clip((C - C.mean(0)) / np.where(sd > 0, sd, 1.0), -5.0, 5.0) | |
| if not np.any(Z): | |
| return _disjoint_strata(T, binary, max_ctx, rng) | |
| n_clusters = -(-n // max_ctx) | |
| clusters = _kmeans_clusters(Z, n_clusters, rng) | |
| z_norm = (Z * Z).sum(1) | |
| n_global = int(round(max_ctx * global_frac)) | |
| n_local = max_ctx - n_global | |
| if binary: | |
| mid = (T.min() + T.max()) / 2 | |
| tr = np.flatnonzero(T > mid) | |
| ct = np.flatnonzero(T <= mid) | |
| exp_n1 = int(round(max_ctx * len(tr) / n)) | |
| min_arm1 = min(len(tr), max(16, min(exp_n1, max_ctx // 10))) | |
| min_arm0 = min(len(ct), max(16, min(max_ctx - exp_n1, max_ctx // 10))) | |
| def _nearest(pool, d2_all, k): | |
| if k <= 0: | |
| return np.empty(0, dtype=np.int64) | |
| if k >= len(pool): | |
| return pool | |
| return pool[np.argpartition(d2_all[pool], k - 1)[:k]] | |
| strata = [] | |
| for q_rows in clusters: | |
| center = Z[q_rows].mean(0) | |
| d2 = z_norm + float((center ** 2).sum()) - 2.0 * (Z @ center) | |
| if n_global > 0: | |
| if binary: | |
| g1 = int(np.clip(round(n_global * len(tr) / n), min(len(tr), 1), min(len(tr), n_global - 1))) | |
| g0 = min(len(ct), n_global - g1) | |
| g1 = min(len(tr), n_global - g0) | |
| anchor = np.concatenate([rng.choice(tr, g1, replace=False), rng.choice(ct, g0, replace=False)]) | |
| else: | |
| anchor = rng.choice(n, n_global, replace=False) | |
| else: | |
| anchor = np.empty(0, dtype=np.int64) | |
| rem = np.ones(n, dtype=bool) | |
| rem[anchor] = False | |
| d2_rem = np.where(rem, d2, np.inf) | |
| nn = np.argpartition(d2_rem, n_local - 1)[:n_local] | |
| if binary: | |
| anchor_n1 = int((T[anchor] > mid).sum()) | |
| total_n1 = anchor_n1 + int((T[nn] > mid).sum()) | |
| total_n0 = max_ctx - total_n1 | |
| if total_n1 >= min_arm1 and total_n0 >= min_arm0: | |
| local = nn | |
| else: | |
| rem_tr, rem_ct = tr[rem[tr]], ct[rem[ct]] | |
| target_n1 = int(np.clip(total_n1, min_arm1, max_ctx - min_arm0)) | |
| need1 = int(np.clip(target_n1 - anchor_n1, 0, min(len(rem_tr), n_local))) | |
| need0 = min(len(rem_ct), n_local - need1) | |
| need1 = n_local - need0 | |
| local = np.concatenate([_nearest(rem_tr, d2, need1), _nearest(rem_ct, d2, need0)]) | |
| ctx_rows = np.concatenate([anchor, local]) | |
| else: | |
| ctx_rows = np.concatenate([anchor, nn]) | |
| if T[ctx_rows].std() < 1e-8: | |
| return _disjoint_strata(T, binary, max_ctx, rng) | |
| strata.append((q_rows, ctx_rows)) | |
| return strata | |
| def _logistic(X, t, ridge, iters=25): | |
| """Ridge-penalized logistic regression by Newton's method: weights (intercept first).""" | |
| A = np.column_stack([np.ones(len(X)), X]) | |
| P = ridge * np.eye(A.shape[1]) | |
| P[0, 0] = 0.0 | |
| w = np.zeros(A.shape[1]) | |
| for _ in range(iters): | |
| p = 1 / (1 + np.exp(-np.clip(A @ w, -30, 30))) | |
| g = A.T @ (p - t) + P @ w | |
| H = (A * (p * (1 - p))[:, None]).T @ A + P + 1e-9 * np.eye(A.shape[1]) | |
| step = np.linalg.solve(H, g) | |
| w -= step | |
| if np.abs(step).max() < 1e-8: | |
| break | |
| return w | |
| def _propensity(C, t, seed=0): | |
| """(n,) P(t = 1 | C), each row's from a logistic regression fitted on the other folds.""" | |
| n = len(t) | |
| X = (C - C.mean(0)) / np.where(C.std(0) > 0, C.std(0), 1.0) if C.shape[1] else np.zeros((n, 0)) | |
| folds = np.random.default_rng(seed).permutation(n) % min(PROPENSITY_FOLDS, n) | |
| e = np.empty(n) | |
| for f in np.unique(folds): | |
| fit, held = folds != f, folds == f | |
| if 0 < t[fit].mean() < 1: | |
| w = _logistic(X[fit], t[fit], PROPENSITY_RIDGE) | |
| e[held] = 1 / (1 + np.exp(-np.clip(w[0] + X[held] @ w[1:], -30, 30))) | |
| else: | |
| e[held] = t[fit].mean() | |
| return e | |
| def _aipw(mu0, mu1, e, T, Y): | |
| """Doubly robust ATE and ATT from per-row predictions, with 90% influence-function intervals.""" | |
| e = np.clip(e, E_CLIP, 1 - E_CLIP) | |
| psi = mu1 - mu0 + T * (Y - mu1) / e - (1 - T) * (Y - mu0) / (1 - e) | |
| ate, se = psi.mean(), psi.std() / np.sqrt(len(Y)) | |
| p = T.mean() | |
| att = (T * (Y - mu0) - (1 - T) * e / (1 - e) * (Y - mu0)).sum() / T.sum() | |
| phi = (T * (Y - mu0 - att) - (1 - T) * e / (1 - e) * (Y - mu0)) / p | |
| se_t = phi.std() / np.sqrt(len(Y)) | |
| return {"ate": (float(ate), float(ate - Z90 * se), float(ate + Z90 * se)), | |
| "att": (float(att), float(att - Z90 * se_t), float(att + Z90 * se_t))} | |
| def effect(model, data, treatment, outcome, graph=None, covariates=None, values=None, contrast=None, | |
| reference=None, names=None, extrapolate=False, discovery_samples=64, tta=1, seed=0): | |
| """The effect of setting `treatment` on `outcome` in a table (a DataFrame or an (n, d) | |
| array; `names` for an array's columns), given an optional graph: a DAG as an edge list of | |
| (cause, effect) names, a (d, d) matrix or an adjacency DataFrame, or a discover() result. | |
| `covariates`: the columns to adjust for (default: all others). `tta`: test-time | |
| augmentation passes (default 4; averages over random column tie-breaker codes with zero | |
| extra peak RAM). Returns an EffectResult.""" | |
| X, names = _table(data, names) | |
| t, y = _column(treatment, names, "treatment"), _column(outcome, names, "outcome") | |
| if t == y: | |
| raise ValueError("the treatment and the outcome are the same column") | |
| cov = [c for c in range(len(names)) if c not in (t, y)] if covariates is None else \ | |
| [_column(c, names, "covariate") for c in covariates] | |
| if t in cov or y in cov: | |
| raise ValueError("the covariates must not include the treatment or the outcome") | |
| kind, dropped, R, zero = "none", [], np.zeros((len(names), N_ROLES)), False | |
| if graph is not None and _is_discovered(graph): | |
| kind = "discovered" | |
| probs = _reorder(graph.probs, graph.names, names) | |
| R = discovered_roles(probs, t, y, discovery_samples, seed) | |
| if probs[t, y, CONF] > 0.2: | |
| warnings.warn(f"the discovered graph gives {names[t]} and {names[y]} a hidden common cause with " | |
| f"probability {probs[t, y, CONF]:.2f}: adjusting for measured covariates cannot remove " | |
| f"its bias", stacklevel=3) | |
| elif graph is not None: | |
| kind = "dag" | |
| A = _adjacency(graph, names) | |
| R = roles(A, t, y) | |
| zero = y not in descendants(A, t) | |
| dropped = [c for c in cov if R[c, 1] == 1] | |
| cov = [c for c in cov if R[c, 1] == 0] | |
| features = np.column_stack([np.full(len(cov), float(kind != "none")), R[cov]]).reshape(len(cov), N_FEATURES) | |
| used = [t, y] + cov | |
| if not np.isfinite(X[:, used]).all(): | |
| raise ValueError("missing or non-finite values in the treatment, the outcome or the covariates; " | |
| "drop or impute those rows first") | |
| n = len(X) | |
| if n < TRAIN_N[0]: | |
| warnings.warn(f"{n} rows is below the training range {TRAIN_N}", stacklevel=3) | |
| C = X[:, cov] | |
| if len(cov) > TRAIN_COVARIATES: | |
| warnings.warn(f"{len(cov)} covariates, more than in training (up to {TRAIN_COVARIATES})", stacklevel=3) | |
| T, Y = X[:, t], X[:, y] | |
| levels = np.unique(T) | |
| binary = len(levels) == 2 | |
| if not binary and len(levels) < MIN_LEVELS: | |
| raise ValueError(f"the treatment has {len(levels)} distinct values: binary (2) and continuous (at least " | |
| f"{MIN_LEVELS}) treatments are supported") | |
| if binary: | |
| vals = [float(levels[0]), float(levels[1])] | |
| a, b = vals | |
| curve_vals, ref = None, None | |
| else: | |
| lo, hi = np.quantile(T, TRAIN_LEVELS) | |
| a, b = contrast if contrast is not None else tuple(float(v) for v in np.quantile(T, CONTRAST_LEVELS)) | |
| curve_vals = np.asarray(values if values is not None else np.quantile(T, CURVE_LEVELS), dtype=np.float64) | |
| ref = float(np.median(T) if reference is None else reference) | |
| asked = np.concatenate([[a, b, ref], curve_vals]) | |
| outside = asked[(asked < lo) | (asked > hi)] | |
| if len(outside): | |
| msg = (f"treatment value(s) {sorted(set(outside.round(6)))} outside its 2-98% quantiles " | |
| f"[{lo:.4g}, {hi:.4g}]: the data hardly covers them") | |
| if not extrapolate: | |
| raise ValueError(msg + "; pass extrapolate=True to estimate anyway") | |
| warnings.warn(msg, stacklevel=3) | |
| vals = sorted(set(float(v) for v in asked)) | |
| k = {v: i for i, v in enumerate(vals)} | |
| rng = np.random.default_rng(seed) | |
| strata = _local_strata(C, T, binary, TRAIN_N[1], rng) | |
| est = {"contrast": [], "att": [], "atc": []} if binary else {"contrast": [], "curve": []} | |
| counts = {key: [] for key in est} | |
| cate, mu0, mu1 = np.empty(n), np.empty(n), np.empty(n) | |
| for idx_s, (q_rows, ctx_rows) in enumerate(strata): | |
| same = len(q_rows) == len(ctx_rows) and np.array_equal(q_rows, ctx_rows) | |
| self_idx = None | |
| if not same: | |
| pos = np.full(n, -1, dtype=np.int64) | |
| pos[ctx_rows] = np.arange(len(ctx_rows), dtype=np.int64) | |
| idx = pos[q_rows] | |
| if (idx >= 0).any(): | |
| self_idx = idx | |
| if cov: | |
| Wz_ctx, wm, ws = _standardize(C[ctx_rows]) | |
| Wz_qry = None if same else (C[q_rows] - wm) / ws | |
| else: | |
| Wz_ctx = np.zeros((len(ctx_rows), 0)) | |
| Wz_qry = None if same else np.zeros((len(q_rows), 0)) | |
| Tz_ctx, tm, ts = _standardize(T[ctx_rows]) | |
| Yz_ctx, ym, ys = _standardize(Y[ctx_rows]) | |
| vz = (np.array(vals) - tm) / ts | |
| all_q = np.ones(len(q_rows), dtype=bool) | |
| jobs = [(k[a], k[b], all_q, "contrast")] | |
| if binary: | |
| treated_q = T[q_rows] == levels[1] | |
| if treated_q.any(): | |
| jobs.append((k[a], k[b], treated_q, "att")) | |
| if (~treated_q).any(): | |
| jobs.append((k[a], k[b], ~treated_q, "atc")) | |
| else: | |
| jobs += [(k[ref], k[v], all_q, "curve") for v in curve_vals] | |
| out = model.predict(Wz_ctx, Tz_ctx, Yz_ctx, features, binary, vz, | |
| [(i, j, r) for i, j, r, _ in jobs], W_qry=Wz_qry, self_idx=self_idx, | |
| tta=tta, seed=seed + idx_s * 97) | |
| Q = out["quantiles"] * ys | |
| curve = [] | |
| for (_, _, r, name), q in zip(jobs, Q): | |
| if name == "curve": | |
| curve.append(q) | |
| else: | |
| est[name].append(q) | |
| counts[name].append(r.sum()) | |
| if curve: | |
| est["curve"].append(np.stack(curve)) | |
| counts["curve"].append(len(q_rows)) | |
| cate[q_rows] = (out["mu"][k[b]] - out["mu"][k[a]]) * ys | |
| if binary: | |
| mu0[q_rows], mu1[q_rows] = out["mu"][k[a]] * ys + ym, out["mu"][k[b]] * ys + ym | |
| quantiles = {name: _combine(est[name], counts[name]) for name in est if name != "curve" and est[name]} | |
| result = EffectResult(names[t], names[y], binary, [names[c] for c in cov], [names[c] for c in dropped], kind, | |
| (a, b), quantiles, cate, n_rows=n, n_subsets=len(strata), | |
| roles={names[c]: dict(zip(ROLE_NAMES, map(float, R[c]))) for c in cov} if kind != "none" else {}) | |
| if binary: | |
| treated = (T == levels[1]).astype(float) | |
| e = result.propensity = _propensity(C, treated, seed) | |
| result.debiased = _aipw(mu0, mu1, e, treated, Y) | |
| extreme = np.mean((e < 0.02) | (e > 0.98)) | |
| if extreme > 0.1: | |
| warnings.warn(f"{extreme:.0%} of rows have a predicted propensity outside 2-98%: poor overlap, the " | |
| f"estimates there rest on extrapolation", stacklevel=3) | |
| else: | |
| result.values, result.reference = curve_vals, ref | |
| C_arr = np.asarray(est["curve"]) # (strata, K, Q) | |
| result.curve = np.stack([_combine(C_arr[:, j], counts["curve"]) for j in range(C_arr.shape[1])]) | |
| result.curve[curve_vals == ref] = 0.0 | |
| if zero: | |
| warnings.warn(f"the graph has no directed path from {names[t]} to {names[y]}: every effect is exactly 0", | |
| stacklevel=3) | |
| result.zero_by_graph = True | |
| result.quantiles = {name: np.zeros(len(QUANTILES)) for name in result.quantiles} | |
| result.cate = np.zeros(n) | |
| if result.curve is not None: | |
| result.curve = np.zeros_like(result.curve) | |
| if result.debiased: | |
| result.debiased = {name: (0.0, 0.0, 0.0) for name in result.debiased} | |
| return result | |