Bayesian probabilistic matrix factorization (BPMF)
BPMF is a matrix factorization model that is fully Bayesian: instead of finding one best set of user and item factors, it averages predictions over many plausible sets. In practice that gives three things the NNMF models do not have:
- No regularization to tune. The strength of the regularization is learned from the data.
- An uncertainty estimate for every prediction, not just a predicted value.
- Robustness to the number of factors. Surplus factors are shrunk by the priors, so using many costs time rather than accuracy.
The model follows Salakhutdinov & Mnih (2008), with two changes described below.
How it works
The model
Each user \(i\) has a vector \(\mathbf{u}_i \in \mathbb{R}^d\) and each item \(j\) has a vector \(\mathbf{v}_j \in \mathbb{R}^d\), where \(d\) is the number of factors. A rating is their inner product plus Gaussian noise with precision \(\alpha\):
User vectors are drawn from a shared Gaussian, and so are item vectors:
This is the regularization: a user with few ratings stays close to the average user \(\boldsymbol{\mu}_U\). The key step is that these means and precisions are not fixed. They get Normal-Wishart priors and are estimated along with everything else:
and likewise for the items. The noise precision has a Gamma prior, \(\alpha \sim \mathrm{Gamma}(a_0, b_0)\). The package uses \(\boldsymbol{\mu}_0 = \mathbf{0}\), \(\mathbf{W}_0 = \mathbf{I}\), \(\nu_0 = d\), \(\beta_0 = 2\) and \(a_0 = b_0 = 1\).
Because the means \(\boldsymbol{\mu}_U\) and \(\boldsymbol{\mu}_V\) are not zero, they play the role of bias terms: \(\boldsymbol{\mu}_U^\top \mathbf{v}_j\) is the typical rating of item \(j\).
Fitting by Gibbs sampling
There is no closed form for all the unknowns at once, but each has a simple distribution when the others are held fixed. One sweep of the sampler draws, in turn:
- \(\boldsymbol{\mu}_U, \boldsymbol{\Lambda}_U\) given the current user vectors (a Normal-Wishart draw).
-
Every user vector given the item vectors and that user's ratings. With \(\Omega_i\) the set of items user \(i\) rated,
\[ \begin{aligned} \mathbf{u}_i \mid \cdot \;&\sim\; \mathcal{N}\!\left(\mathbf{m}_i,\; \mathbf{P}_i^{-1}\right) \\ \mathbf{P}_i &= \boldsymbol{\Lambda}_U + \alpha \sum_{j \in \Omega_i} \mathbf{v}_j \mathbf{v}_j^\top \\ \mathbf{m}_i &= \mathbf{P}_i^{-1}\!\left(\boldsymbol{\Lambda}_U \boldsymbol{\mu}_U + \alpha \sum_{j \in \Omega_i} r_{ij}\, \mathbf{v}_j\right) \end{aligned} \] -
The same two steps for the items.
-
The noise precision given the residuals over the \(N\) observed ratings:
\[ \alpha \mid \cdot \;\sim\; \mathrm{Gamma}\!\left(a_0 + \tfrac{N}{2},\;\; b_0 + \tfrac{1}{2} \sum_{(i,j)\ \mathrm{observed}} \left(r_{ij} - \mathbf{u}_i^\top \mathbf{v}_j\right)^2\right) \]
After burn_in sweeps are discarded, each of the next n_samples sweeps \(s = 1, \dots, S\) gives one plausible version of the whole model.
Predictions and uncertainty
The prediction for every cell is the average over sweeps, and the uncertainty is how much the sweeps disagree:
.predictionsholds \(\hat{r}_{ij}\)..posterior_stdis the uncertainty about the underlying rating, with rating noise removed..predictive_stdadds the estimated rating noise. It describes where an actual rating would fall, and is the one to compare against held-out ratings.
Differences from the original paper
- The noise precision is sampled. The paper fixes \(\alpha\), which only works on a known rating scale.
- Ratings are standardized internally and predictions converted back, so the priors mean the same thing whether ratings run from 0 to 1 or 0 to 100.
Usage
import numpy as np
import pandas as pd
from neighbors import BPMF
# Simulated ratings on a 0-100 scale: 50 users x 100 items
rng = np.random.default_rng(0)
ratings = 50 + 10 * rng.normal(size=(50, 3)) @ rng.normal(size=(3, 100))
data = pd.DataFrame(np.clip(ratings + rng.normal(scale=5, size=ratings.shape), 0, 100))
# Hold out half of each user's ratings so there is something to predict
model = BPMF(data, n_mask_items=0.5, random_state=0)
model.fit()
model.predictions # users x items dataframe
model.summary(dataset="missing")
fit() needs no tuning in most cases. The arguments that matter:
n_factors: defaults to all factors (the smaller of the number of users and items), capped at 50. More is rarely harmful; the cost of a sweep grows with the cube of this number.n_samplesandburn_in: number of sweeps kept and discarded. Defaults are 200 and 100.clip_predictionsandclip_range: as for theNNMFmodels.
Uncertainty
model.predictive_std # users x items, uncertainty about an actual rating
model.posterior_std # users x items, uncertainty about the underlying rating
model.noise_std # estimated rating noise, on the rating scale
lower, upper = model.prediction_interval(level=0.95)
# Share of held-out ratings that fall inside their 95% interval
held_out = ~model.mask
inside = (model.data >= lower) & (model.data <= upper)
coverage = inside.values[held_out.values].mean()
Use prediction_interval(kind="posterior") for an interval on the underlying rating. With many more factors than the data support, surplus factors absorb some rating noise, which makes the posterior interval too wide and the noise estimate too small. The default predictive interval is not affected.
Extensions
A noise level for each user
By default every user is assumed to rate with the same amount of noise. With user_noise=True each user gets their own precision \(\alpha_i\), drawn from a group-level distribution whose parameters are also learned:
This is a random-effects treatment of noise: a user with few ratings is pulled toward the group, and the amount of pulling is learned through \(a\) and \(b\). Noisier users then count for less when the item vectors are updated, and get wider intervals.
model = BPMF(data, n_mask_items=0.5, random_state=0)
model.fit(user_noise=True)
model.user_noise_std # one value per user, on the rating scale
user_noise_std is useful in its own right as a per-user reliability estimate.
Time-series data: a temporal prior
When the items are consecutive time-points, such as continuous ratings of a film, neighbouring columns are not exchangeable. The other models handle this by dilating the observed ratings. BPMF can instead replace the prior on the item vectors with a random walk over time, in the spirit of the dynamic factor models of Xiong et al. (2010) and Chen & Sun (2021):
The step precision \(\boldsymbol{\Lambda}\) is sampled, so the amount of smoothing is learned and there is no kernel width to choose. temporal_order=2 applies the same prior to second differences, \(\mathbf{v}_t - 2\mathbf{v}_{t-1} + \mathbf{v}_{t-2} = \boldsymbol{\epsilon}_t\), which gives smoother trajectories.
Writing \(\mathbf{D}\) for the matrix that takes differences over time and \(\mathbf{K} = \mathbf{D}^\top \mathbf{D}\), all time-points are drawn jointly from a Gaussian with precision
Each time-point is tied only to its nearest neighbours, so this matrix is banded and the draw uses a banded Cholesky factorization. Although only neighbours are tied directly, the ties chain, so a rating informs predictions many time-points away, with influence that fades at the learned rate.
# Simulated continuous ratings: 30 users x 200 time-points that drift smoothly
courses = np.cumsum(rng.normal(size=(200, 3)), axis=0)
ts = 50 + rng.normal(size=(30, 3)) @ courses.T
ts = pd.DataFrame(np.clip(ts + rng.normal(scale=5, size=ts.shape), 0, 100))
model = BPMF(ts, n_mask_items=0.5, random_state=0)
model.fit(temporal_order=1)
Notes:
- Time-points are assumed to be equally spaced and in column order.
- It is an alternative to
dilate_by_nsamples, not something to combine with it. Dilation copies ratings into neighbouring time-points and treats the copies as real, which makes the intervals too narrow. The temporal prior creates no extra data and its intervals stay calibrated. - A fit is several times slower than without the prior.
- Time series usually need many factors. Do not reduce
n_factorswithout checking held-out error.
Timescales: slow feature analysis
The individual factors of a matrix factorization cannot be interpreted, because they can be mixed without changing any prediction. For time-series fits, slow_features() gives a summary that does not have this problem. It re-expresses the predicted curves as uncorrelated, unit-variance time courses ordered from slowest to fastest, using slow feature analysis (Wiskott & Sejnowski, 2002).
With \(\mathbf{z}_t\) the whitened time courses spanning the predicted curves, the slow features are \(\mathbf{y}_t = \mathbf{R}^\top \mathbf{z}_t\), where the columns of \(\mathbf{R}\) are the eigenvectors of the covariance of the steps \(\mathbf{z}_t - \mathbf{z}_{t-1}\), ordered by increasing eigenvalue \(\delta_k\). For a unit-variance series the mean squared step and the correlation between neighbouring time-points \(\rho_k\) are related by \(\delta_k = 2(1 - \rho_k)\), which gives each component a timescale
the number of time-points over which that correlation decays to \(1/e\).
out = model.slow_features()
out["features"] # time-points x components, slowest first
out["components"] # autocorrelation, timescale and share of variance per component
out["weights"] # users x components
out["users"] # per-user autocorrelation, timescale and slow_share
The users table describes how slowly each user's own predicted curve changes, which can be used as an individual-difference measure. Two cautions: a timescale longer than the series means "a trend across the whole series" and is not a precise number, and a user's timescale can be dominated by a few large changes, so look at their curve before interpreting it.
References
- Salakhutdinov, R., & Mnih, A. (2008). Bayesian probabilistic matrix factorization using Markov chain Monte Carlo. Proceedings of the 25th International Conference on Machine Learning, 880–887.
- Xiong, L., Chen, X., Huang, T.-K., Schneider, J., & Carbonell, J. G. (2010). Temporal collaborative filtering with Bayesian probabilistic tensor factorization. Proceedings of the 2010 SIAM International Conference on Data Mining, 211–222.
- Chen, X., & Sun, L. (2021). Bayesian temporal factorization for multidimensional time series prediction. IEEE Transactions on Pattern Analysis and Machine Intelligence, 44(9), 4659–4673.
- Wiskott, L., & Sejnowski, T. J. (2002). Slow feature analysis: Unsupervised learning of invariances. Neural Computation, 14(4), 715–770.