Skip to content
v0.1.3latest release121 skills4 categories6 sub-categories247 tested scripts397 reference docsContact us

categorical-encoding-selector

Choose and implement the right encoding for every categorical column given the model family and the data: one-hot (with infrequent-level grouping and handle_unknown), ordinal with an explicit order, cross-fitted target encoding (scikit-learn TargetEncoder, CatBoost ordered statistics, category_encoders inside CV), frequency/count encoding, feature hashing, native categorical support in LightGBM, HistGradientBoosting, XGBoost and CatBoost, prefix levels for codes (zip3, NAICS-2), and embeddings. Measures cardinality, rare-level share, unseen-level rate on a time-ordered holdout and target signal per column, emits the ColumnTransformer, and quantifies target-encoding leakage (in-sample vs out-of-fold vs holdout AUC). Use when someone asks how to encode categorical variables, one-hot vs target vs ordinal encoding, how to handle high-cardinality IDs, zip codes, unseen categories at inference, or why target encoding overfits.

AI & Machine Learning / Classical Machine Learningv1.0.0Updated OCT 25 20264 references2 scripts

The right encoder depends on three things: the model family (linear models need one column per level or a numeric summary; trees can split integer codes; modern GBMs take categories natively), the cardinality and rare/unseen levels, and whether the column carries order. Target encoding is powerful for high cardinality and dangerous when computed in-sample. scripts/encoding_plan.py measures each column and recommends an encoder with the scikit-learn code; scripts/te_leakage_check.py shows how much naive target encoding inflates a column's apparent signal.

Trigger Conditions

Activate this skill when the user:

  • Asks how to encode categorical variables, or one-hot vs label/ordinal vs target vs frequency encoding
  • Has high-cardinality columns (merchant, product, user, zip, city) and a model that overfits or explodes in width
  • Gets errors or silent issues from unseen categories at inference ("Found unknown categories")
  • Uses LightGBM / XGBoost / CatBoost / HistGradientBoosting and wants native categorical handling
  • Sees great CV scores after target encoding that collapse on a holdout

Workflow

text
1. INVENTORY -> python scripts/encoding_plan.py data.csv --target y --model <family> [--time-col ts]
2. ORDER     -> confirm ordinal columns and their order with a domain owner
3. CARDINAL  -> low: one-hot / native; high: target (cross-fitted), frequency, hashing; codes: prefixes
4. UNSEEN    -> handle_unknown / infrequent grouping / prior smoothing; measure unseen rate on recent data
5. LEAKAGE   -> python scripts/te_leakage_check.py data.csv --target y   (encoders inside CV only)
6. BUILD     -> python scripts/encoding_plan.py ... --code; place it in the Pipeline
7. COMPARE   -> 2-3 encodings on the same folds; keep the simplest that is not worse

Decision Table

ColumnLinear / logistic, k-NN, SVM, NNRandom forest / single treesLightGBM / HistGBM / XGBoostCatBoost
2 levels0/10/10/10/1 or cat_features
Ordered (low < med < high)ordinal integer (or one-hot if effect is non-monotone)ordinalordinalordinal or cat_features
<= ~15 levels, nominalone-hotordinal codes or one-hotnative categoricalcat_features
15-100 levelsone-hot with min_frequency / max_categoriesordinal or targetnative (< 256 levels)cat_features
100+ levels, enough rows per levelcross-fitted target encoding + frequencytarget / frequencynative up to 255, else target / frequencycat_features
100+ levels, many unseen at serve timehashing or frequency; target with strong smoothingfrequencyfrequency / targetcat_features
Near-unique (IDs)drop (or aggregate features per ID)dropdropdrop
Hierarchical codes (zip, NAICS, ICD)prefix levels, then the rules abovesamesamesame
Free textnot categorical: TF-IDF / embeddingstext_features
Datesnot categorical: date features

Encoder internals, parameters and edge cases: encoder-catalog.md.

One-Hot Done Right

python
from sklearn.preprocessing import OneHotEncoder
ohe = OneHotEncoder(handle_unknown="infrequent_if_exist", min_frequency=20, sparse_output=True)
  • min_frequency / max_categories group rare levels into one "infrequent" column, learned on train.
  • handle_unknown="infrequent_if_exist" maps unseen levels to the infrequent column (or "ignore" -> all zeros).
  • drop="if_binary" for linear models without regularisation (avoid the dummy trap); with L2 regularisation keep all columns.
  • Sparse output for wide data; most linear solvers accept sparse matrices.

Target Encoding Without Leakage

Replacing a level by the mean target of its rows is in-sample memorisation when the row's own label is included. Rare levels then "predict" perfectly in CV and fail on new data.

text
encoded(level) = (sum_y(level) + m * prior) / (n(level) + m)       # smoothing toward the global mean

