datalets 🧩
Partition-then-fit machine learning, scikit-learn compatible.
Many tiles, one picture. Cluster your data into datalets, run a model tournament per datalet, route every prediction to the right specialist.
Real-world datasets rarely follow one pattern. A single global model fits the average of all the patterns in your data — datalets instead discovers the subpopulations (unsupervised, on X only), crowns the best classifier for each one, and routes every prediction to the specialist that owns it.
┌──────────────┐
X ─────► │ clusterer │────► datalet 1 ──► tournament ──► 🏆 XGBoost (t=0.31)
│ (any of 12) │────► datalet 2 ──► tournament ──► 🏆 LogReg (t=0.55)
└──────────────┘────► datalet 3 ──► tournament ──► 🏆 RandomForest (t=0.48)
too small ──────────────────► global fallback
Install
pip install datalets # core (scikit-learn models only)
pip install "datalets[boosters]" # + XGBoost, LightGBM, CatBoost
pip install -e ".[dev]" # from a clone, for development
Named after the data slices it carves — and pip install datalets,
import datalets: one name everywhere.
Quickstart
from datalets import PartitionedClassifier
model = PartitionedClassifier(
clusterer="auto", # searches kmeans/gmm x k (up to 12) + hdbscan,
# scored by predictive utility — fully automatic;
# or a list like ["kmeans", "gmm"] to pick
# which algorithms compete (skip slow ones)
candidates="default", # or "fast", "all", or your own list of classifiers
class_weight="balanced", # automated imbalance handling (weights, no resampling)
routing="soft", # blend specialists by P(cluster | x)
)
model.fit(X_train, y_train) # no cluster tags needed — the partition is discovered
model.predict(X_test) # routed to each point's specialist
model.predict_cluster(X_test) # which datalet does each point belong to?
print(model.auto_search_) # every partition tried, scored + silhouette/BIC
print(model.report()) # per-cluster: size, base rate, champion, lift
print(model.summary()) # verdict: does the partition earn its keep?
print(model.tree()) # the finish tree: the whole fit, one picture
Prefer manual control? clusterer="kmeans", n_clusters=6 (or "gmm",
"hdbscan", … or any clusterer instance) pins the partition yourself.
fit narrates itself: numbered stages, a live progress bar over every
(tournament, candidate) pair in interactive sessions, and the finish
tree at the end — how the data was carved up, the clustering quality
(sampled silhouette), which champion serves each segment at what threshold,
which algorithms dominated, and the verdict:
datalets · PartitionedClassifier · fit in 3.4s
├─ data 1,200 rows × 5 features · 2 classes · positives 42.3%
├─ clustering kmeans → 3 clusters · silhouette 0.29 · sizes 398–402 (median 400)
├─ tournament 4 slices × 2 candidates · metric f1 · 8 CV races
├─ segments
│ ├─ cluster 0 · n=402 (34%) · pos 45.0% → ★ logistic_regression · f1 0.850 · thr 0.47 · lift +0.018
│ ├─ cluster 1 · n=400 (33%) · pos 45.8% → ★ decision_tree · f1 0.667 · thr 0.02 · lift +0.002
│ └─ cluster 2 · n=398 (33%) · pos 36.2% → ★ logistic_regression · f1 0.923 · thr 0.43 · lift +0.085
├─ fallback decision_tree · f1 0.772 · safety net only
├─ champions logistic_regression ×2 · decision_tree ×1
└─ verdict ✓ partition earns its keep · routed OOF f1 0.803 vs global 0.772 · lift +0.0311
Non-interactive runs (logs, CI, servers) are never silent on long fits:
throttled per-task completion lines plus a heartbeat that names the task
currently blocking (⏳ still working · 96/104 done · waiting on global · random_forest). progress=False or DATALETS_QUIET=1
silences everything.
What you get
- Clusterer zoo — all 12 scikit-learn clustering families by name
(
kmeans,minibatch_kmeans,bisecting_kmeans,gmm,bayesian_gmm,birch,agglomerative,spectral,hdbscan,dbscan,meanshift,optics), or bring your own instance. - Universal routing — clusterers that cannot label new points (Agglomerative, Spectral, DBSCAN, HDBSCAN, OPTICS) are made inductive with a KNN gate. DBSCAN/HDBSCAN noise points are served by the global model.
- Model tournament per cluster — every candidate is scored with stratified out-of-fold CV inside the cluster; a one-standard-error rule breaks ties toward the simpler model. Candidate zoo spans scikit-learn's classifiers plus XGBoost / LightGBM / CatBoost when installed.
- Per-cluster decision thresholds — clusters with different positive rates want different cutoffs; datalets tunes each cluster's threshold for your metric (F1 by default). This alone often lifts F1 on heterogeneous data.
- Imbalance handled, two automated modes — thresholds alone are the
F1-first mode;
class_weight="balanced"adds inverse-frequency weights through fitting, thresholds and scoring (no resampling) for the recall-first mode: on a 0.4%-positive benchmark it catches 97% of positives with better ranking (ROC-AUC 0.999) than tuned boosters. - Soft routing — predictions blend all specialists by P(cluster | x), so
nothing jumps discontinuously at cluster boundaries.
routing="hard"if you want one specialist per point. - Global safety net — a tournament-selected global model serves clusters that are too small, too class-starved, or labelled as noise.
- The honesty report —
report()shows, per cluster, whether the specialist actually beats the global model on the same rows, andsummary()gives a verdict. If the partition doesn't earn its keep, datalets says so instead of letting you ship it. - A fit you can watch — stage-by-stage narration with a live progress
bar, and
tree(): the post-fit finish tree showing the partition, the clustering quality, every segment's champion and the final verdict at a glance. - Temporal and grouped data —
cvaccepts any sklearn splitter (TimeSeriesSplit,StratifiedGroupKFold, …) or an explicit list of(train, test)folds, andfit(groups=...)keeps entity leakage out of every tournament; an integercvcombined withgroupsupgrades to a group-aware splitter automatically. - Operating-point objectives — deploy on the constraint your
stakeholders speak:
threshold_objective=("recall_at_precision", 0.8),("precision_at_recall", ...),("cost", {"fp": 1, "fn": 5}), or("flag_rate", 0.02)(rank-based, exact per batch). - Missing values as a policy —
missing="median"or"sentinel"(for NaNs that mean something), applied once to the single view every component sees, at fit and serve time alike. - Preemption-proof fits —
checkpoint_dir=...caches every (slice, candidate) scoring under content-hash keys; a killed 30-hour fit resumes instead of restarting.estimate_cost(X, y)prints the wall-time plan before anything expensive runs. - MLflow flavor —
pip install "datalets[mlflow]": save/log/load via pyfunc with the report, finish tree and segment narratives logged as artifacts. - Multi-scale ensembles —
DataletEnsembleClassifier/Regressorfit one model per partition scale (k=3, 5, 8, …) and blend the votes — the configuration the cluster-then-predict literature found strongest.
Is the partition real? Prove it.
The in-fit report reuses training folds, so treat it as a screen. For a leakage-free comparison, everything (clustering, tournaments, thresholds) is refit inside every fold:
from datalets import honest_cv
print(honest_cv(X, y, datalets=PartitionedClassifier(n_clusters=6, random_state=0)))
# f1_mean f1_std roc_auc_mean ...
# datalets 0.912 0.011 0.965
# tournament_global 0.887 0.014 0.951
# hist_gradient_boosting 0.879 0.012 0.949
TournamentClassifier (the model-selection engine without clustering) is
also exported — it is both the library's global fallback and the honest
single-model baseline.
Regression too
PartitionedRegressor is the continuous-target twin: same clusterer zoo,
same per-datalet tournaments (over a regressor zoo: Ridge/Lasso, KNN,
forests, boosters, SVR, MLP + XGBoost/LightGBM/CatBoost), same soft/hard
routing and honesty report — no thresholds, since there is nothing to
threshold. selection_metric is one of "r2" (default), "mse",
"rmse", "mae".
from datalets import PartitionedRegressor, honest_cv_regression
reg = PartitionedRegressor(n_clusters=6, candidates="default").fit(X_train, y_train)
print(reg.report()) # per-cluster: champion, cv_score, lift
print(honest_cv_regression(X, y, datalets=reg))
When does datalets help?
Partition-then-fit wins when your data genuinely contains subpopulations with different X→y rules — customer segments, operating regimes, sensor types, geographies. It will not beat a tuned gradient booster on homogeneous data (boosters already partition internally); the report will tell you when that is the case. What you always keep, even at parity: interpretable segments, one readable specialist per segment, and per-segment thresholds and diagnostics.
sklearn-compatible, for real
All six estimators pass scikit-learn's check_estimator suite —
TournamentClassifier, TournamentRegressor and PartitionedRegressor
with no exemptions at all; the partition classifiers carry a handful
of documented exemptions rooted in two deliberate design decisions (the
decision rule is a tuned threshold, not argmax — the same exemption
scikit-learn grants its own TunedThresholdClassifierCV — and the
X-only clustering is unweighted by design). Pipelines, GridSearchCV,
cross_val_score, sample_weight, cloning and pickling all work:
from sklearn.model_selection import GridSearchCV
GridSearchCV(
PartitionedClassifier(),
{"n_clusters": [4, 6, 8], "clusterer": ["kmeans", "gmm"]},
scoring="f1",
)
Lineage
datalets stands on a 45-year research line: clusterwise regression
(Späth 1979), mixtures of experts (Jacobs, Jordan, Nowlan & Hinton 1991),
finite mixtures of regressions (DeSarbo & Cron 1988; R's flexmix), local
learning (Bottou & Vapnik 1992), and the cluster-then-predict practitioner
pattern. See examples/demo.py for a dataset where the approach provably
shines — and the report that tells you when it doesn't.
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file datalets-1.0.2.tar.gz.
File metadata
- Download URL: datalets-1.0.2.tar.gz
- Upload date:
- Size: 105.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via:
twine/7.0.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
1523bb014f95b0285778cc6439497bc70d8a7b11619e14e2da8afc51cd5691d9
|
|
| MD5 |
7934f8d1828894ccaec790a06790832e
|
|
| BLAKE2b-256 |
159f9cb96ac625efa0284f19e24bda9fea671a3b0547ef09360e4140b684ad48
|
Provenance
The following attestation bundles were made for datalets-1.0.2.tar.gz:
Publisher:
publish.yml on nashit8421/datalets
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
datalets-1.0.2.tar.gz -
Subject digest:
1523bb014f95b0285778cc6439497bc70d8a7b11619e14e2da8afc51cd5691d9 - Sigstore transparency entry: 2288231997
- Sigstore integration time:
-
Permalink:
nashit8421/datalets@1278cd540bc1cee0e4768be94c6959be4deb30a2 -
Branch / Tag:
refs/tags/v1.0.2 - Owner: https://github.com/nashit8421
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@1278cd540bc1cee0e4768be94c6959be4deb30a2 -
Trigger Event:
release
-
Statement type:
File details
Details for the file datalets-1.0.2-py3-none-any.whl.
File metadata
- Download URL: datalets-1.0.2-py3-none-any.whl
- Upload date:
- Size: 79.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via:
twine/7.0.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
cac0fdf8df53e820a3a197f67f232223c723e882ae23443e15ef87378ee63be9
|
|
| MD5 |
18e62b7f41bc2847f1a085377da26cc4
|
|
| BLAKE2b-256 |
49ffd02c107c57ba9f62f32753a8e77e19a2a642e5624524ba8e638656526396
|
Provenance
The following attestation bundles were made for datalets-1.0.2-py3-none-any.whl:
Publisher:
publish.yml on nashit8421/datalets
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
datalets-1.0.2-py3-none-any.whl -
Subject digest:
cac0fdf8df53e820a3a197f67f232223c723e882ae23443e15ef87378ee63be9 - Sigstore transparency entry: 2288232015
- Sigstore integration time:
-
Permalink:
nashit8421/datalets@1278cd540bc1cee0e4768be94c6959be4deb30a2 -
Branch / Tag:
refs/tags/v1.0.2 - Owner: https://github.com/nashit8421
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@1278cd540bc1cee0e4768be94c6959be4deb30a2 -
Trigger Event:
release
-
Statement type: