Impurity / gain (model-based)
| Library | Call | Default type |
|---|---|---|
| LightGBM | model.booster_.feature_importance(importance_type="gain") | feature_importances_ is split count by default (importance_type="split") |
| XGBoost | model.get_booster().get_score(importance_type="total_gain") | feature_importances_ uses gain (average gain per split) for tree boosters |
| CatBoost | model.get_feature_importance() | PredictionValuesChange; type="LossFunctionChange" needs data and is held-out-capable |
| scikit-learn trees/forests | model.feature_importances_ | mean decrease in impurity (MDI), normalised to sum 1 |
Prefer total gain over split counts: split counts reward features that are split on often for small gains. All of these are computed from training data and inherit training-set overfitting.
Coefficients
|coef_j| x std(x_j) (or the coefficients of a model fitted on standardised features) gives the change in the
linear predictor for a one-standard-deviation change. Without scaling, coefficients are not comparable. Under
collinearity they are unstable, so use permutation importance instead.
Permutation importance (held-out)
from sklearn.inspection import permutation_importance
r = permutation_importance(pipe, X_test, y_test, scoring="roc_auc", n_repeats=10, random_state=0, n_jobs=-1)
r.importances_mean, r.importances_std, r.importances # (features, repeats)- Run it on the whole pipeline with raw input columns: importance is then per input feature, and one-hot levels are permuted together automatically.
- Use 10-30 repeats. Report mean ± std; a feature is distinguishable from zero if mean > 2 x std.
- Several scorers at once:
scoring=["roc_auc", "average_precision"]returns a dict of results. - Cost: features x repeats x one prediction pass, with no refitting.
Grouped permutation
Permuting one of two correlated features barely hurts, because the model reads the other one. Permuting the group jointly measures the information they share.
def group_importance(model, X, y, scorer, members, repeats=10, seed=0):
rng = np.random.default_rng(seed)
base = scorer(model, X, y)
drops = []
for _ in range(repeats):
Xp = X.copy()
Xp[members] = Xp[members].to_numpy()[rng.permutation(len(Xp))] # same shuffle for all members
drops.append(base - scorer(model, Xp, y))
return np.mean(drops), np.std(drops)Groups come from domain knowledge (all "billing" features) or from correlation clustering (|Spearman| >= 0.7;
gen_importance_script.py uses union-find over that threshold).
Drop-column importance
Retrain without the feature (same CV, same seeds) and compare held-out scores. This is the most faithful answer to "do we need this feature?", but it costs one refit per feature (or group). Use it for a shortlist or a final decision, not for screening hundreds of features.
Mean |SHAP|
See shap-value-explainer. Summing |SHAP| over one-hot columns is valid for
a "use" measure (sum the signed values first per row, then take the absolute value, as
gen_shap_script.py --group does).
Conditional / model-agnostic alternatives
| Method | When |
|---|---|
| Conditional permutation (permute within bins of correlated features) | correlated features, want the unique contribution |
| LOCO (leave one covariate out) with refits | statistical inference on importance |
| SAGE (Shapley additive global importance) | Shapley-fair global importance of loss; expensive |
| Boruta (shadow features) | all-relevant feature selection, not ranking |
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).
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).
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.