prep is a ColumnTransformer (scaled numerics + one-hot for linear models; ordinal/native categoricals for
trees). See scikit-learn-pipeline-builder.
Linear and GLMs (scikit-learn)
from sklearn.linear_model import RidgeCV, LassoCV, ElasticNetCV, HuberRegressor, PoissonRegressor, GammaRegressor, TweedieRegressor
from sklearn.pipeline import make_pipeline
import numpy as np
ridge = make_pipeline(prep, RidgeCV(alphas=np.logspace(-3, 3, 25)))
huber = make_pipeline(prep, HuberRegressor(epsilon=1.35, alpha=1e-4, max_iter=1000))
poisson = make_pipeline(prep, PoissonRegressor(alpha=1e-3, max_iter=1000))
gamma = make_pipeline(prep, GammaRegressor(alpha=1e-3, max_iter=1000))
tweedie = make_pipeline(prep, TweedieRegressor(power=1.6, link="log", alpha=1e-3, max_iter=1000))GLM coefficients with a log link are multiplicative effects: exp(coef) per unit (per SD when scaled).
HistGradientBoosting
from sklearn.ensemble import HistGradientBoostingRegressor
hgb = HistGradientBoostingRegressor(loss="squared_error", # "absolute_error", "gamma", "poisson", "quantile"
learning_rate=0.05, max_leaf_nodes=31, min_samples_leaf=40,
l2_regularization=1.0, early_stopping=True, validation_fraction=0.15,
monotonic_cst=None, random_state=0)No Tweedie loss in HistGradientBoosting: use LightGBM/XGBoost/CatBoost, or TweedieRegressor.
LightGBM
import lightgbm as lgb
reg = lgb.LGBMRegressor(objective="tweedie", tweedie_variance_power=1.5, n_estimators=5000, learning_rate=0.03,
num_leaves=31, min_child_samples=50, subsample=0.8, subsample_freq=1,
colsample_bytree=0.8, reg_lambda=1.0, random_state=0, verbose=-1)
reg.fit(X_tr, y_tr, eval_set=[(X_va, y_va)], eval_metric="tweedie",
callbacks=[lgb.early_stopping(200), lgb.log_evaluation(0)])
# Exposure offset for Poisson/Tweedie: the model learns the rate.
# With init_score LightGBM does not boost from the average (it starts at raw score 0 = rate 1), so put the
# base rate into the offset too; otherwise early stopping can halt while predictions are still biased.
base = y_tr.sum() / exposure_tr.sum()
reg_off = lgb.LGBMRegressor(objective="poisson", n_estimators=3000, learning_rate=0.03, verbose=-1)
reg_off.fit(X_tr, y_tr, init_score=np.log(exposure_tr) + np.log(base),
eval_set=[(X_va, y_va)], eval_init_score=[np.log(exposure_va) + np.log(base)],
callbacks=[lgb.early_stopping(200)])
rate = reg_off.predict(X_new) * base # predict() excludes init_score: add the base rate back
expected = rate * exposure_new # counts for the new rows' exposureMeasured on the claims fixture: offset with the base rate -> mean predicted rate 0.164 vs actual 0.166;
offset without it -> 0.226 after early stopping. LightGBM >= 4.7 deprecates eval_set in the scikit-learn
API in favour of eval_X= / eval_y=; eval_set still works with a warning.
Other objectives: regression, regression_l1, huber (alpha = δ), fair, quantile (alpha = q),
mape, gamma, poisson, cross_entropy.
XGBoost
import xgboost as xgb
reg = xgb.XGBRegressor(objective="reg:gamma", n_estimators=5000, learning_rate=0.03, max_depth=6,
min_child_weight=5, subsample=0.8, colsample_bytree=0.8, reg_lambda=1.0,
tree_method="hist", early_stopping_rounds=200, random_state=0)
reg.fit(X_tr, y_tr, eval_set=[(X_va, y_va)], verbose=False)
# offsets: reg.fit(X, y, base_margin=np.log(exposure)); prediction needs base_margin tooQuantile: objective="reg:quantileerror", quantile_alpha=[0.1, 0.5, 0.9] (multi-quantile in one model).
CatBoost
from catboost import CatBoostRegressor
reg = CatBoostRegressor(loss_function="Tweedie:variance_power=1.5", iterations=5000, learning_rate=0.05,
depth=6, l2_leaf_reg=3, od_type="Iter", od_wait=200, random_seed=0, verbose=0,
cat_features=cat_cols)
reg.fit(X_tr, y_tr, eval_set=(X_va, y_va), use_best_model=True)baseline= in Pool carries an offset.
Monotone constraints
HistGradientBoostingRegressor(monotonic_cst={"sqft": 1, "age": -1}) # dict by name (sklearn >= 1.2)
lgb.LGBMRegressor(monotone_constraints=[1, -1, 0, ...]) # one per feature, in column order
xgb.XGBRegressor(monotone_constraints={"sqft": 1, "age": -1})Sample weights
Use weights for exposure (rates), for reflecting the population when rows were sampled unevenly, or for
business importance (revenue-weighted error). Pass them to fit and to the evaluation metric.
Ensembles
Averaging a GLM and a GBM, or GBMs with different objectives, often improves calibration across deciles.
Stack with out-of-fold predictions (StackingRegressor(cv=5)) when the gain justifies the complexity.
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.