API reference — ModelTree¶
The model tree: typed fit, split-search knobs, quantiles, training log. Guide: Model.
ModelTree¶
pythonclass ModelTree((max_depth=6, min_rows=15, minsplit=None, minbucket=None, minprob=0.02, max_leaf_nodes=None, min_gain=1e-09, purity_gate=None, purity_gate_metric='sd', tail_quantile=None, gain=None, split_precision=Ellipsis, split_cols=None, col_sample=None, seed=42, leaf='linear', tau=0.5, l1=0.0, l2=0.5, leaf_cols='all', leaf_digest=True, cat_order=None, cat_search='cumulative', monotone=Ellipsis, tree_monotone=None, leaf_monotone=None, col_weights=None, interaction_groups=None, alpha=0.0, imbalance_penalty=0.0, prune='cp', cp_alpha=5.0, honesty=False, honesty_fraction=0.5, maxsurrogate=0, split_test='none', split_alpha=0.05, bonferroni=False, preselect='none', min_relevance=None, verbose=0, leaf_family='gaussian', leaf_solver='lbfgs', split_eval='fast', presort=False, events=None, treatments=None, train_groups=True, train_ids=False, n_classes=None, tweedie_p=1.5, tobit_threshold=0.0, mars_degree=1, mars_terms=10, mars_penalty=2.0, knn_k=5, knn_k_validity=5, knn_variant='uniform', knn_metric='euclidean', knn_gamma=None, knn_p=2.0, shrinkage=0.0, max_classes=256, leaf_na_policy='drop_fallback', preset=None, control=None, leaf_control=None, mmd_kernel=None, mmd_bandwidth=None, fairness_penalty=None, protected_col=None, fairness_metric=None, sporf_d=0, sporf_projections=10, extratrees=False, ebm_fast=False, target_cause=1, aft_dist='weibull', cure_fraction=None, spline_knots=3))
Model tree: greedy splits with Gaussian, binomial-logit or Poisson-log
leaves, NA-aware (learned split directions + NA-indicator leaf terms).
Task: regression, binary probability estimation, or count modeling.
ModelTree.apply¶
pythonapply((self, /, x))
Return the leaf ID (0..n_leaves-1) for each input row.
Args: x: raw rows of predictors.
Returns: one integer leaf ID per row.
ModelTree.break_down¶
pythonbreak_down((self, /, row))
DALEX-style break-down of one response-scale prediction.
Args:
row: one row of predictors (None = missing). Accepts mixed numeric and categorical strings.
Returns: {"baseline", "steps": [[column_name, contribution], ...],
"residual", "prediction"}; baseline + steps + residual == prediction.
ModelTree.cdf¶
pythoncdf((self, /, x, value))
Fitted binomial/Poisson CDF P(Y <= value), conditional on each row.
Args: x: raw rows of predictors, with the same missing/level handling as predict. value: response threshold; discrete CDFs use its integer floor.
Returns: one fitted-distribution probability per row. Unlike quantile, this uses the fitted family, not the empirical target t-digest.
Raises: ValueError for Gaussian leaves or an invalid threshold.
ModelTree.extract_rules¶
pythonextract_rules((self, /, x=None, y=None, prune=True, cf=0.25))
Extract a C5.0-style rule set from this fitted tree.
ModelTree.fast_interactions¶
pythonfast_interactions((self, /))
Returns list of detected pairwise feature interactions from EBM FAST screening.
ModelTree.feature_importance¶
pythonfeature_importance((self, /, method='gain', x=None, y=None, metric=None, n_repeats=None, seed=None))
Feature importance — supports "gain" (default, rpart split gain share),
"shapley" (mean absolute TreeSHAP over rows), or "permutation" (score degradation).
ModelTree.fit¶
pythonfit((self, /, x, y, w=None, dtypes=None, control=None, id_col=None, group_col=None, col_names=None, event=None, treatment=None, n_classes=None, sample_weight=None, row_weights=None, col_weights=None, feature_weights=None, train_groups=None, train_ids=None, fairness_penalty=None, protected_col=None, protected_attribute=None, fairness_metric=None, sporf_d=None, sporf_projections=None, extratrees=None, ebm_fast=None))
Fit the tree on row-major data using the selected leaf family.
Args:
x: rows of predictors; None entries are missing (NA rows train).
y: targets; None/NaN drops that row for binomial/Poisson.
Gaussian NaN handling follows the historical Gaussian path.
Binomial targets are 0 or 1; Poisson targets are finite
nonnegative counts or rates (including fractional values).
Gaussian targets retain ordinary regression.
w: optional per-row sample weights (row weightage); zero-weight
rows are ignored.
dtypes: optional per-column types — "numeric" (default) or
"categorical" (values are level codes; the split search
partitions levels, no encoding).
Returns: nothing; the fitted tree replaces the inner model.
ModelTree.get_params¶
pythonget_params((self, /, deep=True))
Return all hyperparameter values as a dict (scikit-learn compatible).
ModelTree.leaf_samples¶
pythonleaf_samples((self, /, x, id_col=None, col_names=None))
Return row indices or entity IDs grouped by leaf ID: {leaf_id: [indices_or_ids]}.
Args: x: raw rows of predictors. id_col: optional column name, column index, or list of IDs. If None (default), returns integer row indices [0, 1, ...]. If provided, returns the corresponding entity ID values. col_names: optional data column names when x has different layout than training data.
Returns: dict mapping integer leaf_id to a list of row indices or entity IDs.
ModelTree.leaf_stats¶
pythonleaf_stats((self, /))
Return the list of 0D stats dictionaries for all leaves.
ModelTree.leaf_summary¶
pythonleaf_summary((self, /, leaf_id))
Format a leaf's regression model as an R summary(lm) / Python statsmodels table.
ModelTree.leaves¶
pythonleaves((self, /))
Fitted leaf models with their empirical target distribution stats.
Args: none.
Returns: one dict per leaf with cols, coef, na_coef,
intercept, response_constant, n, mean, std, min, max,
quantiles.
Linear coef, na_coef, and intercept use the family's link scale
(identity, logit, or log); mean and other stats describe raw targets.
Constant leaves have no link-scale coefficient vector: intercept
is None, while response_constant is the response-scale constant.
ModelTree.n_leaves¶
pythonn_leaves((self, /))
Number of leaves.
Args: none.
Returns: leaf count.
ModelTree.permutation_importance¶
pythonpermutation_importance((self, /, x, y, metric='rmse', n_repeats=5, seed=42))
Permutation feature importance: per-column validation loss degradation
when the column is shuffled across rows.
ModelTree.predict¶
pythonpredict((self, /, x, kind='response', times=None, neighbors=None, cause=None))
Predict with flexible output kinds:
kind="response" (default): expected value / class / median survival time.
kind="proba": class probabilities ((N, C) matrix for Softmax, 1D float list for Binomial/Probit).
kind="dist": (mean, std) location-scale tuples for Heteroscedastic.
kind="survival": S(t) survival curve over times grid.
kind="hazard": Lambda(t) cumulative hazard curve over times grid.
kind="cif": F_c(t) cumulative incidence function for cause over times grid.
kind="risk": predicted risk score (higher score = shorter expected survival / higher risk).
kind="leaf_id": integer leaf ID per row.
ModelTree.predict_adjusted¶
pythonpredict_adjusted((self, /, x, neighbors=5))
Predict with Cubist-style k-NN sample neighbor adjustment.
ModelTree.predict_interval¶
pythonpredict_interval((self, /, x, coverage=0.9))
Empirical prediction interval (lower, upper) per row at the requested coverage.
Args: x: raw rows of predictors. coverage: coverage probability in (0, 1) (default 0.90 for a 90% interval).
Returns: list of (lower, upper) tuples.
ModelTree.predict_label¶
pythonpredict_label((self, /, x, threshold=0.5))
Hard binary class labels (0 or 1), one label per input row.
Args: x: raw rows of predictors. threshold: probability threshold (default 0.5).
Returns: one integer label (0 or 1) per row.
Raises: ValueError unless the fitted leaf family is binomial.
ModelTree.predict_proba¶
pythonpredict_proba((self, /, x))
Predict class probabilities (convenience alias for predict(x, kind="proba")).
ModelTree.predict_vector¶
pythonpredict_vector((self, /, x))
Predict multi-dimensional vector targets for row-major x (when trained on vector targets).
ModelTree.profile¶
pythonprofile((self, /))
Per-level timing profile (group/sort, scan, leaf fit).
Args: none.
Returns: one dict per depth level with depth, nodes, rows,
cols, candidates, group_ns, scan_ns, leaf_ns.
ModelTree.quantile¶
pythonquantile((self, /, x, tau))
Empirical conditional target quantiles from the leaves' t-digests:
any tau in [0, 1] after fitting. These are not quantiles of the fitted
binomial/Poisson distribution; use cdf for that distribution's CDF.
Args: x: rows of predictors (NA never blocks). tau: quantile level.
Returns: one quantile per row (NaN when a leaf's digest was dropped).
ModelTree.retrain¶
pythonretrain((self, /, x, y, control=None, w=None, mode='internal', leaf_features=None, retrain_cols=None, col_names=None, leaf=None, leaf_family=None, leaf_cols=None, l1=None, l2=None, leaf_digest=None, tau=None, event=None, n_classes=None))
Retrain all leaf models on new or existing data without altering tree topology or splits.
Args:
x: rows of predictors; None entries are missing.
y: targets.
control: optional LeafControl instance or dict.
w: optional sample weights.
mode: "internal" (updates self in place and returns self) or "external" (returns new ModelTree clone).
leaf_features: optional subset of column indices or names for leaf models.
retrain_cols: alias for leaf_features.
col_names: optional data column names to validate and remap splits.
leaf: optional leaf kind override ("linear", "mean", "median", "quantile", "huber").
leaf_family: optional leaf distribution override ("gaussian", "binomial", "poisson").
leaf_cols: optional leaf columns policy override ("all", "path_used").
l1: optional lasso penalty override.
l2: optional ridge penalty override.
leaf_digest: optional bool whether to keep leaf t-digests.
tau: optional quantile tau when leaf is "quantile" (default 0.5).
Returns: updated ModelTree (self for internal mode, or new ModelTree for external mode).
ModelTree.root_split¶
pythonroot_split((self, /))
Root node split, if the tree split at the root.
ModelTree.shapley¶
pythonshapley((self, /, row))
Exact TreeSHAP feature attributions for a single row prediction:
efficiency invariant: base_value + \sum values == prediction.
ModelTree.split_diagnostics¶
pythonsplit_diagnostics((self, /))
Statistical split diagnostics per node (MOB / Chow / CTree hypothesis tests).
Returns a list of dicts with test name, statistic, p-value, alpha,
passed flag, and per-variable test results.
ModelTree.split_paths¶
pythonsplit_paths((self, /))
Split columns along each root-to-leaf path.
Args: none.
Returns: one list of column names per root-to-leaf path (the split columns on that path) — the introspection behind interaction-group checking.
ModelTree.splits¶
pythonsplits((self, /))
Learned splits.
Args: none.
Returns: one dict per split with col, threshold, missing_left,
gain (goodness of split).
ModelTree.summary¶
pythonsummary((self, /))
Print comprehensive summary of all leaf models across the tree.
ModelTree.to_dot¶
pythonto_dot((self, /))
Graphviz DOT for the tree (render with pygraphviz/graphviz — layout is
graphviz's job):
pgv.AGraph(string=model.to_dot()).draw("tree.svg", prog="dot").
ModelTree.training_log¶
pythontraining_log((self, /))
The training log (populated when verbose > 0): scan config, per
depth/per node candidate counts, precision grid, timings.
Args: none.
Returns: log lines.
LeafControl¶
pythonclass LeafControl((leaf='linear', leaf_family='gaussian', leaf_solver='irls', leaf_cols='all', l1=0.0, l2=0.001, leaf_digest=True, tau=0.5, leaf_features=None, leaf_monotone=None, monotone=None, mars_degree=1, mars_terms=10, mars_penalty=2.0, tweedie_p=1.5, tobit_threshold=0.0, knn_k=5, knn_k_validity=5, knn_variant='uniform', knn_metric='euclidean', knn_gamma=None, knn_p=2.0, events=None, treatments=None, n_classes=None, shrinkage=0.0, max_classes=256, leaf_na_policy='drop_fallback', aft_dist='weibull', cure_fraction=None, spline_knots=3))
Parameter controls for fitting leaf models independently of tree topology.
LeafControl.with_params¶
pythonwith_params((self, /, leaf=None, leaf_family=None, leaf_cols=None, l1=None, l2=None, leaf_digest=None, tau=None, leaf_features=None, leaf_monotone=None, mars_degree=None, mars_terms=None, mars_penalty=None, tweedie_p=None, tobit_threshold=None))