Safe implementations:

  • scikit-learn TargetEncoder (>= 1.3): fit_transform cross-fits internally (each row encoded by a model fitted on other folds); transform uses the full-train mapping. Supports binary, multiclass (one column per class) and continuous targets; smooth="auto" uses empirical Bayes shrinkage.
  • CatBoost: ordered target statistics (encode each row using only "earlier" rows in a random permutation), the default for cat_features.
  • category_encoders (TargetEncoder, MEstimateEncoder, JamesSteinEncoder, CatBoostEncoder): only inside a Pipeline evaluated with CV, never fitted on all data before splitting.

te_leakage_check.py makes the danger concrete:

text
column                 levels rows/lvl in-sample     OOF  holdout     gap
merchant_id_name          471      6.4     0.858   0.723    0.755  +0.135  <- in-sample encoding leaks
zip_code                  397      1.0     1.000   0.499    0.500  +0.501  <- in-sample encoding leaks

A near-unique column gets AUC 1.000 in-sample and 0.5 honestly. Leakage detail and nested-CV patterns: target-encoding-and-leakage.md.

Native Categorical Support in GBMs

LibraryHowNotes
LightGBMcategorical_feature=[...] or pandas category dtypeoptimal split over sorted level gradients; tune cat_smooth, min_data_per_group, max_cat_threshold; can overfit high cardinality
HistGradientBoostingcategorical_features="from_dtype" (>= 1.4) or a boolean mask< 256 levels (max_bins); codes must be 0..k-1, negative = missing
XGBoostenable_categorical=True with pandas category dtype, tree_method="hist"max_cat_to_onehot switches to one-hot splits for small k
CatBoostcat_features=[...]ordered target statistics + feature combinations; strong default for many categoricals

Category dtype must have identical categories (same order) in training and serving: store the category list with the model. Code: gbm-native-categoricals.md.

Unseen and Rare Levels

SituationHandling
New levels appear in production (new merchants)one-hot handle_unknown; target encoding falls back to the prior; frequency = 0; hashing handles it
Rare levels (< 20 rows)group into "other" (min_frequency) or rely on smoothing
Levels change meaning over timetime-based validation; re-fit encoders on retrain
Missing valuesexplicit "missing" level for one-hot/target; native handling in GBMs

encoding_plan.py --time-col measures the share of the latest 20% of rows whose level never appears in the earlier 80%: that is roughly the unseen rate the model will face.

Output Format

When recommending encodings, answer with:

  1. Per-column plan - levels, rare share, unseen rate, order, target signal, chosen encoder and why (the encoding_plan.py table).
  2. Code - the ColumnTransformer (or native-categorical setup) inside a Pipeline.
  3. Leakage note - for target-encoded columns, the cross-fitting method and the te_leakage_check.py gap.
  4. Serving notes - unseen-level behaviour, stored category lists, refit schedule.
  5. Comparison plan - which alternative encoders to test on the same folds.

Scripts

bash
python scripts/encoding_plan.py data.csv --target churned --model linear
python scripts/encoding_plan.py data.csv --target is_fraud --model gbm --time-col timestamp --drop txn_id
python scripts/encoding_plan.py data.csv --target y --model catboost --json
python scripts/encoding_plan.py data.csv --target y --model linear --code > prep.py

Models: linear, knn, nn, tree, gbm, catboost. Per non-numeric column (plus numeric-looking codes): levels, rows per level, missing share, rare share (--min-count, default 20), unseen rate on the latest (or hashed) 20%, detected order (low/medium/high, S/M/L, basic/standard/premium, Likert...), out-of-fold target signal; then one of onehot, onehot_infrequent, ordinal, target, hashing, native, catboost_native, prefix (near-unique codes), skip (dates) or drop (IDs). --code prints a ColumnTransformer with OneHotEncoder / OrdinalEncoder (explicit categories) / TargetEncoder / FeatureHasher steps (picklable) and the native-categorical list. Exit codes: 0 printed, 2 usage or read error.

bash
python scripts/te_leakage_check.py data.csv --target is_fraud --time-col date
python scripts/te_leakage_check.py data.csv --target churned --columns zip_code plan --folds 5 --smooth 20 --json

For each categorical column: ROC-AUC of the target-encoded column alone, in-sample vs out-of-fold (smoothed, K folds) vs time-ordered holdout, the gap, and a flag when the gap exceeds --max-gap for columns with fewer than --min-rows-per-level rows per level. Exit codes: 0 no flagged column, 1 flagged column(s), 2 usage error or non-binary target.

Additional Resources

