pip install cmfrec★Ships bothfloat32&float64builds; needs a C compiler.pip install --no-use-pep517 cmfrecFallback if the standard build fails.from cmfrec import CMF, CMF_implicit★The two workhorse classes.export DONT_SET_MARCH=1Portable wheel: drop-march=nativebefore install.brew install libompmacOS: enable multi-threading, then reinstall.
CMF★Explicit ratings (1–5). Most flexible; add U/I side info.CMF_implicit★Implicit clicks/plays. Weighted-binary; no biases.ContentBasedPure content model — factors are a direct map of attributes.OMF_explicit / OMF_implicitOffsets model: attributes + a free offset. Better cold-start.MostPopularNon-personalized baseline (biases only). Sanity benchmark.CMF_imputer / CMF_embedderscikit-learn subclasses for imputation / embeddings.
X = df["UserId","ItemId","Rating"]★Explicit long-format table; IDs may be strings.X = df["UserId","ItemId","Value"]Implicit uses aValuecolumn (counts/weights).X = scipy.sparse.coo_matrix(...)Fastest input; skips internal reindexing.U, I = user_df, item_dfSide info; carry aUserId/ItemIdcolumn if X is a DF.arr[i, j] = np.nanDense inputs: unobserved entries must beNaN.W = weightsOptional per-observation weights (explicit models).
m = CMF(k=40, method="als")★Construct with hyperparameters.m.fit(X=X, U=U, I=I)★Train on interactions + optional side info.m.fit(X, W=W)Weighted fit;Wmatches X's shape/nnz.m.fit(X, U_bin=Ub)Binary side info — only withmethod="lbfgs".m.A_, m.B_, m.C_, m.D_Learned factor matrices after fitting.m.glob_mean_, m.user_bias_Global mean & per-row biases (explicit).
m.predict(user=[3,3], item=[2,4])★Existing user/item, element-wise pairs.m.predict_warm(items, X_col=, X_val=)Warm: new user defined by fresh ratings.m.predict_cold(items, U=u)Cold: new user from attributes only, no X.m.predict_new(user, I=i)New items scored from item attributes.m.predict_warm_multiple(X, item)Batch version across many new users.
m.topN(user=3, n=10)★Bestnitems for an existing user.m.topN_warm(n=, X_col=, X_val=)★Rank for a new user from their new ratings.m.topN_cold(n=, U=u)Rank for a new user from attributes alone.m.topN_new(user, I=i, n=)Rank a set of brand-new items for a user.m.topN(3, exclude=seen, output_score=True)Drop already-seen items; also return scores.m.topN(3, include=candidates)Rank only within a candidate shortlist.
m.factors_warm(X_col=, X_val=)Factor vector for a new user from ratings.m.factors_cold(U=u)Factor vector from attributes only.m.factors_multiple(X=, U=)Batch factors for many rows at once.m.factors_warm(..., return_bias=True)Also hand back the estimated user bias.m.item_factors_cold(I=i)slowItem factors are un-precomputed — prefer swapping.
k=40★Shared latent dimensions. Typical 30–100.lambda_=10.0★L2 regularization — absolute, not per-entry. Tune wide.method="als"als= fast;lbfgs= better optima + binary side info.niter=10ALS rounds. Typical 6–30; more = better fit.use_cg=TrueConjugate-gradient ALS: fast;False= exact Cholesky.lambda_=[bu,bi,A,B,C,D]Per-matrix regularization as a 6-vector.
alpha=1.0★Confidence weight on positives:W = 1 + alpha·X.lambda_=1.0Higher default than explicit; e.g. ~5 for LastFM-360K.w_user=10., w_item=10.Up-weight side info — X's dense zeros dominate otherwise.apply_log_transf=TrueLog-scale raw counts before fitting.from recometrics import ...Companion lib for P@K / MAP / hit-rate metrics.
k=40Shared across X, U and I — the coupling.k_user=0Extra dims used only by U (in A & C).k_item=0Extra dims used only by I (in B & D).k_main=0Extra dims used only by X (in A & B).w_main=1., w_user=, w_item=Loss weight per matrix — who wins on conflict.
scale_lam=TruePer-row regularization — then use a much smallerlambda_(~0.05).add_implicit_features=TrueFree implicit signal from the same X; helps small data.nonneg=TrueNMF-style non-negative factors (turn off centering).NA_as_zero=TrueTreat sparse missing as 0 — for dim-reduction / speed.l1_lambda=0.0L1 sparsity (coordinate descent — slower).use_float=Truefloat32: faster & leaner, less precise.
m.transform(X)Reconstruct all missing entries of X (imputation).CMF_imputer()Drop-in scikit-learn imputer step.CMF_embedder()Emit the A-factors as features for a Pipeline.m.user_mapping_, m.item_mapping_Internal↔original ID maps (DataFrame inputs).m.get_params() / m.set_params()sklearn-compatible —set_paramsresets the fit.
m.drop_nonessential_matrices()Shrink for serving; keepsfactors_*/topN_*.m.swap_users_and_items()★Make item-side ops (item cold-start) fast.CMF.from_model_matrices(A, B)Wrap externally-trained factors into a cmfrec model.precompute_for_predictions=FalseFaster/leaner fit; recompute later on demand.# ANN over A · BFor big catalogs, serve top-N via hnsw / Milvus.
df = df.copy()mutatesfitreindexes input in place — copy first.CMF on click datawrongUseCMF_implicitfor implicit feedback & P@K.lambda_ like other libsoff-scalecmfrec'slambda_is absolute — often 10–100× larger.U_bin with method="als"n/aBinary side info + sigmoid needmethod="lbfgs".topN on huge catalogfull scantopNscores every item — use ANN in production.
existinguser/item was in the training data.warmnew X ratings for prediction (fresh history).coldnew user from U attributes, no ratings.newnew items scored from I attributes.X · U · Iinteractions · user attrs · item attrs.A · B · C · Duser · item · user-attr · item-attr factors.