Ranking
DCG and NDCG@k
DCG@k = Σ_{i=1..k} (2^{rel_i} − 1) / log2(i + 1) # exponential gain (common in LTR)
IDCG@k = DCG@k of the ideal ordering
NDCG@k = DCG@k / IDCG@k # per query, then averaged over queriesQueries with no relevant items have IDCG = 0: decide explicitly whether they count as 0, 1 or are excluded
(LightGBM's lambdarank counts them as 1 by default). Linear gain rel_i instead of 2^{rel}-1 is the other
convention: state which one you use.
MRR
Mean of 1 / rank of the first relevant item. Use when one right answer matters (navigational search, QA).
MAP@k
Mean over queries of average precision within the top k. Binary relevance.
Recall@k / hit rate@k
Share of relevant items (or of queries with at least one relevant item) appearing in the top k.
import numpy as np
from sklearn.metrics import ndcg_score
ndcg_score([true_relevance_per_query], [scores_per_query], k=10) # one query per row; pads must be equal lengthRecommendation
| Metric | Measures | Caveat |
|---|---|---|
| Recall@k | future interactions retrieved in the list | needs a time-based holdout, not random |
| NDCG@k | position-aware retrieval | graded relevance from ratings or dwell time |
| Coverage | share of catalogue ever recommended | popularity recommenders score low |
| Novelty | mean −log2(popularity) of recommended items | trades off with accuracy |
| Diversity | 1 − mean pairwise similarity in a list | needs item features |
| Popularity bias | share of recommendations from the head | monitor drift toward popular items |
Offline gains in recall@k often do not transfer online; treat CTR/conversion/retention from an A/B test as the real success metric.
Survival
Concordance index
Share of comparable pairs (the earlier time is an observed event) where the model ranks risk correctly.
- Harrell's C: biased under heavy censoring.
- Uno's C: inverse-probability-of-censoring weighted; preferred when censoring is heavy or depends on time.
from lifelines.utils import concordance_index
concordance_index(durations, -risk_scores, events) # higher risk -> shorter time, so negate
from sksurv.metrics import concordance_index_ipcw # Uno's CTime-dependent AUC and integrated Brier score
cumulative_dynamic_auc(scikit-survival) at the decision horizon (e.g. 90 days).- Integrated Brier score over [t_min, t_max]: calibration + discrimination of the survival curve.
Uplift
Uplift curve and Qini
Sort by predicted uplift; at each fraction φ of the population:
Qini(φ) = Y_T(φ) − Y_C(φ) · N_T(φ) / N_C(φ) # incremental positives among the top φ- Qini coefficient: area between the Qini curve and the random-targeting line, normalised by the area for the ideal model.
- AUUC: area under the uplift curve (conversion-rate difference version).
- Uplift@K: (conversion_T − conversion_C) among the top K.
Valid only on randomised data (RCT or proper randomisation). See uplift-model-builder for code.
Anomaly detection
| Metric | When |
|---|---|
| Precision@k (k = alert budget) | analysts review k alerts per day |
| Recall on known incidents | a catalogue of past incidents exists |
| Time to detect | streaming detection |
| Alert volume, alert fatigue | always a guardrail |
| PR-AUC | once a labelled set exists |
Clustering (diagnostics, not success)
| Metric | Higher is better? | Notes |
|---|---|---|
| Silhouette | yes (−1..1) | favours convex, similar-sized clusters |
| Calinski-Harabasz | yes | same bias |
| Davies-Bouldin | no (lower) | same bias |
| Adjusted Rand / NMI vs labels | yes | only with ground truth |
| Bootstrap stability (ARI between runs) | yes | the most useful check |
Success for clustering is that segments lead to different actions and remain stable over time.
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.