Metadata-Version: 2.4
Name: mltreelib
Version: 0.4.1
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Rust
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: MacOS
Classifier: Operating System :: Microsoft :: Windows
Requires-Dist: pyarrow>=14
Requires-Dist: matplotlib>=3.8 ; extra == 'plotting'
Requires-Dist: pygraphviz>=1.11 ; extra == 'plotting'
Requires-Dist: seaborn>=0.13 ; extra == 'plotting'
Requires-Dist: optuna>=3.0 ; extra == 'tuning'
Provides-Extra: plotting
Provides-Extra: tuning
License-File: LICENSE
Summary: Tree-based machine learning: Rust core with Python and R frontends
Keywords: tree,decision-trees,causal-inference,uplift-modeling,model-trees,cubist,c50,interpretable-ml,rust
Home-Page: https://github.com/jkapila/mltreelib
Author: Jitin Kapila
License-Expression: Apache-2.0
Requires-Python: >=3.10
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Documentation, https://jkapila.github.io/mltreelib/
Project-URL: Homepage, https://github.com/jkapila/mltreelib
Project-URL: Issues, https://github.com/jkapila/mltreelib/issues
Project-URL: Repository, https://github.com/jkapila/mltreelib

# mltreelib — Machine Learning with Tree Based Library

[![CI](https://github.com/jkapila/mltreelib/actions/workflows/test.yaml/badge.svg)](https://github.com/jkapila/mltreelib/actions/workflows/test.yaml)
[![Docs](https://github.com/jkapila/mltreelib/actions/workflows/deploy.yaml/badge.svg)](https://jkapila.github.io/mltreelib/)
[![Version](https://img.shields.io/badge/version-0.3.0-informational)](Cargo.toml)
[![Python](https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12%20%7C%203.13%20%7C%203.14%20%7C%203.15-blue)](pyproject.toml)
[![Rust](https://img.shields.io/badge/rust-2021-orange.svg?logo=rust)](crates/mltreelib-core/)
[![License](https://img.shields.io/badge/license-Apache--2.0-green.svg)](LICENSE)
[![Zero Sklearn](https://img.shields.io/badge/dependencies-zero--sklearn-brightgreen)](#)
[![Missing Data](https://img.shields.io/badge/missing--data-first--class-blueviolet)](#)

Tree-based machine learning with a **Rust core** and thin **Python** (and, next, **R**) frontends. Evolved from the attempt to make the *right* kind of **Decision Trees**, after Hastie, Tibshirani, Friedman, Quinlan, Loh, Chaudhari.

The bet: tree/ensemble methods are under-studied relative to tabular foundation models, and the information hidden in **categorical, grouped and hierarchical structure** is exactly what flat learners lose. We build the classics properly in Rust (CART → C4.5 → C5.0 → Cubist → GritBot), measure them honestly on data where that structure matters, and only then mix and extend.

## Layout

```
crates/mltreelib-core/   Rust core: data layer, generator, metrics, the model tree
crates/mltreelib-py/     PyO3 bindings (the mltreelib Python surface)
python/mltreelib/        Python package: datasets loader + optional plots layer
examples/                runnable examples (all docs output comes from these)
docs/                    the documentation site (zensical; benchmarks + API + guides)
tests/                   Python behavior tests (the Rust seam lives in the core crate)
benchmarks/              the Elo field: prepared splits, scores, attempts, round manifests
specs/                   implementation specs (published as GitHub issues)
playground/              local marimo playground for edge-case hunting (not in git)
```

## Setup

Requires Rust and [uv](https://docs.astral.sh/uv/).

```sh
uv sync                        # .venv + builds the Rust extension (maturin)
uv run --with pandas --with pyarrow python examples/quickstart.py
```

Optional extras: `plotting` (matplotlib/pygraphviz/seaborn), `tuning` (optuna).

## The model tree today

Typed ingest — categoricals enter as **levels** (a distinct value is a level;
the split search partitions level sets), NAs route as-is, nothing is encoded
for the tree:

```python
from mltreelib import ModelTree, Metrics

m = ModelTree(
    max_depth=4, min_rows=10, leaf="linear",   # leaf: linear|mean|median|quantile|huber
    l2=0.1,                                    # ridge on leaf coefficients
    gain="sse",                                # regression: sse|friedman_mse|absolute_error|huber|poisson|sdr
                                               # class: entropy|gini|gain_ratio|twoing | callable
    split_precision=0.001,                     # candidate grid (None = exact scan)
    cat_order="frequency_desc", cat_search="cumulative",
    alpha=0.0, imbalance_penalty=0.0,          # grf-style split balance
    prune="none",                              # none|bic|mdl (+ cp family landing)
    split_test="none",                         # none|chow — significance-gated splitting
    split_alpha=0.05, bonferroni=False,        # gate level (+ selection correction)
    col_sample=None, seed=42,                  # per-node random column subset
    leaf_digest=True,                          # per-leaf t-digest: any tau post-fit
)
m.fit(x, y, dtypes=dtypes)      # dtypes per column: "numeric" | "categorical"
m.predict(xte)                  # NAs never block a prediction
m.quantile(x, 0.9)              # conditional quantiles from the leaf digests
m.training_log()                # candidate counts, dtype search, timings (verbose)
```

Growth knobs under active development (spec `#3`, all default-off until a
round measures them): `honesty`, NA **surrogate splits**, the pruning
family (cost-complexity / C5 pessimistic / cost-matrix),
`minsplit/minbucket/minprob`, EFB-style pre-selection, and an experimental
purity gate. Significance-gated splitting has **landed** (`split_test="chow"`
+ `split_alpha` + `bonferroni`: the scan's best split must beat the pooled
node model in a Chow F test, else the node stays a leaf). Distributional
leaves have landed for the first batch: `leaf_family="binomial"` (logit)
and `"poisson"` (log), `gain="deviance"`, and `predict_proba` /
`cdf` outputs (`examples/leaf_family.py`); probit, tobit, tweedie and
softmax remain spec `#4` follow-ups.

## Tree-based clustering & mixed search

Modular tree spine with pluggable split criteria, termination policies, and leaf prototypes:

- **TrieKNN**: Jitin Kapila (2018/2025) non-binary categorical prefix branching + leaf numerical KNN with hierarchical parent back-off for mixed-type tabular data.
- **Predictive Clustering Trees (PCT / CLUS)**: Multi-target variance reduction clustering with transparent rule extraction.
- **CLTree**: Bing Liu et al. (KDD 2000) decision tree clustering via analytical background non-data.
- **HDBSCAN Condensed Tree**: Mutual reachability MST, single-linkage dendrogram, condensed cluster hierarchy, Excess of Mass stability selection, and GLOSH outlier scores.
- **Unsupervised Random Forest (URF)**: Breiman/Shi-Horvath synthetic marginal scrambling, leaf proximity matrix $P(i, j)$, Lance-Williams average-linkage agglomerative clustering on $D = \sqrt{1 - P}$, and proximity outlier scores.

```python
from mltreelib import TrieKNN, PredictiveClusteringTree, CLTree, HDBSCAN, UnsupervisedRandomForest

# HDBSCAN density clustering & GLOSH outliers
hdb = HDBSCAN(min_cluster_size=20, min_samples=10)
hdb.fit(x)
labels = hdb.labels                 # None = noise / outlier
outliers = hdb.outlier_scores       # GLOSH score in [0, 1]
tree = hdb.condensed_tree()         # cluster birth, death, stability

# Unsupervised Random Forest proximity
urf = UnsupervisedRandomForest(n_trees=50, max_depth=6)
urf.fit(x, n_clusters=3)
prox = urf.proximity_matrix         # [N x N] leaf co-occurrence in [0, 1]
labels = urf.labels                 # agglomerative clusters on sqrt(1 - P)
```

## Base anomaly & density trees

High-throughput, explainable outlier detection algorithms implemented in pure Rust:

- **DensityEstimationTree (DET)**: Integrated Squared Error (ISE) density estimation and negative log-density scoring.
- **ExtendedIsolationTree (EIF)**: Oblique hyperplane cuts eliminating axis-aligned ghost artifacts + native categorical projection.
- **HalfSpaceTree (HST)**: High-speed streaming mass estimation and fixed-depth online updating.
- **RandomCutTree (RCT)**: Streaming tree computing Collusive Displacement (CoDisp) to catch tightly clustered / masked anomalies.
- **ActiveAnomalyTree (AAD)**: Human-in-the-loop active learning updating leaf importance weights from nominal/anomaly feedback.
- **ContextAnomalyTree (CAT)**: Sequential categorical transition tracking scoring temporal surprise in bits ($-\log_2 P$).
- **GritBot**: RuleQuest-style surprising condition-dependent subgroup anomaly mining with context preservation.

## Dataset component

The dataset component is the heart of the library: an adjustable benchmark
generator whose knobs control how much signal lives in categorical, grouped and
hierarchical structure, plus a data layer that takes any data in.

```python
from mltreelib import generate, IndexMapper, grouped_transform, summarize

g = generate(
    n_rows=10_000, n_numeric=5, cardinalities=[3, 8, 50, 200],
    hierarchy_levels=3, branching=[4, 10, 25],
    group_effect_strength=0.6, hierarchy_effect_strength=0.3,
    interaction_strength=0.2, noise=0.1, seed=42,
)
g["columns"]                 # num_*, cat_*, hier_* columns (None = NA)
g["target"]                  # regression target (labels for task="classification")
g["truth"]["variance"]       # realized variance share per component
g["truth"]["categorical_effects"]  # ground-truth level effects
```

Because the ground truth is known, every learner can be scored on *structure
recovery*, not just accuracy — including tail behavior (`tail_behavior="bathtub"`
reproduces the DAR bathtub edges) and missingness.

## Measuring: the Elo field

`benchmarks/` holds a living field comparing models across **Rust, Python, and R**:
- **Regression arena**: 18 datasets, 36 models (our `ModelTree` flavors; `rpart`, `ctree`, `lmtree`, `glmtree`, `cubist`, `grf`, `mboost`, `ranger`, `bart`, `fru`, `earth` in R; `LightGBM`, `CatBoost`, `CTBoost`, `ChimeraBoost`, `EBM`, `HistGradientBoosting`, `sklearn GBM`, `sklearn RF`, `ExtraTrees`, `sklearn Linear`, `KNN`, `MARS`, `statsmodels OLS/RLM/QuantReg`, `modeltrees lmtree` in Python; `forust` and `perpetual` in Rust), round-robin Elo on per-dataset RMSE.
- **Classification arena**: 24 TabArena datasets (20 binary, 4 multiclass), 28 models across Python, Rust, and R (including RuleQuest `C5.0 (tree)` and `C5.0 (rules)` in R, `HistGradientBoosting`, `sklearn GBM`, `LightGBM`, `CatBoost`, `CTBoost`, `ChimeraBoost`, `EBM`, `ranger`, `mboost`, `bart`, `glmtree`), round-robin Elo on per-dataset logloss. *(Note: ModelTree classification is under active development and will be attached once complete.)*

Every entry tracks language (`Rust`, `Python`, `R`) and categorical handling (`internal` native/as-is, `external` driver-encoded, `none` numeric-only). Fits run under a strict 300s process-group timeout with hard `SIGKILL` termination.

Runbook & experimentation guide: [benchmarks/README.md](benchmarks/README.md).
Docs: [API reference](https://jkapila.github.io/mltreelib/reference/api/),
[ELO board](https://jkapila.github.io/mltreelib/benchmarks/elo/),
[guides and examples](https://jkapila.github.io/mltreelib/examples/walkthrough/).

## Dependency policy

Lean but **pragmatic — no wheel reinvention**: fast data handling and fast
tree algorithms, with research on top. Scikit-learn stays out of the library
(API shape only, never imported); established packages earn their place where
they replace real complexity — `pyarrow` (parquet), `tdigest` (leaf quantiles),
`rayon` (parallel scans), `faer` (dense solves in the split hot path). The
field/benchmark tooling may use anything it measures (that is its job).

## Research inputs

Grounded research lives in `references/research/` (tracked; bulky clones of
the reference sources stay local): the
split-criteria survey, NGBoost leaf/training deep-dive, leaf-purity
literature review, and the knob-gap reviews against rpart/ctree/cubist/
partykit/grf. Specs are published as GitHub issues (`ready-for-agent`).

## Roadmap

1. [x] Data & feature layer (builder, encoders, transforms, generator, datasets loader)
2. [x] Model tree in Rust (typed ingest, criterion family, leaf kinds, quantiles,
      pruning (bic/mdl), balance knobs, budgets, training log)
3. [ ] **Model-tree capability knobs** (issue #3) — significance splits, honesty,
      NA surrogates, pruning family, minsplit/minbucket/minprob, EFB, purity gate
4. [ ] **Distributional leaves** (issue #4) — initial `leaf_family` batch:
      binomial/logit, Poisson/log, probit, tobit, tweedie, gamma; follow-up
      distributional stump leaves landed: softmax, survival, heteroscedastic
      with unified `predict(kind=...)`
5. [ ] **Forests & committees** — honesty + averaging (grf-lesson), Cubist-style
      committees + neighbor adjustment; the ensembles currently top the board
6. [ ] C5.0 rulesets + committees; GritBot surprising-subgroup mining
7. [ ] Mixing: LinearForest-style ensembles, sparse leaves (TRUST lineage)

Ground rule: **every knob is default-off until a measured round decides
otherwise** — the round manifests exist so that no number moves for free.

