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

gen_mf_script.py

Helper script for collaborative-filtering-implementer · 211 lines

AI & Machine Learning / Classical Machine Learningv1.0.0Updated OCT 25 20263 references2 scripts
scripts/gen_mf_script.py
#!/usr/bin/env python3
"""Generate a NumPy script that trains implicit ALS, BPR and EASE recommenders, tunes them on a temporal
validation split and writes top-k lists for rec_eval.py.

The script it writes:
  - loads the training interactions (user_id,item_id[,rating][,timestamp]); positives are all interactions,
    or ratings >= --min-rating; implicit counts become confidence weights 1 + alpha * count (ALS)
  - holds out each user's last --val-n positives (by timestamp, else file order) as validation
  - models (all NumPy, no extra dependencies):
      als   implicit ALS (Hu, Koren & Volinsky 2008): alternating exact least squares with confidence
            weights, regularisation lambda, f factors
      bpr   Bayesian personalised ranking (Rendle et al. 2009): SGD on (user, positive, sampled negative)
            triples
      ease  EASE (Steck 2019): closed-form item-item weights B = I - P / diag(P), P = (X'X + lambda I)^-1;
            strong and fast when the catalogue is < ~20k items
  - grid-searches a small set of hyperparameters per model on validation recall@k / NDCG@k, refits the best
    configuration on all training data and writes recs_<model>.csv (and recs_all.csv with a model column)
Needs numpy and pandas.

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

Exit codes: 0 written, 2 usage error.
"""

import argparse
import os
import sys

TEMPLATE = '''"""ALS / BPR / EASE recommenders for {train!r}. Generated by gen_mf_script.py.

Run:  python {script}
Then: python rec_eval.py --recs recs_all.csv --test <test.csv> --train {train} --k {k}{min_rating_flag}
"""
import numpy as np
import pandas as pd

TRAIN, USER, ITEM, RATING, TIME = {train!r}, {user!r}, {item!r}, {rating!r}, {time!r}
MIN_RATING, MODELS, K, VAL_N, SEED = {min_rating!r}, {models!r}, {k}, {val_n}, 0
rng = np.random.default_rng(SEED)

df = pd.read_csv(TRAIN)
seen_all = df.groupby(USER)[ITEM].apply(set).to_dict()
pos = df if MIN_RATING is None else df[df[RATING] >= MIN_RATING]
if TIME in pos.columns:
    pos = pos.sort_values([USER, TIME])
users = sorted(df[USER].unique())
items = sorted(df[ITEM].unique())
uix = {{u: i for i, u in enumerate(users)}}
iix = {{t: i for i, t in enumerate(items)}}
n_users, n_items = len(users), len(items)
weight = pos.groupby([USER, ITEM]).size().rename("w").reset_index()
if MIN_RATING is None and RATING in pos.columns:
    weight = pos.groupby([USER, ITEM])[RATING].sum().rename("w").reset_index()


def matrix(frame):
    X = np.zeros((n_users, n_items))
    for u, i, w in frame[[USER, ITEM, "w"]].itertuples(index=False):
        X[uix[u], iix[i]] = w
    return X


# validation: last VAL_N positives per user (users keep >= 2 positives in train)
val_rows = pos.groupby(USER).tail(VAL_N)
keep = pos.groupby(USER)[ITEM].transform("count") > VAL_N + 1
val_rows = val_rows[keep.loc[val_rows.index]]
fit_rows = pos.drop(val_rows.index)
fit_w = fit_rows.groupby([USER, ITEM]).size().rename("w").reset_index()
val = val_rows.groupby(USER)[ITEM].apply(set).to_dict()
fit_seen = {{u: set(s) - val.get(u, set()) for u, s in seen_all.items()}}


def als(X, f=32, lam=0.1, alpha=10.0, iters=12):
    C = 1 + alpha * X
    P = (X > 0).astype(float)
    U = rng.normal(0, 0.01, (n_users, f))
    V = rng.normal(0, 0.01, (n_items, f))
    I = np.eye(f)
    for _ in range(iters):
        VtV = V.T @ V
        for u in range(n_users):
            cu = C[u]
            A = VtV + (V.T * (cu - 1)) @ V + lam * I
            U[u] = np.linalg.solve(A, (V.T * cu) @ P[u])
        UtU = U.T @ U
        for i in range(n_items):
            ci = C[:, i]
            A = UtU + (U.T * (ci - 1)) @ U + lam * I
            V[i] = np.linalg.solve(A, (U.T * ci) @ P[:, i])
    return U @ V.T


def bpr(X, f=32, lr=0.05, reg=0.01, epochs=60):
    P = X > 0
    U = rng.normal(0, 0.1, (n_users, f))
    V = rng.normal(0, 0.1, (n_items, f))
    us, its = np.nonzero(P)
    for _ in range(epochs):
        order = rng.permutation(len(us))
        for k in order:
            u, i = us[k], its[k]
            j = rng.integers(n_items)
            while P[u, j]:
                j = rng.integers(n_items)
            x = U[u] @ (V[i] - V[j])
            g = 1 / (1 + np.exp(x))
            uu = U[u].copy()
            U[u] += lr * (g * (V[i] - V[j]) - reg * U[u])
            V[i] += lr * (g * uu - reg * V[i])
            V[j] += lr * (-g * uu - reg * V[j])
    return U @ V.T


def ease(X, lam=100.0):
    B_in = (X > 0).astype(float)
    G = B_in.T @ B_in + lam * np.eye(n_items)
    P = np.linalg.inv(G)
    B = -P / np.diag(P)
    np.fill_diagonal(B, 0.0)
    return B_in @ B


GRIDS = {{"als": [dict(f=f, lam=l, alpha=a) for f in (8, 32) for l in (1.0, 10.0, 50.0) for a in (1.0, 10.0, 40.0)],
         "bpr": [dict(f=f, lr=lr) for f in (16, 32) for lr in (0.02, 0.05)],
         "ease": [dict(lam=l) for l in (10.0, 50.0, 200.0, 500.0)]}}
FN = {{"als": als, "bpr": bpr, "ease": ease}}


def topk(S, seen, k):
    out = {{}}
    for u in users:
        s = S[uix[u]].copy()
        for it in seen.get(u, ()):
            s[iix[it]] = -np.inf
        idx = np.argpartition(-s, min(k, n_items - 1))[:k]
        idx = idx[np.argsort(-s[idx])]
        out[u] = [items[i] for i in idx if np.isfinite(s[i])]
    return out


def score(recs, truth, k):
    rec_sum = nd = 0.0
    for u, rel in truth.items():
        lst = recs.get(u, [])[:k]
        h = [1 if it in rel else 0 for it in lst]
        rec_sum += sum(h) / len(rel)
        dcg = sum(x / np.log2(i + 2) for i, x in enumerate(h))
        idcg = sum(1 / np.log2(i + 2) for i in range(min(len(rel), k)))
        nd += dcg / idcg
    return rec_sum / len(truth), nd / len(truth)


X_fit = matrix(fit_w)
X_all = matrix(weight)
all_rows = []
for name in MODELS:
    best = None
    for params in GRIDS[name]:
        S = FN[name](X_fit, **params)
        r, n = score(topk(S, fit_seen, K), val, K)
        print(f"{{name}} {{params}} -> validation recall@{{K}} {{r:.4f}} ndcg@{{K}} {{n:.4f}}")
        if best is None or n > best[0]:
            best = (n, params)
    print(f"best {{name}}: {{best[1]}} (validation ndcg@{{K}} {{best[0]:.4f}})")
    S = FN[name](X_all, **best[1])
    recs = topk(S, seen_all, K)
    rows = [(name, u, it, r + 1) for u, lst in recs.items() for r, it in enumerate(lst)]
    pd.DataFrame(rows, columns=["model", "user_id", "item_id", "rank"]).drop(columns="model").to_csv(
        f"recs_{{name}}.csv", index=False)
    all_rows += rows
pd.DataFrame(all_rows, columns=["model", "user_id", "item_id", "rank"]).to_csv("recs_all.csv", index=False)
print("wrote recs_all.csv and recs_<model>.csv")
'''


