Code assumes X_train, X_test, y_train, y_test from the deployment-faithful split.
Classification
Dummy predictors
from sklearn.dummy import DummyClassifier
from sklearn.metrics import average_precision_score, log_loss, roc_auc_score
for strategy in ("most_frequent", "prior", "stratified"):
d = DummyClassifier(strategy=strategy, random_state=0).fit(X_train, y_train)
p = d.predict_proba(X_test)[:, 1]
print(strategy, roc_auc_score(y_test, p), average_precision_score(y_test, p), log_loss(y_test, p, labels=[0, 1]))priorgives the log-loss and Brier floor.- PR-AUC of any constant score equals the test prevalence.
Current business rule
rule = (X_test["support_calls"] >= 3) | (X_test["last_login_days"] > 30)
from sklearn.metrics import precision_score, recall_score
print("rule precision", precision_score(y_test, rule), "recall", recall_score(y_test, rule))For capacity-bound decisions, compare at the same K: rank by the rule's own priority order (or randomly within the rule's positives) and take the top K.
One feature (OneR)
import pandas as pd
from sklearn.metrics import roc_auc_score
def one_feature_auc(col, bins=10):
if pd.api.types.is_numeric_dtype(X_train[col]):
edges = pd.qcut(X_train[col], bins, retbins=True, duplicates="drop")[1]
tr = pd.cut(X_train[col], edges, include_lowest=True)
te = pd.cut(X_test[col].clip(edges[0], edges[-1]), edges, include_lowest=True)
else:
tr, te = X_train[col], X_test[col]
rate = y_train.groupby(tr, observed=True).mean()
return roc_auc_score(y_test, te.map(rate).astype(float).fillna(y_train.mean()))Pick the column on a validation split, not on the test set.
Linear and GBM baselines
See first-model-recipes.md; untuned LogisticRegression(max_iter=2000) and
HistGradientBoostingClassifier() in pipelines.
Regression
from sklearn.dummy import DummyRegressor
for strategy in ("mean", "median"):
d = DummyRegressor(strategy=strategy).fit(X_train, y_train)- Median minimises MAE; mean minimises squared error; report the one that matches the metric.
- R² of the mean predictor on the test set is ≈ 0 (slightly negative because the train mean differs).
- For WAPE/MAPE-reported problems, also try
DummyRegressor(strategy="quantile", quantile=0.5).
Forecasting
import numpy as np
def naive(y, h): # last observed value
return np.repeat(y[-1], h)
def seasonal_naive(y, h, m): # same point one season ago
return np.array([y[-m + (i % m)] for i in range(h)])
def drift(y, h): # straight line from first to last value
slope = (y[-1] - y[0]) / (len(y) - 1)
return y[-1] + slope * np.arange(1, h + 1)
def moving_average(y, h, w=28):
return np.repeat(np.mean(y[-w:]), h)
def mase(y_true, y_pred, y_train, m):
scale = np.mean(np.abs(y_train[m:] - y_train[:-m]))
return np.mean(np.abs(y_true - y_pred)) / scaleBacktest on several rolling origins (see time-series-forecasting-model-builder).
Intermittent demand (Croston / SBA)
def croston(y, h, alpha=0.1, sba=True):
z = p = None
q = 1
for v in y:
if v > 0:
z = v if z is None else z + alpha * (v - z)
p = q if p is None else p + alpha * (q - p)
q = 1
else:
q += 1
if z is None:
return np.zeros(h)
f = z / p * ((1 - alpha / 2) if sba else 1)
return np.repeat(f, h)Recommendation
popular = train.groupby("item_id").size().sort_values(ascending=False).index[:10]
# per-user top-k excluding items already seen
def recommend(user, k=10):
seen = set(train.loc[train.user_id == user, "item_id"])
return [i for i in popular_full if i not in seen][:k]Segment popularity (most popular among users in the same country/plan) is a stronger, still-cheap rung.
Ranking
- Current production ranking or BM25 score.
- Sort by one strong feature (clicks, recency).
- Random order within a query gives the NDCG floor (compute it, it is not 0).
Anomaly detection
med = X_train.median()
mad = (X_train - med).abs().median() * 1.4826
score = ((X_test - med).abs() / mad.replace(0, np.nan)).max(axis=1) # worst robust z across featuresSurvival
Kaplan-Meier without covariates predicts the same survival curve for everyone: concordance 0.5, and its integrated Brier score is the floor for covariate models.
Uplift
| Policy | Expected value |
|---|---|
| Treat nobody | control conversion rate x N |
| Treat everyone | treatment conversion rate x N - cost x N |
| Random targeting of K | linear between the two; Qini = 0 |
| Response model (top K by P(convert)) | often worse than random for uplift: targets sure things |
Multiclass
- Majority class: accuracy = majority share; macro-F1 ≈ 1/K x F1 of the majority.
- Class priors (stratified dummy).
- Keyword or rule router (rung 2).
Clustering
Compare silhouette / stability against:
- K random clusters of the same sizes (silhouette ≈ 0).
- The same algorithm on data with each column independently shuffled (destroys structure).
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.