FileContent
encoder-catalog.mdEvery encoder: one-hot, dummy, ordinal, target/M-estimate/James-Stein/WoE, frequency, hashing, binary, embeddings, prefixes; parameters and pitfalls
target-encoding-and-leakage.mdWhy in-sample encoding leaks, smoothing math, cross-fitting, nested CV, multiclass and regression targets, time-aware encoding
gbm-native-categoricals.mdLightGBM, XGBoost, HistGradientBoosting, CatBoost native categorical code and tuning, serving consistency
comparing-encoders.mdExperiment design for choosing encoders, typical results by model family, width and latency costs
More in Classical Machine Learning

anomaly-detection-model-builder

Build and evaluate anomaly detection for tabular, sensor and transaction data with few or no labels: define the anomaly type (point, contextual, collective), choose detectors (robust z-score/MAD and IQR rules, Mahalanobis with robust covariance, k-NN distance, LOF, Isolation Forest, one-class SVM, PCA reconstruction / autoencoders, forecasting residuals for time series), combine them by rank, explain each alert by its deviating features, set thresholds from an alert budget or the score distribution, and evaluate with precision@k, PR-AUC and recall on known incidents, or detector agreement when no labels exist. Includes pure-Python detectors (robust z, Mahalanobis, kNN, Isolation Forest, ensemble) and an evaluation script.

catboost-model-builder

Build CatBoost models that use its strengths correctly: raw categorical columns as cat_features (ordered target statistics, no manual encoding), text_features, Pool construction with NaN-safe categories, ordered boosting and has_time for temporal data, symmetric (oblivious) trees, overfitting detector with eval_set and use_best_model, losses for classification, regression (Quantile, Poisson, Tweedie) and ranking (YetiRank), class weights, monotone constraints, feature importance (PredictionValuesChange, LossFunctionChange) and SHAP values, GPU training and model export. Plans cat/text/numeric columns from a CSV and generates a runnable training script, and checks parameter sets for the conflicts CatBoost rejects (iterations vs n_estimators, Bayesian bootstrap with subsample, multiple class-weight options, depth > 16, use_best_model without eval_set).

classification-model-selector

Choose the right classification algorithm for tabular, text or mixed data and prove the choice with a fair bake-off: logistic regression (L2, L1, elastic net), linear SVM, naive Bayes, k-NN, RBF SVM, decision trees, random forest, extra trees, HistGradientBoosting, LightGBM, XGBoost, CatBoost, explainable boosting machines (EBM/GAM), points scorecards and MLPs, matched to data size, width, categorical and high-cardinality share, missingness, class imbalance, text, and constraints such as interpretability, monotonic constraints, calibrated probabilities, latency budgets and tiny deployable models. Ranks candidates with starting hyperparameters and cautions, then generates a bake-off script running every candidate on identical CV folds with per-fold metrics, fit time and prediction latency.

clustering-algorithm-selector

Choose the right clustering algorithm and check that clustering makes sense at all: cluster tendency (Hopkins statistic with a correlated-features caveat, nearest-neighbour isolation), then k-means / MiniBatchKMeans, Gaussian mixtures with BIC, agglomerative (Ward, average, complete, single) with dendrograms, DBSCAN, HDBSCAN, OPTICS, spectral clustering, BIRCH, mean shift, k-prototypes and k-modes for mixed or categorical data, and Gower distance, matched to data size, expected shapes, noise, varying density, known k, soft memberships, hierarchy and streaming. Covers preprocessing (scaling, encoding, dimensionality, distance metrics), validation (internal indices, bootstrap stability, external labels, business profiling) and assigning new points.

collaborative-filtering-implementer

Implement collaborative filtering recommenders that beat popularity: item-based kNN with cosine, Jaccard or asymmetric similarity, shrinkage, neighbourhood size, positive-only or mean-centred rating signals and 'because you liked X' explanations; implicit ALS with confidence weighting, BPR pairwise ranking and the closed-form EASE model in plain NumPy, tuned on a temporal validation split by recall@k and NDCG@k and refit on all data; plus user-kNN, explicit matrix factorisation, the implicit/LightFM libraries, hyperparameter ranges, cold-start fallbacks, scaling with sparse matrices and approximate nearest neighbours. Produces top-k lists in the format of the recommendation evaluator.

counterfactual-explanation-generator

Generate counterfactual explanations and algorithmic recourse: the smallest realistic change to a row's features that changes the model's decision. Solves exact minimal-cost recourse for linear and logistic models (MAD-scaled L1 cost, immutable features, increase/decrease directions, bounds, integer and binary features, diverse alternatives, features every counterfactual must change, and a no-recourse finding when immutable features decide), generates DiCE counterfactuals for any scikit-learn model with constraints turned into permitted ranges and every result re-predicted, and validates counterfactuals from any method for constraint violations, implausible values, off-manifold rows, broken derived-feature relations and failure to flip the prediction.