Skip to content

neighbors.models.BPMF

Bayesian probabilistic matrix factorization decomposes a users x items matrix into user and item factors like the NNMF models, but places priors on the factors and averages predictions over posterior samples instead of returning a single point estimate.

This has two practical consequences. The amount of regularization is learned from the data, so there are no regularization hyper-parameters to tune and fitting more factors than the data support is far less harmful. And every prediction comes with an uncertainty estimate, available after fitting in .posterior_std, .predictive_std, and via .prediction_interval().

Training is performed via Gibbs sampling following Salakhutdinov & Mnih, 2008: https://www.cs.toronto.edu/~amnih/papers/bpmf.pdf, with two differences: ratings are standardized internally, and the observation noise is sampled rather than fixed so the model adapts to any rating scale.

Note: the uncertainty estimates assume every training rating is an independent observation. Fitting with dilate_by_nsamples breaks that assumption, because dilation fills in neighbouring time-points with copies of the observed ratings. Predictions still benefit from dilation, but the intervals become too narrow, increasingly so with larger dilation.

Unlike the NNMF models, factors are not constrained to be non-negative, random_state fully controls the fit, and there is no convergence criterion: the sampler always runs burn_in + n_samples sweeps.

Source code in neighbors/models.py
class BPMF(BaseNMF):
    """
    Bayesian probabilistic matrix factorization decomposes a users x items matrix into user and item factors like the `NNMF` models, but places priors on the factors and averages predictions over posterior samples instead of returning a single point estimate.

    This has two practical consequences. The amount of regularization is learned from the data, so there are no regularization hyper-parameters to tune and fitting more factors than the data support is far less harmful. And every prediction comes with an uncertainty estimate, available after fitting in `.posterior_std`, `.predictive_std`, and via `.prediction_interval()`.

    Training is performed via Gibbs sampling following Salakhutdinov & Mnih, 2008: https://www.cs.toronto.edu/~amnih/papers/bpmf.pdf, with two differences: ratings are standardized internally, and the observation noise is sampled rather than fixed so the model adapts to any rating scale.

    **Note**: the uncertainty estimates assume every training rating is an independent observation. Fitting with `dilate_by_nsamples` breaks that assumption, because dilation fills in neighbouring time-points with copies of the observed ratings. Predictions still benefit from dilation, but the intervals become too narrow, increasingly so with larger dilation.

    Unlike the `NNMF` models, factors are not constrained to be non-negative, `random_state` fully controls the fit, and there is no convergence criterion: the sampler always runs `burn_in + n_samples` sweeps.
    """

    def __init__(
        self, data, mask=None, n_mask_items=None, verbose=True, random_state=None
    ):
        """
        Args:
            data (pd.DataFrame): users x items dataframe
            mask (pd.DataFrame, optional): A boolean dataframe used to split the data into 'observed' and 'missing' datasets. Defaults to None.
            n_mask_items (int/float, optional): number of items to mask out, 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

        """
        super().__init__(
            data, mask, n_mask_items, random_state=random_state, verbose=verbose
        )
        self.n_factors = None
        self.posterior_std = None
        self.predictive_std = None

    def __repr__(self):
        return f"{super().__repr__()[:-1]}, n_factors={self.n_factors})"

    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,
        user_noise=False,
        **kwargs,
    ):
        """
        Fit a Bayesian probabilistic matrix factorization model using Gibbs sampling.

        Args:
            n_factors (int, optional): number of factors to learn. Defaults to None which, like the `NNMF` models, uses all factors (the smaller of the number of users and items), but capped at 50 because the cost of each sweep grows with the cube of the number of factors. Surplus factors are shrunk by the priors, so they cost time rather than accuracy.
            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 (int, optional): How many items to dilate by prior to training. Defaults to None.
            clip_predictions (bool, optional): clip predictions to the rating range. Defaults to True.
            clip_range (tuple, optional): explicit (min, max) bounds to clip to, e.g. the full rating scale. Defaults to None which uses the min and max of the observed (training) ratings.
            temporal_order (int, optional): for time-series data whose items are equally spaced time-points. 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 amount of smoothing is learned from the data. This is an alternative to `dilate_by_nsamples` that does not create extra training data. Defaults to None which treats items as exchangeable.
            user_noise (bool, optional): learn a separate noise level for every user rather than one shared value. Each user's noise is estimated as a deviation from a group-level distribution, so users with few ratings are pulled toward the group. Users with noisier ratings then count for less when learning about items, and their predictions get wider intervals. Per-user estimates are available afterwards in `.user_noise_std`. Defaults to False.
        """

        # Call parent fit which acts as a guard for non-masked data
        super().fit()

        n_users, n_items = self.data.shape

        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([50, 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)

        # Perform dilation if requested
        self.dilate_mask(n_samples=dilate_by_nsamples)

        # Standardize the training ratings so the priors mean the same thing on any rating scale
        X = self.masked_data.to_numpy(dtype=np.float64)
        M = np.isfinite(X)
        self._center = X[M].mean()
        scale = X[M].std()
        self._scale = scale if scale > 0 else 1.0
        R = np.where(M, (X - self._center) / self._scale, 0.0)

        self.temporal_order = temporal_order

        out = bpmf_gibbs(
            R,
            M.astype(np.float64),
            n_factors,
            n_samples,
            burn_in,
            self.random_state,
            verbose=verbose,
            temporal_order=temporal_order,
            user_noise=user_noise,
        )

        # Save outputs to model, converting back to the original rating scale
        # Factors are oriented like NNMF_sgd: user x factor, factor x item
        self.user_vecs, self.item_vecs = out["U"], out["V"].T
        self._pred_mean = out["pred_mean"] * self._scale + self._center
        self.noise_std = np.sqrt(np.mean(out["noise_var"])) * self._scale
        self.user_noise_std = (
            pd.Series(
                np.sqrt(out["noise_var"]) * self._scale,
                index=self.data.index,
                name="noise_std",
            )
            if user_noise
            else None
        )
        self.noise_precision_history = out["alpha_history"]
        self.error_history = out["rmse_history"] * self._scale / self.data_range
        train_error = (self._pred_mean - X)[M]
        self._norm_rmse = np.sqrt(np.mean(train_error**2)) / self.data_range
        # There is no convergence criterion for a sampler; inspect .plot_learning() instead
        self.converged = None

        posterior_std = np.sqrt(out["pred_var"]) * self._scale
        noise_var = np.reshape(out["noise_var"], (-1, 1))
        predictive_std = np.sqrt(out["pred_var"] + noise_var) * self._scale
        self.posterior_std = pd.DataFrame(
            posterior_std, index=self.data.index, columns=self.data.columns
        )
        self.predictive_std = pd.DataFrame(
            predictive_std, index=self.data.index, columns=self.data.columns
        )

        if verbose:
            print(f"\n\tFinal Norm Error: {np.round(100 * self._norm_rmse, 2)}%")
            print(f"\tEstimated noise SD: {np.round(self.noise_std, 3)}")

        self._predict()
        self.is_fit = True

    def _predict(self):
        """Predict users' missing items using the posterior mean over Gibbs samples"""

        predictions = self._pred_mean
        if self.clip_predictions:
            predictions = self._clip_predictions(predictions)
        self.predictions = pd.DataFrame(
            predictions, index=self.data.index, columns=self.data.columns
        )

    def slow_features(self, n_components=None, variance=0.99):
        """
        Summarize the timescales in a fitted model of time-series data, where the items are consecutive time-points, using slow feature analysis (Wiskott & Sejnowski, 2002).

        The model's predicted rating curves are re-expressed as a set of uncorrelated, unit-variance time courses ordered from the slowest changing to the fastest. Unlike `.item_vecs`, whose factors can be mixed arbitrarily without changing the predictions, these are computed from the predictions themselves, so they are a property of the fit. Most useful after fitting with `temporal_order`, which removes rating noise from the predicted curves; with noisy curves every component looks faster than it is.

        Args:
            n_components (int, optional): number of time courses to return. Defaults to None which keeps as many as are needed to explain `variance` of the predicted curves.
            variance (float, optional): proportion of the variance in the predicted curves to keep when `n_components` is None. Defaults to 0.99.

        Returns:
            dict: with keys
                'features': time-points x components dataframe of time courses, slowest first
                'components': per-component summary; 'autocorrelation' is the correlation between neighbouring time-points, 'timescale' is the number of time-points over which that correlation decays to 1/e, and 'variance' is the share of variance in the predicted curves it carries
                'weights': users x components dataframe; each user's predicted curve is their mean plus their weights times the features
                'users': per-user summary of how slowly their own predicted curve changes, with the same 'autocorrelation' and 'timescale' columns, plus 'slow_share', the share of their curve's variance carried by the slower half of the components
        """

        if not self.is_fit:
            raise ValueError("Model must be fit before computing slow features")
        if isinstance(self.data.columns, pd.MultiIndex):
            raise NotImplementedError("slow_features is only available for BPMF")

        curves = self._pred_mean - self._pred_mean.mean(axis=1, keepdims=True)
        n_times = curves.shape[1]
        _, sing, vt = np.linalg.svd(curves, full_matrices=False)
        explained = sing**2 / np.sum(sing**2)
        if n_components is None:
            n_components = int(np.searchsorted(np.cumsum(explained), variance) + 1)
        n_components = min(n_components, int(np.sum(sing > sing[0] * 1e-8)))
        # Unit-variance, uncorrelated time courses spanning the predicted curves
        white = vt[:n_components].T * np.sqrt(n_times)
        steps = np.diff(white, axis=0)
        slowness, rotation = np.linalg.eigh(steps.T @ steps / len(steps))
        features = white @ rotation
        weights = curves @ features / n_times

        def describe(mean_sq_step):
            # For a unit-variance series the mean squared step is 2 * (1 - lag-1 autocorrelation)
            autocorr = 1 - mean_sq_step / 2
            with np.errstate(divide="ignore", invalid="ignore"):
                timescale = np.where(autocorr > 0, -1 / np.log(autocorr), 0.0)
            return autocorr, timescale

        names = [f"slow_{i + 1}" for i in range(n_components)]
        autocorr, timescale = describe(slowness)
        components = pd.DataFrame(
            {
                "autocorrelation": autocorr,
                "timescale": timescale,
                "variance": np.sum(weights**2, axis=0) / np.sum(curves**2) * n_times,
            },
            index=names,
        )
        kept = np.sum(weights**2, axis=1)
        user_autocorr, user_timescale = describe(weights**2 @ slowness / kept)
        users = pd.DataFrame(
            {
                "autocorrelation": user_autocorr,
                "timescale": user_timescale,
                "slow_share": np.sum(weights[:, : (n_components + 1) // 2] ** 2, axis=1)
                / kept,
            },
            index=self.data.index,
        )
        return {
            "features": pd.DataFrame(features, index=self.data.columns, columns=names),
            "components": components,
            "weights": pd.DataFrame(weights, index=self.data.index, columns=names),
            "users": users,
        }

    def prediction_interval(self, level=0.95, kind="predictive"):
        """
        Get an interval around each prediction using a normal approximation to the posterior.

        Args:
            level (float, optional): probability mass the interval should cover. Defaults to 0.95.
            kind (str, optional): 'predictive' for where a new rating is expected to fall, which includes rating noise, or 'posterior' for uncertainty about the underlying noise-free rating. Defaults to 'predictive'.

        **Note**: 'predictive' intervals are well calibrated regardless of `n_factors`. 'posterior' intervals are only calibrated when `n_factors` is close to the true number of factors. With surplus factors some rating noise is attributed to the factors, which makes 'posterior' intervals wider than they should be.

        Returns:
            tuple: (lower, upper) user x item dataframes, clipped the same way as the predictions
        """

        if not self.is_fit:
            raise ValueError("Model has not been fit!")
        if not 0 < level < 1:
            raise ValueError("level must be between 0 and 1")
        if kind not in ["predictive", "posterior"]:
            raise ValueError("kind must be one of 'predictive' or 'posterior'")

        std = self.predictive_std if kind == "predictive" else self.posterior_std
        half_width = norm.ppf(0.5 + level / 2) * std.to_numpy()
        lower, upper = self._pred_mean - half_width, self._pred_mean + half_width
        if self.clip_predictions:
            lower, upper = self._clip_predictions(lower), self._clip_predictions(upper)
        return tuple(
            pd.DataFrame(arr, index=self.data.index, columns=self.data.columns)
            for arr in (lower, upper)
        )

__init__(self, data, mask=None, n_mask_items=None, verbose=True, random_state=None) special

Parameters:

Name Type Description Default
data pd.DataFrame

users x items dataframe

required
mask pd.DataFrame

A boolean dataframe used to split the data into 'observed' and 'missing' datasets. Defaults to None.

None
n_mask_items int/float

number of items to mask out, 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 (pd.DataFrame): users x items dataframe
        mask (pd.DataFrame, optional): A boolean dataframe used to split the data into 'observed' and 'missing' datasets. Defaults to None.
        n_mask_items (int/float, optional): number of items to mask out, 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

    """
    super().__init__(
        data, mask, n_mask_items, random_state=random_state, verbose=verbose
    )
    self.n_factors = None
    self.posterior_std = None
    self.predictive_std = 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, user_noise=False, **kwargs)

Fit a Bayesian probabilistic matrix factorization model using Gibbs sampling.

Parameters:

Name Type Description Default
n_factors int

number of factors to learn. Defaults to None which, like the NNMF models, uses all factors (the smaller of the number of users and items), but capped at 50 because the cost of each sweep grows with the cube of the number of factors. Surplus factors are shrunk by the priors, so they cost time rather than accuracy.

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 int

How many items to dilate by prior to training. Defaults to None.

None
clip_predictions bool

clip predictions to the rating range. Defaults to True.

True
clip_range tuple

explicit (min, max) bounds to clip to, e.g. the full rating scale. Defaults to None which uses the min and max of the observed (training) ratings.

None
temporal_order int

for time-series data whose items are equally spaced time-points. 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 amount of smoothing is learned from the data. This is an alternative to dilate_by_nsamples that does not create extra training data. Defaults to None which treats items as exchangeable.

None
user_noise bool

learn a separate noise level for every user rather than one shared value. Each user's noise is estimated as a deviation from a group-level distribution, so users with few ratings are pulled toward the group. Users with noisier ratings then count for less when learning about items, and their predictions get wider intervals. Per-user estimates are available afterwards in .user_noise_std. Defaults to False.

False
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,
    user_noise=False,
    **kwargs,
):
    """
    Fit a Bayesian probabilistic matrix factorization model using Gibbs sampling.

    Args:
        n_factors (int, optional): number of factors to learn. Defaults to None which, like the `NNMF` models, uses all factors (the smaller of the number of users and items), but capped at 50 because the cost of each sweep grows with the cube of the number of factors. Surplus factors are shrunk by the priors, so they cost time rather than accuracy.
        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 (int, optional): How many items to dilate by prior to training. Defaults to None.
        clip_predictions (bool, optional): clip predictions to the rating range. Defaults to True.
        clip_range (tuple, optional): explicit (min, max) bounds to clip to, e.g. the full rating scale. Defaults to None which uses the min and max of the observed (training) ratings.
        temporal_order (int, optional): for time-series data whose items are equally spaced time-points. 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 amount of smoothing is learned from the data. This is an alternative to `dilate_by_nsamples` that does not create extra training data. Defaults to None which treats items as exchangeable.
        user_noise (bool, optional): learn a separate noise level for every user rather than one shared value. Each user's noise is estimated as a deviation from a group-level distribution, so users with few ratings are pulled toward the group. Users with noisier ratings then count for less when learning about items, and their predictions get wider intervals. Per-user estimates are available afterwards in `.user_noise_std`. Defaults to False.
    """

    # Call parent fit which acts as a guard for non-masked data
    super().fit()

    n_users, n_items = self.data.shape

    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([50, 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)

    # Perform dilation if requested
    self.dilate_mask(n_samples=dilate_by_nsamples)

    # Standardize the training ratings so the priors mean the same thing on any rating scale
    X = self.masked_data.to_numpy(dtype=np.float64)
    M = np.isfinite(X)
    self._center = X[M].mean()
    scale = X[M].std()
    self._scale = scale if scale > 0 else 1.0
    R = np.where(M, (X - self._center) / self._scale, 0.0)

    self.temporal_order = temporal_order

    out = bpmf_gibbs(
        R,
        M.astype(np.float64),
        n_factors,
        n_samples,
        burn_in,
        self.random_state,
        verbose=verbose,
        temporal_order=temporal_order,
        user_noise=user_noise,
    )

    # Save outputs to model, converting back to the original rating scale
    # Factors are oriented like NNMF_sgd: user x factor, factor x item
    self.user_vecs, self.item_vecs = out["U"], out["V"].T
    self._pred_mean = out["pred_mean"] * self._scale + self._center
    self.noise_std = np.sqrt(np.mean(out["noise_var"])) * self._scale
    self.user_noise_std = (
        pd.Series(
            np.sqrt(out["noise_var"]) * self._scale,
            index=self.data.index,
            name="noise_std",
        )
        if user_noise
        else None
    )
    self.noise_precision_history = out["alpha_history"]
    self.error_history = out["rmse_history"] * self._scale / self.data_range
    train_error = (self._pred_mean - X)[M]
    self._norm_rmse = np.sqrt(np.mean(train_error**2)) / self.data_range
    # There is no convergence criterion for a sampler; inspect .plot_learning() instead
    self.converged = None

    posterior_std = np.sqrt(out["pred_var"]) * self._scale
    noise_var = np.reshape(out["noise_var"], (-1, 1))
    predictive_std = np.sqrt(out["pred_var"] + noise_var) * self._scale
    self.posterior_std = pd.DataFrame(
        posterior_std, index=self.data.index, columns=self.data.columns
    )
    self.predictive_std = pd.DataFrame(
        predictive_std, index=self.data.index, columns=self.data.columns
    )

    if verbose:
        print(f"\n\tFinal Norm Error: {np.round(100 * self._norm_rmse, 2)}%")
        print(f"\tEstimated noise SD: {np.round(self.noise_std, 3)}")

    self._predict()
    self.is_fit = True

prediction_interval(self, level=0.95, kind='predictive')

Get an interval around each prediction using a normal approximation to the posterior.

Parameters:

Name Type Description Default
level float

probability mass the interval should cover. Defaults to 0.95.

0.95
kind str

'predictive' for where a new rating is expected to fall, which includes rating noise, or 'posterior' for uncertainty about the underlying noise-free rating. Defaults to 'predictive'.

'predictive'

Note: 'predictive' intervals are well calibrated regardless of n_factors. 'posterior' intervals are only calibrated when n_factors is close to the true number of factors. With surplus factors some rating noise is attributed to the factors, which makes 'posterior' intervals wider than they should be.

Returns:

Type Description
tuple

(lower, upper) user x item dataframes, clipped the same way as the predictions

Source code in neighbors/models.py
def prediction_interval(self, level=0.95, kind="predictive"):
    """
    Get an interval around each prediction using a normal approximation to the posterior.

    Args:
        level (float, optional): probability mass the interval should cover. Defaults to 0.95.
        kind (str, optional): 'predictive' for where a new rating is expected to fall, which includes rating noise, or 'posterior' for uncertainty about the underlying noise-free rating. Defaults to 'predictive'.

    **Note**: 'predictive' intervals are well calibrated regardless of `n_factors`. 'posterior' intervals are only calibrated when `n_factors` is close to the true number of factors. With surplus factors some rating noise is attributed to the factors, which makes 'posterior' intervals wider than they should be.

    Returns:
        tuple: (lower, upper) user x item dataframes, clipped the same way as the predictions
    """

    if not self.is_fit:
        raise ValueError("Model has not been fit!")
    if not 0 < level < 1:
        raise ValueError("level must be between 0 and 1")
    if kind not in ["predictive", "posterior"]:
        raise ValueError("kind must be one of 'predictive' or 'posterior'")

    std = self.predictive_std if kind == "predictive" else self.posterior_std
    half_width = norm.ppf(0.5 + level / 2) * std.to_numpy()
    lower, upper = self._pred_mean - half_width, self._pred_mean + half_width
    if self.clip_predictions:
        lower, upper = self._clip_predictions(lower), self._clip_predictions(upper)
    return tuple(
        pd.DataFrame(arr, index=self.data.index, columns=self.data.columns)
        for arr in (lower, upper)
    )

slow_features(self, n_components=None, variance=0.99)

Summarize the timescales in a fitted model of time-series data, where the items are consecutive time-points, using slow feature analysis (Wiskott & Sejnowski, 2002).

The model's predicted rating curves are re-expressed as a set of uncorrelated, unit-variance time courses ordered from the slowest changing to the fastest. Unlike .item_vecs, whose factors can be mixed arbitrarily without changing the predictions, these are computed from the predictions themselves, so they are a property of the fit. Most useful after fitting with temporal_order, which removes rating noise from the predicted curves; with noisy curves every component looks faster than it is.

Parameters:

Name Type Description Default
n_components int

number of time courses to return. Defaults to None which keeps as many as are needed to explain variance of the predicted curves.

None
variance float

proportion of the variance in the predicted curves to keep when n_components is None. Defaults to 0.99.

0.99

Returns:

Type Description
dict

with keys 'features': time-points x components dataframe of time courses, slowest first 'components': per-component summary; 'autocorrelation' is the correlation between neighbouring time-points, 'timescale' is the number of time-points over which that correlation decays to 1/e, and 'variance' is the share of variance in the predicted curves it carries 'weights': users x components dataframe; each user's predicted curve is their mean plus their weights times the features 'users': per-user summary of how slowly their own predicted curve changes, with the same 'autocorrelation' and 'timescale' columns, plus 'slow_share', the share of their curve's variance carried by the slower half of the components

Source code in neighbors/models.py
def slow_features(self, n_components=None, variance=0.99):
    """
    Summarize the timescales in a fitted model of time-series data, where the items are consecutive time-points, using slow feature analysis (Wiskott & Sejnowski, 2002).

    The model's predicted rating curves are re-expressed as a set of uncorrelated, unit-variance time courses ordered from the slowest changing to the fastest. Unlike `.item_vecs`, whose factors can be mixed arbitrarily without changing the predictions, these are computed from the predictions themselves, so they are a property of the fit. Most useful after fitting with `temporal_order`, which removes rating noise from the predicted curves; with noisy curves every component looks faster than it is.

    Args:
        n_components (int, optional): number of time courses to return. Defaults to None which keeps as many as are needed to explain `variance` of the predicted curves.
        variance (float, optional): proportion of the variance in the predicted curves to keep when `n_components` is None. Defaults to 0.99.

    Returns:
        dict: with keys
            'features': time-points x components dataframe of time courses, slowest first
            'components': per-component summary; 'autocorrelation' is the correlation between neighbouring time-points, 'timescale' is the number of time-points over which that correlation decays to 1/e, and 'variance' is the share of variance in the predicted curves it carries
            'weights': users x components dataframe; each user's predicted curve is their mean plus their weights times the features
            'users': per-user summary of how slowly their own predicted curve changes, with the same 'autocorrelation' and 'timescale' columns, plus 'slow_share', the share of their curve's variance carried by the slower half of the components
    """

    if not self.is_fit:
        raise ValueError("Model must be fit before computing slow features")
    if isinstance(self.data.columns, pd.MultiIndex):
        raise NotImplementedError("slow_features is only available for BPMF")

    curves = self._pred_mean - self._pred_mean.mean(axis=1, keepdims=True)
    n_times = curves.shape[1]
    _, sing, vt = np.linalg.svd(curves, full_matrices=False)
    explained = sing**2 / np.sum(sing**2)
    if n_components is None:
        n_components = int(np.searchsorted(np.cumsum(explained), variance) + 1)
    n_components = min(n_components, int(np.sum(sing > sing[0] * 1e-8)))
    # Unit-variance, uncorrelated time courses spanning the predicted curves
    white = vt[:n_components].T * np.sqrt(n_times)
    steps = np.diff(white, axis=0)
    slowness, rotation = np.linalg.eigh(steps.T @ steps / len(steps))
    features = white @ rotation
    weights = curves @ features / n_times

    def describe(mean_sq_step):
        # For a unit-variance series the mean squared step is 2 * (1 - lag-1 autocorrelation)
        autocorr = 1 - mean_sq_step / 2
        with np.errstate(divide="ignore", invalid="ignore"):
            timescale = np.where(autocorr > 0, -1 / np.log(autocorr), 0.0)
        return autocorr, timescale

    names = [f"slow_{i + 1}" for i in range(n_components)]
    autocorr, timescale = describe(slowness)
    components = pd.DataFrame(
        {
            "autocorrelation": autocorr,
            "timescale": timescale,
            "variance": np.sum(weights**2, axis=0) / np.sum(curves**2) * n_times,
        },
        index=names,
    )
    kept = np.sum(weights**2, axis=1)
    user_autocorr, user_timescale = describe(weights**2 @ slowness / kept)
    users = pd.DataFrame(
        {
            "autocorrelation": user_autocorr,
            "timescale": user_timescale,
            "slow_share": np.sum(weights[:, : (n_components + 1) // 2] ** 2, axis=1)
            / kept,
        },
        index=self.data.index,
    )
    return {
        "features": pd.DataFrame(features, index=self.data.columns, columns=names),
        "components": components,
        "weights": pd.DataFrame(weights, index=self.data.index, columns=names),
        "users": users,
    }