neighbors.models.BPTF
Bayesian probabilistic tensor factorization extends BPMF to data with a third dimension: the same users rating the same items in several contexts, e.g. several emotions, several questions about each stimulus, or several sessions. Each rating is modeled as a sum over factors of the product of a user, an item, and a context loading (a CP decomposition), so what is learned about a user or item in one context informs predictions in the others.
Data are passed as a dictionary of users x items dataframes, one per context, which must all share the same users and items. Internally, and in every dataframe the model returns (.predictions, .mask, .posterior_std, etc), the tensor is laid out as a single users x (context, item) dataframe with two-level columns. This keeps masking, scoring, and plotting identical to the other models. Use .predictions[context] to get the users x items predictions for one context.
Ratings are standardized separately within each context and each context has its own noise level, so contexts can be on different scales. Because of that, overall error metrics from .score() and .summary() mix scales; prefer .score_by_context().
The implementation follows Xiong et al., 2010: https://www.cs.cmu.edu/~jgc/publication/PublicationPDF/Temporal_Collaborative_Filtering_With_Bayesian_Probabilidtic_Tensor_Factorization.pdf, without their temporal smoothness prior. Dilation is not supported.
Source code in neighbors/models.py
class BPTF(BPMF):
"""
Bayesian probabilistic tensor factorization extends `BPMF` to data with a third dimension: the same users rating the same items in several *contexts*, e.g. several emotions, several questions about each stimulus, or several sessions. Each rating is modeled as a sum over factors of the product of a user, an item, and a context loading (a CP decomposition), so what is learned about a user or item in one context informs predictions in the others.
Data are passed as a dictionary of users x items dataframes, one per context, which must all share the same users and items. Internally, and in every dataframe the model returns (`.predictions`, `.mask`, `.posterior_std`, etc), the tensor is laid out as a single users x (context, item) dataframe with two-level columns. This keeps masking, scoring, and plotting identical to the other models. Use `.predictions[context]` to get the users x items predictions for one context.
Ratings are standardized separately within each context and each context has its own noise level, so contexts can be on different scales. Because of that, overall error metrics from `.score()` and `.summary()` mix scales; prefer `.score_by_context()`.
The implementation follows Xiong et al., 2010: https://www.cs.cmu.edu/~jgc/publication/PublicationPDF/Temporal_Collaborative_Filtering_With_Bayesian_Probabilidtic_Tensor_Factorization.pdf, without their temporal smoothness prior. Dilation is not supported.
"""
def __init__(
self, data, mask=None, n_mask_items=None, verbose=True, random_state=None
):
"""
Args:
data (dict/pd.DataFrame): dictionary of users x items dataframes keyed by context, or a single users x (context, item) dataframe with two-level columns
mask (dict/pd.DataFrame, optional): boolean mask(s) in the same layout as data, used to split the data into 'observed' and 'missing' datasets. Defaults to None.
n_mask_items (int/float, optional): number of (context, item) combinations to mask out per user, while the rest are treated as observed; Defaults to None.
random_state (None, int, RandomState): a seed or random state used for all internal random operations, including the sampler. Passing None will generate a new random seed. Default None.
verbose (bool; optional): print any initialization warnings; Default True
"""
data = self._to_wide(data, "data")
if mask is not None:
mask = self._to_wide(mask, "mask")
if not (
mask.columns.equals(data.columns) and mask.index.equals(data.index)
):
raise ValueError(
"mask must have the same users, contexts, and items as data"
)
super().__init__(
data, mask, n_mask_items, random_state=random_state, verbose=verbose
)
self.contexts = list(data.columns.levels[0])
self.n_contexts = len(self.contexts)
self.n_items = data.shape[1] // self.n_contexts
self.context_vecs = None
@staticmethod
def _to_wide(data, name):
"""Validate a dict of users x items dataframes, or an already-wide dataframe, and return a users x (context, item) dataframe sorted by context then item"""
if isinstance(data, dict):
if not all(isinstance(elem, pd.DataFrame) for elem in data.values()):
raise ValueError(
f"every value in the {name} dictionary must be a pandas dataframe"
)
first = next(iter(data.values()))
for context, elem in data.items():
if not elem.index.equals(first.index) or set(elem.columns) != set(
first.columns
):
raise ValueError(
f"context {context!r} does not have the same users and items as the other contexts in {name}"
)
data = pd.concat(data, axis=1)
if not isinstance(data, pd.DataFrame) or data.columns.nlevels != 2:
raise ValueError(
f"{name} must be a dictionary of users x items dataframes or a dataframe with (context, item) columns"
)
data = data.sort_index(axis=1)
data.columns = data.columns.remove_unused_levels()
contexts, items = data.columns.levels
if not data.columns.equals(pd.MultiIndex.from_product([contexts, items])):
raise ValueError(
f"every context in {name} must contain every item exactly once"
)
data.columns.names = ["Context", data.columns.names[1] or "Item"]
return data
def __repr__(self):
return f"{super().__repr__()[:-1]}, n_contexts={self.n_contexts})"
def fit(
self,
n_factors=None,
n_samples=200,
burn_in=100,
verbose=False,
dilate_by_nsamples=None,
clip_predictions=True,
clip_range=None,
temporal_order=None,
**kwargs,
):
"""
Fit a Bayesian probabilistic tensor factorization model using Gibbs sampling.
Args:
n_factors (int, optional): number of factors to learn. Defaults to None which uses 20, or the number of users or items if either is smaller. The default is larger than for `BPMF` because the same factors have to describe every context. Too few factors is the main way this model underperforms fitting each context separately, so if in doubt use more.
n_samples (int, optional): number of posterior samples to average over. Defaults to 200.
burn_in (int, optional): number of initial sweeps to discard before collecting samples. Defaults to 100.
verbose (bool, optional): print information about sampling. Defaults to False.
dilate_by_nsamples (None): not supported; present for consistency with other models.
clip_predictions (bool, optional): clip predictions to the rating range. Defaults to True.
clip_range (tuple, optional): explicit (min, max) bounds to clip every context to. Defaults to None which uses the min and max of the observed (training) ratings within each context.
temporal_order (int, optional): for data whose items are equally spaced time-points, e.g. several emotions rated continuously over the same film. 1 gives neighbouring time-points similar factors (a random walk); 2 makes factors change at a similar rate from one time-point to the next, which is smoother. The time courses are shared by all contexts and the amount of smoothing is learned from the data. Defaults to None which treats items as exchangeable.
"""
# Call parent fit which acts as a guard for non-masked data
Base.fit(self)
if dilate_by_nsamples is not None:
raise NotImplementedError("BPTF does not support dilation")
n_users, n_contexts, n_items = self.n_users, self.n_contexts, self.n_items
self.temporal_order = temporal_order
if isinstance(n_factors, (float, np.floating)) or (
isinstance(n_factors, (int, np.integer))
and (n_factors < 1 or (n_factors > n_items and n_factors > n_users))
):
raise TypeError(
"n_factors must be a positive integer < number of items and users"
)
for name, value in [("n_samples", n_samples), ("burn_in", burn_in)]:
if not isinstance(value, (int, np.integer)) or value < (
1 if name == "n_samples" else 0
):
raise ValueError(
f"{name} must be a non-negative integer (n_samples > 0)"
)
if n_factors is None:
n_factors = min([20, n_users, n_items])
self.n_factors = n_factors
self.n_samples = n_samples
self.burn_in = burn_in
self._set_clipping(clip_predictions, clip_range)
# Columns are sorted by context then item, so the wide layout reshapes directly to users x contexts x items
shape = (n_users, n_contexts, n_items)
X = self.masked_data.to_numpy(dtype=np.float64).reshape(shape)
M = np.isfinite(X)
if not M.any(axis=(0, 2)).all():
raise ValueError("every context needs at least one observed rating")
# Standardize within context so contexts on different scales contribute equally
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=RuntimeWarning)
center = np.nanmean(X, axis=(0, 2), keepdims=True)
scale = np.nanstd(X, axis=(0, 2), keepdims=True)
scale[scale == 0] = 1.0
R = np.where(M, (X - center) / scale, 0.0)
out = bptf_gibbs(
R,
M.astype(np.float64),
n_factors,
n_samples,
burn_in,
self.random_state,
verbose=verbose,
temporal_order=temporal_order,
)
def to_frame(arr):
return pd.DataFrame(
arr.reshape(n_users, -1),
index=self.data.index,
columns=self.data.columns,
)
# Save outputs to model, converting back to each context's rating scale
self.user_vecs, self.item_vecs = out["U"], out["V"].T
self.context_vecs = pd.DataFrame(out["T"], index=self.contexts)
self._pred_mean = (out["pred_mean"] * scale + center).reshape(n_users, -1)
self.noise_std = pd.Series(
np.sqrt(out["noise_var"]) * scale.ravel(), index=self.contexts
)
# Contexts can be on different scales, so training error is tracked in standardized units
self.error_history = out["rmse_history"]
self._norm_rmse = np.sqrt(np.mean((out["pred_mean"] - R)[M] ** 2))
self.converged = None
self.posterior_std = to_frame(np.sqrt(out["pred_var"]) * scale)
noise_var = out["noise_var"][None, :, None]
self.predictive_std = to_frame(np.sqrt(out["pred_var"] + noise_var) * scale)
self._predict()
self.is_fit = True
def _clip_predictions(self, predictions):
"""Clip predictions to `self.clip_range` if set, otherwise to the range of the observed (training) ratings within each context."""
if self.clip_range is not None:
return np.clip(predictions, *self.clip_range)
observed = self.data[self.mask]
lo = observed.T.groupby(level=0).min().min(axis=1).to_numpy()
hi = observed.T.groupby(level=0).max().max(axis=1).to_numpy()
return np.clip(
predictions, np.repeat(lo, self.n_items), np.repeat(hi, self.n_items)
)
def score_by_context(self, metric="rmse", dataset="missing", actual=None):
"""
Score each context separately. Each score is the mean over users of that user's score within the context.
Args:
metric (str; optional): one of 'rmse', 'mse', 'mae' or 'correlation'; Default 'rmse'.
dataset (str; optional): one of 'observed', 'missing' or 'full'. Default 'missing'.
actual (dict/pd.DataFrame, None; optional): data to score against in the same layout as the input data; Default is None which uses the data provided when the model was initialized
Returns:
pd.Series: one score per context
"""
if not self.is_fit:
raise ValueError("You must fit() model first before using this method.")
model_actual, pred = self._retrieve_predictions(dataset)
actual = model_actual if actual is None else self._to_wide(actual, "actual")
if actual is None:
raise ValueError(
"Cannot score predictions on missing values because no ground truth was observed"
)
scores = {}
for context in self.contexts:
a, p = actual[context].to_numpy(), pred[context].to_numpy()
error = p - a
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=RuntimeWarning)
if metric == "rmse":
by_user = np.sqrt(np.nanmean(error**2, axis=1))
elif metric == "mse":
by_user = np.nanmean(error**2, axis=1)
elif metric == "mae":
by_user = np.nanmean(np.abs(error), axis=1)
elif metric == "correlation":
by_user = (
pd.DataFrame(a).corrwith(pd.DataFrame(p), axis=1).to_numpy()
)
else:
raise ValueError(
"metric must be one of 'rmse', 'mse', 'mae', or 'correlation'"
)
scores[context] = np.nanmean(by_user)
return pd.Series(scores, name=f"{metric}_{dataset}")
__init__(self, data, mask=None, n_mask_items=None, verbose=True, random_state=None)
special
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data |
dict/pd.DataFrame |
dictionary of users x items dataframes keyed by context, or a single users x (context, item) dataframe with two-level columns |
required |
mask |
dict/pd.DataFrame |
boolean mask(s) in the same layout as data, used to split the data into 'observed' and 'missing' datasets. Defaults to None. |
None |
n_mask_items |
int/float |
number of (context, item) combinations to mask out per user, while the rest are treated as observed; Defaults to None. |
None |
random_state |
None, int, RandomState |
a seed or random state used for all internal random operations, including the sampler. Passing None will generate a new random seed. Default None. |
None |
verbose |
bool; optional |
print any initialization warnings; Default True |
True |
Source code in neighbors/models.py
def __init__(
self, data, mask=None, n_mask_items=None, verbose=True, random_state=None
):
"""
Args:
data (dict/pd.DataFrame): dictionary of users x items dataframes keyed by context, or a single users x (context, item) dataframe with two-level columns
mask (dict/pd.DataFrame, optional): boolean mask(s) in the same layout as data, used to split the data into 'observed' and 'missing' datasets. Defaults to None.
n_mask_items (int/float, optional): number of (context, item) combinations to mask out per user, while the rest are treated as observed; Defaults to None.
random_state (None, int, RandomState): a seed or random state used for all internal random operations, including the sampler. Passing None will generate a new random seed. Default None.
verbose (bool; optional): print any initialization warnings; Default True
"""
data = self._to_wide(data, "data")
if mask is not None:
mask = self._to_wide(mask, "mask")
if not (
mask.columns.equals(data.columns) and mask.index.equals(data.index)
):
raise ValueError(
"mask must have the same users, contexts, and items as data"
)
super().__init__(
data, mask, n_mask_items, random_state=random_state, verbose=verbose
)
self.contexts = list(data.columns.levels[0])
self.n_contexts = len(self.contexts)
self.n_items = data.shape[1] // self.n_contexts
self.context_vecs = None
fit(self, n_factors=None, n_samples=200, burn_in=100, verbose=False, dilate_by_nsamples=None, clip_predictions=True, clip_range=None, temporal_order=None, **kwargs)
Fit a Bayesian probabilistic tensor factorization model using Gibbs sampling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_factors |
int |
number of factors to learn. Defaults to None which uses 20, or the number of users or items if either is smaller. The default is larger than for |
None |
n_samples |
int |
number of posterior samples to average over. Defaults to 200. |
200 |
burn_in |
int |
number of initial sweeps to discard before collecting samples. Defaults to 100. |
100 |
verbose |
bool |
print information about sampling. Defaults to False. |
False |
dilate_by_nsamples |
None |
not supported; present for consistency with other models. |
None |
clip_predictions |
bool |
clip predictions to the rating range. Defaults to True. |
True |
clip_range |
tuple |
explicit (min, max) bounds to clip every context to. Defaults to None which uses the min and max of the observed (training) ratings within each context. |
None |
temporal_order |
int |
for data whose items are equally spaced time-points, e.g. several emotions rated continuously over the same film. 1 gives neighbouring time-points similar factors (a random walk); 2 makes factors change at a similar rate from one time-point to the next, which is smoother. The time courses are shared by all contexts and the amount of smoothing is learned from the data. Defaults to None which treats items as exchangeable. |
None |
Source code in neighbors/models.py
def fit(
self,
n_factors=None,
n_samples=200,
burn_in=100,
verbose=False,
dilate_by_nsamples=None,
clip_predictions=True,
clip_range=None,
temporal_order=None,
**kwargs,
):
"""
Fit a Bayesian probabilistic tensor factorization model using Gibbs sampling.
Args:
n_factors (int, optional): number of factors to learn. Defaults to None which uses 20, or the number of users or items if either is smaller. The default is larger than for `BPMF` because the same factors have to describe every context. Too few factors is the main way this model underperforms fitting each context separately, so if in doubt use more.
n_samples (int, optional): number of posterior samples to average over. Defaults to 200.
burn_in (int, optional): number of initial sweeps to discard before collecting samples. Defaults to 100.
verbose (bool, optional): print information about sampling. Defaults to False.
dilate_by_nsamples (None): not supported; present for consistency with other models.
clip_predictions (bool, optional): clip predictions to the rating range. Defaults to True.
clip_range (tuple, optional): explicit (min, max) bounds to clip every context to. Defaults to None which uses the min and max of the observed (training) ratings within each context.
temporal_order (int, optional): for data whose items are equally spaced time-points, e.g. several emotions rated continuously over the same film. 1 gives neighbouring time-points similar factors (a random walk); 2 makes factors change at a similar rate from one time-point to the next, which is smoother. The time courses are shared by all contexts and the amount of smoothing is learned from the data. Defaults to None which treats items as exchangeable.
"""
# Call parent fit which acts as a guard for non-masked data
Base.fit(self)
if dilate_by_nsamples is not None:
raise NotImplementedError("BPTF does not support dilation")
n_users, n_contexts, n_items = self.n_users, self.n_contexts, self.n_items
self.temporal_order = temporal_order
if isinstance(n_factors, (float, np.floating)) or (
isinstance(n_factors, (int, np.integer))
and (n_factors < 1 or (n_factors > n_items and n_factors > n_users))
):
raise TypeError(
"n_factors must be a positive integer < number of items and users"
)
for name, value in [("n_samples", n_samples), ("burn_in", burn_in)]:
if not isinstance(value, (int, np.integer)) or value < (
1 if name == "n_samples" else 0
):
raise ValueError(
f"{name} must be a non-negative integer (n_samples > 0)"
)
if n_factors is None:
n_factors = min([20, n_users, n_items])
self.n_factors = n_factors
self.n_samples = n_samples
self.burn_in = burn_in
self._set_clipping(clip_predictions, clip_range)
# Columns are sorted by context then item, so the wide layout reshapes directly to users x contexts x items
shape = (n_users, n_contexts, n_items)
X = self.masked_data.to_numpy(dtype=np.float64).reshape(shape)
M = np.isfinite(X)
if not M.any(axis=(0, 2)).all():
raise ValueError("every context needs at least one observed rating")
# Standardize within context so contexts on different scales contribute equally
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=RuntimeWarning)
center = np.nanmean(X, axis=(0, 2), keepdims=True)
scale = np.nanstd(X, axis=(0, 2), keepdims=True)
scale[scale == 0] = 1.0
R = np.where(M, (X - center) / scale, 0.0)
out = bptf_gibbs(
R,
M.astype(np.float64),
n_factors,
n_samples,
burn_in,
self.random_state,
verbose=verbose,
temporal_order=temporal_order,
)
def to_frame(arr):
return pd.DataFrame(
arr.reshape(n_users, -1),
index=self.data.index,
columns=self.data.columns,
)
# Save outputs to model, converting back to each context's rating scale
self.user_vecs, self.item_vecs = out["U"], out["V"].T
self.context_vecs = pd.DataFrame(out["T"], index=self.contexts)
self._pred_mean = (out["pred_mean"] * scale + center).reshape(n_users, -1)
self.noise_std = pd.Series(
np.sqrt(out["noise_var"]) * scale.ravel(), index=self.contexts
)
# Contexts can be on different scales, so training error is tracked in standardized units
self.error_history = out["rmse_history"]
self._norm_rmse = np.sqrt(np.mean((out["pred_mean"] - R)[M] ** 2))
self.converged = None
self.posterior_std = to_frame(np.sqrt(out["pred_var"]) * scale)
noise_var = out["noise_var"][None, :, None]
self.predictive_std = to_frame(np.sqrt(out["pred_var"] + noise_var) * scale)
self._predict()
self.is_fit = True
score_by_context(self, metric='rmse', dataset='missing', actual=None)
Score each context separately. Each score is the mean over users of that user's score within the context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metric |
str; optional |
one of 'rmse', 'mse', 'mae' or 'correlation'; Default 'rmse'. |
'rmse' |
dataset |
str; optional |
one of 'observed', 'missing' or 'full'. Default 'missing'. |
'missing' |
actual |
dict/pd.DataFrame, None; optional |
data to score against in the same layout as the input data; Default is None which uses the data provided when the model was initialized |
None |
Returns:
| Type | Description |
|---|---|
pd.Series |
one score per context |
Source code in neighbors/models.py
def score_by_context(self, metric="rmse", dataset="missing", actual=None):
"""
Score each context separately. Each score is the mean over users of that user's score within the context.
Args:
metric (str; optional): one of 'rmse', 'mse', 'mae' or 'correlation'; Default 'rmse'.
dataset (str; optional): one of 'observed', 'missing' or 'full'. Default 'missing'.
actual (dict/pd.DataFrame, None; optional): data to score against in the same layout as the input data; Default is None which uses the data provided when the model was initialized
Returns:
pd.Series: one score per context
"""
if not self.is_fit:
raise ValueError("You must fit() model first before using this method.")
model_actual, pred = self._retrieve_predictions(dataset)
actual = model_actual if actual is None else self._to_wide(actual, "actual")
if actual is None:
raise ValueError(
"Cannot score predictions on missing values because no ground truth was observed"
)
scores = {}
for context in self.contexts:
a, p = actual[context].to_numpy(), pred[context].to_numpy()
error = p - a
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=RuntimeWarning)
if metric == "rmse":
by_user = np.sqrt(np.nanmean(error**2, axis=1))
elif metric == "mse":
by_user = np.nanmean(error**2, axis=1)
elif metric == "mae":
by_user = np.nanmean(np.abs(error), axis=1)
elif metric == "correlation":
by_user = (
pd.DataFrame(a).corrwith(pd.DataFrame(p), axis=1).to_numpy()
)
else:
raise ValueError(
"metric must be one of 'rmse', 'mse', 'mae', or 'correlation'"
)
scores[context] = np.nanmean(by_user)
return pd.Series(scores, name=f"{metric}_{dataset}")