Recommenders often fail for design reasons rather than algorithm reasons:
- a random split that leaks the future
- no popularity baseline, so a "good" model may only recommend bestsellers
- RMSE optimised when the product shows a ranked list
- no plan for new users and items
- offline metrics that never meet the business metric
This skill sets up the design, the protocol and the evaluation:
scripts/interaction_profile.pyreads the log and recommends an approachscripts/temporal_split.pysplits the log the way the system will be usedscripts/rec_eval.pyscores any recommendation lists against held-out interactions, with beyond-accuracy metrics and a popularity baseline
Trigger Conditions
Activate this skill when the user:
- Plans a recommender ("you may also like", "customers also bought", next item, personalised feed or email)
- Must choose an approach (popularity, item-kNN, ALS, BPR, content-based, two-tower, LTR)
- Needs an offline evaluation protocol or metrics for recommendations
- Sees a recommender that only shows popular items, or offline gains that do not show up in A/B tests
Building item-kNN and matrix factorisation models: collaborative-filtering-implementer. Re-ranking with features: learning-to-rank-model-builder.
Workflow
1. PROFILE -> python scripts/interaction_profile.py interactions.csv
2. DEFINE -> the surface, what counts as relevant (purchase, rating >= 4, watch > 50%), k, constraints
3. SPLIT -> python scripts/temporal_split.py interactions.csv --mode leave-last --n 2 --prefix data
4. BASELINE -> popularity is computed automatically by rec_eval.py; add recent-popularity / item-kNN
5. MODEL -> candidates (CF, content) -> optional re-ranker; write recs.csv (user_id,item_id,rank[,model])
6. EVALUATE -> python scripts/rec_eval.py --recs recs.csv --test data_test.csv --train data_train.csv --k 10 --min-rating 4
7. ONLINE -> A/B test on the business metric; monitor coverage and feedback loopsChoosing an Approach
| Situation | Start with | Add |
|---|---|---|
| Little data, strong bestsellers | popularity (overall, per segment, recent) | item-kNN |
| Thousands of users and items, implicit feedback | item-kNN, ALS / EASE | BPR, a re-ranker |
| Explicit ratings | item-kNN / MF on ratings, evaluated as a ranking | treat low ratings as negative |
| Many new items (news, marketplace) | content-based (text / attribute embeddings) | hybrid with CF when interactions arrive |
| Many new users | popularity / contextual (location, device, referrer) | session-based models |
| Session data without user ids | item-to-item co-occurrence, session kNN, GRU4Rec / SASRec | |
| Large scale with rich features | two-tower retrieval + LTR re-ranking (GBDT LambdaMART) | |
| Repeat consumption (grocery, music) | personal frequency/recency baseline | CF for discovery |
Approach details, trade-offs and cold start: approaches.md.
Evaluation Protocol
- Split by time. Use leave-last-n per user (common in research) or a global cut-off (closest to deployment). Random splits put the future in train.
- Filter seen items unless re-recommendation is allowed.
rec_eval.pydoes this by default. - Relevance definition: explicit
rating >= 4(--min-rating 4), implicit purchases or long views. Write it down. - Always compare with popularity. On the fixture, popularity reached NDCG@10 0.164, a genre-aware list 0.440 and random 0.054. The exit code is 1 when no model beats popularity.
- Beyond accuracy:
| Metric | Measures | Watch for |
|---|---|---|
| coverage | share of the catalogue recommended | below 20%: long tail ignored |
| novelty | mean self-information of recommended items | very low: only bestsellers |
| popularity bias | popularity of recommended items vs the catalogue average | well above 1: popularity amplification |
| personalisation | 1 - mean Jaccard between users' lists | near 0: everyone gets the same list |
| diversity | distinct categories per list (with --item-features) | single-category lists |
- Segment the results: cold vs warm users, head vs tail items, and new vs returning users.
Metric definitions, sampled-metric pitfalls and offline-online gaps:
evaluating-recommenders.md. Verified: precision, recall, MAP and
NDCG match an independent computation (NDCG via sklearn.metrics.ndcg_score).
Architecture
candidate generation (CF, content, popularity, rules) -> ~500 candidates per user
ranking (GBDT / neural re-ranker with user, item, context features) -> scored list
business logic (availability, diversity, dedup, fairness to sellers, exploration) -> final k
logging (impressions, clicks, position) -> training data and evaluationServing patterns, feedback loops, exploration and A/B testing: production-recommenders.md.
Output Format
When designing a recommender, deliver:
- Data profile - size, density, cold start, popularity concentration, feedback type.
- Problem definition - surface, relevance, k, constraints, business metric.
- Approach - baselines, candidate sources, ranker, cold-start fallback.
- Offline evaluation - split, the metric table against popularity, segment results.
- Online plan - A/B design, guardrails (coverage, diversity), monitoring.
Scripts
python scripts/interaction_profile.py ratings.csv
python scripts/interaction_profile.py events.csv --user-col visitor --item-col product --time-col ts --cold 5 --jsonExit codes: 0 profiled, 2 usage or read error.
python scripts/temporal_split.py ratings.csv --mode leave-last --n 2 --prefix ratings
python scripts/temporal_split.py events.csv --mode global --test-frac 0.2 --time-col ts --prefix eventsWrites <prefix>_train.csv and <prefix>_test.csv, and reports cold test users and unseen test items.
Exit codes: 0 written, 2 usage or read error.
python scripts/rec_eval.py --recs recs.csv --test test.csv --train train.csv --k 10 --min-rating 4 --item-features items.csv
python scripts/rec_eval.py --recs all_models.csv --test test.csv --train train.csv --k 5 20 --jsonExit codes: 0 the best model beats popularity, 1 no model beats popularity, 2 usage or read error.
Additional Resources
| File | Content |
|---|---|
| approaches.md | popularity, neighbourhood, MF, EASE, content, hybrid, sequential, two-tower, LTR; cold start |
| evaluating-recommenders.md | splits, metric definitions, sampled metrics, segment analysis, offline vs online |
| production-recommenders.md | multi-stage architecture, serving, business rules, exploration, feedback loops, A/B tests |
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.