Skip to content

Bayesian probabilistic tensor factorization (BPTF)

BPTF extends BPMF to data with a third dimension: the same users rating the same items in several contexts. Examples are several emotions rated for each image, several questions asked about each trial, or several sessions. What is learned about a user or an item in one context informs predictions in the others.

The model follows Xiong et al. (2010). Their third dimension is time; here it is an unordered set of contexts, and a temporal prior is available on the items instead for time-series data.

How it works

The model

Each user \(i\), item \(j\) and context \(k\) has a vector with \(d\) entries: \(\mathbf{u}_i\), \(\mathbf{v}_j\) and \(\mathbf{t}_k\). A rating is the sum over factors of the product of the three (a CP, or PARAFAC, decomposition; see Kolda & Bader, 2009):

\[ r_{ijk} \mid \cdot \;\sim\; \mathcal{N}\!\left(\sum_{f=1}^{d} u_{if}\, v_{jf}\, t_{kf},\;\; \alpha_k^{-1}\right) \]

A context vector therefore says how strongly each factor is expressed in that context. If two contexts have similar vectors, a user's ratings in one are informative about the other.

The priors are the same as in BPMF. Each of the three sets of vectors is drawn from its own Gaussian, whose mean and precision have Normal-Wishart priors:

\[ \begin{aligned} \mathbf{u}_i &\sim \mathcal{N}\!\left(\boldsymbol{\mu}_U, \boldsymbol{\Lambda}_U^{-1}\right) \\ \mathbf{v}_j &\sim \mathcal{N}\!\left(\boldsymbol{\mu}_V, \boldsymbol{\Lambda}_V^{-1}\right) \\ \mathbf{t}_k &\sim \mathcal{N}\!\left(\boldsymbol{\mu}_T, \boldsymbol{\Lambda}_T^{-1}\right) \end{aligned} \]

Two things differ from the paper:

  • Each context has its own noise precision \(\alpha_k \sim \mathrm{Gamma}(a_0, b_0)\), and ratings are standardized separately within each context, so contexts can be on different scales.
  • Contexts are exchangeable. The paper's third dimension is time, with a prior tying neighbouring time slices together; here contexts are unordered, and the same kind of prior can be put on the items instead.

Fitting

Holding two sets of vectors fixed, the third has the same Gaussian conditional as in the matrix model. For a user, the role of the item vector is played by the elementwise product \(\mathbf{q}_{jk} = \mathbf{v}_j \odot \mathbf{t}_k\):

\[ \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 + \sum_{(j,k) \in \Omega_i} \alpha_k\, \mathbf{q}_{jk} \mathbf{q}_{jk}^\top \\ \mathbf{m}_i &= \mathbf{P}_i^{-1}\!\left(\boldsymbol{\Lambda}_U \boldsymbol{\mu}_U + \sum_{(j,k) \in \Omega_i} \alpha_k\, r_{ijk}\, \mathbf{q}_{jk}\right) \end{aligned} \]

and symmetrically for items and contexts. The sampler cycles through the three sets, their hyperparameters, and the noise precisions. Predictions and uncertainty are computed from the sweeps exactly as for BPMF.

Usage

Data are passed as a dictionary of users x items dataframes, one per context, which must share the same users and items.

import numpy as np
import pandas as pd
from neighbors import BPTF

# Simulated ratings: 40 users x 60 items rated on three related scales
rng = np.random.default_rng(0)
users, items = rng.normal(size=(40, 3)), rng.normal(size=(60, 3))
data = {}
for context, strength in {"happy": [1, 1, 0], "excited": [1, 0.5, 1], "calm": [-1, 0, 1]}.items():
    ratings = 50 + 10 * (users * strength) @ items.T
    data[context] = pd.DataFrame(np.clip(ratings + rng.normal(scale=5, size=ratings.shape), 0, 100))

model = BPTF(data, n_mask_items=0.5, random_state=0)
model.fit()

model.predictions["calm"]    # users x items predictions for one context

Internally, and in every dataframe the model returns (.predictions, .mask, .posterior_std, and so on), the tensor is a single users x (context, item) dataframe with two-level columns. Indexing by a context name gives the users x items table for that context.

model.score_by_context(metric="rmse", dataset="missing")
model.noise_std              # estimated rating noise, one value per context
lower, upper = model.prediction_interval(level=0.95)

Notes:

  • n_mask_items counts (context, item) combinations per user. To hold out a different pattern, such as a whole trial across all contexts, pass your own mask in the same layout as the data.
  • Because contexts can be on different scales, overall metrics from .score() and .summary() mix scales. Prefer .score_by_context().
  • n_factors defaults to 20 (or fewer if there are fewer users or items). One set of factors has to describe every context, so use more factors with many contexts.
  • Dilation, user_noise and slow_features() are not available for BPTF.

Time-series data

When the items are consecutive time-points, such as several emotions rated continuously over the same film, pass temporal_order exactly as for BPMF. The item vectors then follow a random walk over time,

\[ \mathbf{v}_t = \mathbf{v}_{t-1} + \boldsymbol{\epsilon}_t, \qquad \boldsymbol{\epsilon}_t \sim \mathcal{N}\!\left(\mathbf{0},\; \boldsymbol{\Lambda}^{-1}\right) \]

with the step precision \(\boldsymbol{\Lambda}\) learned from the data. The time courses are shared by all contexts: each (user, context) pair is a series over time whose weights on those time courses are \(\mathbf{u}_i \odot \mathbf{t}_k\). A rating in one context at one moment therefore informs both the other contexts and the neighbouring moments.

# 30 users rating 3 emotions over 150 time-points
courses = np.cumsum(rng.normal(size=(150, 3)), axis=0)
people = rng.normal(size=(30, 3))
series = {}
for context, strength in {"happy": [1, 1, 0], "excited": [1, 0.5, 1], "calm": [-1, 0, 1]}.items():
    ratings = 50 + (people * strength) @ courses.T
    series[context] = pd.DataFrame(np.clip(ratings + rng.normal(scale=5, size=ratings.shape), 0, 100))

model = BPTF(series, n_mask_items=0.7, random_state=0)
model.fit(temporal_order=1)

Time-points are assumed to be equally spaced, in column order, and the same in every context.

When to use it over BPMF

Fitting one BPTF is better than fitting a separate BPMF per context when the contexts share structure, and the advantage grows as ratings get sparser. When contexts are unrelated, separate BPMF fits can do slightly better at very high sparsity, because the shared factors then have nothing to share.

References