def main():
    ap = argparse.ArgumentParser(description="Generate an ALS / BPR / EASE recommender script.", epilog=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--train", required=True)
    ap.add_argument("--user-col", default="user_id")
    ap.add_argument("--item-col", default="item_id")
    ap.add_argument("--rating-col", default="rating")
    ap.add_argument("--time-col", default="timestamp")
    ap.add_argument("--min-rating", type=float, help="explicit data: ratings >= this are positives")
    ap.add_argument("--models", nargs="+", choices=["als", "bpr", "ease"], default=["als", "bpr", "ease"])
    ap.add_argument("--k", type=int, default=10)
    ap.add_argument("--val-n", type=int, default=1, help="validation positives per user")
    ap.add_argument("-o", "--output")
    a = ap.parse_args()
    if a.k < 1 or a.val_n < 1:
        print("error: --k and --val-n must be >= 1", file=sys.stderr)
        return 2
    text = TEMPLATE.format(train=a.train, user=a.user_col, item=a.item_col, rating=a.rating_col, time=a.time_col,
                           min_rating=a.min_rating, models=a.models, k=a.k, val_n=a.val_n,
                           min_rating_flag=f" --min-rating {a.min_rating:g}" if a.min_rating is not None else "",
                           script=os.path.basename(a.output or "mf.py"))
    if a.output:
        with open(a.output, "w", encoding="utf-8") as f:
            f.write(text)
        print(f"wrote {a.output}: {', '.join(a.models)}, k={a.k}", file=sys.stderr)
    else:
        sys.stdout.write(text)
    return 0


if __name__ == "__main__":
    sys.exit(main())
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.