Skip to content
v0.1.3latest release121 skills4 categories6 sub-categories247 tested scripts397 reference docsContact us

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. Use when someone builds 'users who liked this also liked', item-to-item recommendations, matrix factorisation or ALS/BPR models, or asks why their collaborative filter is no better than recommending bestsellers.

AI & Machine Learning / Classical Machine Learningv1.0.0Updated OCT 25 20263 references2 scripts

Collaborative filtering (CF) recommends from the interaction matrix alone: people who liked X also liked Y. Done well, it is a strong recommender. Done carelessly, it is popularity with extra steps. The details that decide it are which interactions count as positive, similarity shrinkage, regularisation strong enough for sparse data, and hyperparameters tuned on a temporal validation split.

  • scripts/itemknn.py implements item-kNN with explanations
  • scripts/gen_mf_script.py generates NumPy ALS, BPR and EASE models with tuning

Both write lists that rec_eval.py from recommendation-system-designer scores against the popularity baseline.

Trigger Conditions

Activate this skill when the user:

  • Builds item-to-item ("similar items", "also liked") or personalised CF recommendations
  • Implements or tunes ALS, BPR, EASE, SVD/matrix factorisation or kNN recommenders
  • Has a CF model that barely beats popularity, or recommends only bestsellers
  • Needs explanations for recommendations ("because you watched X")

Design, data profiling, splits and evaluation: recommendation-system-designer. Feature-based re-ranking of CF candidates: learning-to-rank-model-builder.

Workflow

text
1. SPLIT     -> temporal_split.py (recommendation-system-designer) -> train.csv / test.csv
2. KNN       -> python scripts/itemknn.py train.csv --min-rating 4 --k 10 -o recs_knn.csv
3. MF        -> python scripts/gen_mf_script.py --train train.csv --min-rating 4 --k 10 -o mf.py; python mf.py
4. EVALUATE  -> rec_eval.py --recs recs_all.csv --test test.csv --train train.csv --k 10 --min-rating 4
5. TUNE      -> signal definition first, then shrink/neighbours (kNN) or lambda/alpha/factors (ALS), lambda (EASE)
6. SHIP      -> the best model plus a popularity fallback for cold users; explanations from item-kNN

Signal Definition Matters Most

On the ratings fixture (NDCG@10 on a leave-last-3 split, relevant = rating >= 4):

Item-kNN signalNDCG@10Coverage
all interactions as positive (low ratings included)0.1740.49
positives only (--min-rating 4)0.3020.80
positives only, no shrinkage (--shrink 0)0.3500.86
mean-centred ratings (--weighted)0.3640.96
popularity baseline0.1640.46

Treating a 1-star rating as "liked" teaches the model the wrong taste. For implicit data (views, plays, purchases), weight by count with confidence (ALS) and drop accidental signals (bounces, short plays).

Models

ModelStrengthsKey hyperparametersFixture NDCG@10
Item-kNN (itemknn.py)explainable, stable, cheap, strong on small and medium datasimilarity, shrink (0-100), neighbours (20-200)0.364
ALS (implicit, Hu et al. 2008)scales, implicit confidencefactors 8-256, lambda 0.1-100, alpha 1-400.354
EASE (Steck 2019)closed form, often the strongest simple baselinelambda 10-10000.331
BPRoptimises ranking directlyfactors, learning rate, epochs, negative sampling0.300

On this small fixture all four beat popularity clearly. The ordering changes with data size, so tune them all on validation and pick by the test result. The NumPy ALS matches the implicit library (exact solver, same hyperparameters) on precision, recall, hit rate and coverage, and within 0.011 NDCG (initialisation). Item cosine similarities match sklearn.metrics.pairwise.cosine_similarity to 1e-16.

Algorithms, formulas and library code: neighbourhood-methods.md and matrix-factorisation.md.

Tuning Rules

  • Tune on a validation split taken from train (the generated script holds out each user's last positive), then refit on all training data. The test split is touched once.
  • Small or sparse data needs strong regularisation. ALS chose lambda 50 here. With lambda 0.1-1 it scored only 0.174. EASE lambda grows with the catalogue size.
  • Shrinkage stops item pairs with one or two common users from looking identical. Tune 0-100, and expect less of it on dense data.
  • Check coverage and popularity bias alongside NDCG. A model that wins NDCG by recommending the head of the catalogue may lose online.
  • Cold users (fewer than 3-5 positives) get popularity or content fallbacks. itemknn.py fills short lists with popular unseen items and marks them.

Scaling (sparse matrices, ANN retrieval, incremental updates) and production notes: scaling-and-serving.md.

Output Format

When implementing CF, deliver:

  1. Signal - what counts as positive and how it is weighted.
  2. Models and tuning - validation grid results and the chosen hyperparameters.
  3. Test comparison - rec_eval.py table: kNN, ALS/EASE/BPR, popularity; coverage and bias included.
  4. Recommendations - top-k CSV with explanations (kNN) and the cold-start fallback.
  5. Next steps - re-ranking with features, an A/B test, retraining cadence.

Scripts

bash
python scripts/itemknn.py train.csv --k 10 -o recs.csv
python scripts/itemknn.py ratings_train.csv --min-rating 4 --similarity cosine --shrink 10 --neighbors 50 -o recs.csv
python scripts/itemknn.py events.csv --user-col visitor --item-col product --similarity asymmetric --alpha 0.7

Output columns: user_id, item_id, rank, score, because. Exit codes: 0 written, 2 usage or read error.

bash
python scripts/gen_mf_script.py --train ratings_train.csv --min-rating 4 --k 10 -o mf.py
python scripts/gen_mf_script.py --train events.csv --user-col visitor --item-col product --models als ease --k 20

The generated script writes recs_<model>.csv and recs_all.csv (with a model column). Exit codes: 0 written, 2 usage error.

Additional Resources

FileContent
neighbourhood-methods.mditem/user kNN, similarities, shrinkage, normalisation, explanations, co-occurrence
matrix-factorisation.mdexplicit MF, implicit ALS, BPR, EASE, hyperparameters, implicit / LightFM / surprise code
scaling-and-serving.mdsparse data structures, ANN retrieval, incremental updates, batch vs online, monitoring
More in Classical Machine Learning

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.

counterfactual-explanation-generator

Generate counterfactual explanations and algorithmic recourse: the smallest realistic change to a row's features that changes the model's decision. Solves exact minimal-cost recourse for linear and logistic models (MAD-scaled L1 cost, immutable features, increase/decrease directions, bounds, integer and binary features, diverse alternatives, features every counterfactual must change, and a no-recourse finding when immutable features decide), generates DiCE counterfactuals for any scikit-learn model with constraints turned into permitted ranges and every result re-predicted, and validates counterfactuals from any method for constraint violations, implausible values, off-manifold rows, broken derived-feature relations and failure to flip the prediction.