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

Matrix Factorisation

Reference for collaborative-filtering-implementer · 67 lines

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

Explicit ratings (biased MF / "Funk SVD")

text
r_hat(u, i) = mu + b_u + b_i + p_u . q_i
minimise sum over observed (r - r_hat)^2 + lambda (|p_u|^2 + |q_i|^2 + b_u^2 + b_i^2)

SGD or ALS on observed ratings only. It optimises RMSE, which rarely matches a ranked list, so evaluate the ranking anyway. Libraries: surprise.SVD, surprise.SVDpp.

Implicit ALS (Hu, Koren & Volinsky 2008)

text
p(u, i) = 1 if the user interacted, else 0         (preference)
c(u, i) = 1 + alpha * r(u, i)                       (confidence; r = count / plays / weight)
minimise sum over ALL (u, i) of c(u, i) (p(u, i) - x_u . y_i)^2 + lambda (|x_u|^2 + |y_i|^2)
x_u = (Y'Y + Y'(C_u - I)Y + lambda I)^-1 Y' C_u p(u)       (closed form per user; same for items)
  • The Y'Y trick makes each update cost O(f^2 * n_u + f^3).
  • Hyperparameters: factors 8-256 (more with more data), lambda 0.1-100 (strong for sparse data), alpha 1-40 (or log scaling: c = 1 + alpha log(1 + r / eps)), iterations 10-20.
python
import scipy.sparse as sp
from implicit.als import AlternatingLeastSquares
model = AlternatingLeastSquares(factors=64, regularization=10.0, alpha=20.0, iterations=15, random_state=0)
model.fit(user_items)                                  # users x items CSR (implicit >= 0.5)
ids, scores = model.recommend(uid, user_items[uid], N=10, filter_already_liked_items=True)
similar_ids, sims = model.similar_items(item_id, N=10)

BPR (Rendle et al. 2009)

Maximises sum log sigmoid(x_ui - x_uj) over (user, positive item, sampled negative item) triples. It optimises AUC-like ranking directly. Negative sampling matters: uniform sampling is the default, and popularity-based sampling gives harder negatives. Libraries: implicit.bpr.BayesianPersonalizedRanking, LightFM (loss="bpr" or "warp", where WARP is often better for top-k).

EASE (Steck 2019)

text
G = X'X + lambda I ;  P = G^-1 ;  B = -P / diag(P) (column-wise) ; diag(B) = 0 ;  scores = X B

EASE is a closed-form item-item linear model with no latent factors, and is often the strongest simple model on benchmark datasets. Cost: an items x items inverse (fine below ~20-50k items). lambda: 10-1000+, larger for bigger catalogues.

Hybrid MF with features (LightFM)

python
from lightfm import LightFM
model = LightFM(no_components=32, loss="warp")
model.fit(interactions, user_features=uf, item_features=itf, epochs=30)

Item features (category, brand, text tags) give new items a representation, which helps cold start.

Practical checks

SymptomLikely cause
barely beats popularitylambda too small, factors too many, low ratings treated as positives
lists identical across usersover-regularised or too few factors; check personalisation
good offline, odd items onlinestale factors, id mapping bugs between training and serving
NaN or exploding values (BPR)learning rate too high; clip or lower it
results vary run to runrandom initialisation: fix seeds, average several runs when comparing
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.