prophet.utilities

  1# Copyright (c) Facebook, Inc. and its affiliates.
  2
  3# This source code is licensed under the MIT license found in the
  4# LICENSE file in the root directory of this source tree.
  5
  6from __future__ import annotations
  7
  8from typing import TYPE_CHECKING, cast
  9
 10import numpy as np
 11import pandas as pd
 12
 13if TYPE_CHECKING:
 14    from prophet.forecaster import Prophet
 15    import numpy.typing as npt
 16
 17
 18def regressor_index(m: Prophet, name: str) -> np.intp:
 19    """Given the name of a regressor, return its (column) index in the `beta` matrix.
 20
 21    Parameters
 22    ----------
 23    m: Prophet model object, after fitting.
 24    name: Name of the regressor, as passed into the `add_regressor` function.
 25
 26    Returns
 27    -------
 28    The column index of the regressor in the `beta` matrix.
 29    """
 30    cols = cast(pd.DataFrame, m.train_component_cols)
 31    return np.extract(cols[name] == 1, cols.index)[0]
 32
 33def regressor_coefficients(m: Prophet) -> pd.DataFrame:
 34    """Summarise the coefficients of the extra regressors used in the model.
 35
 36    For additive regressors, the coefficient represents the incremental impact
 37    on `y` of a unit increase in the regressor. For multiplicative regressors,
 38    the incremental impact is equal to `trend(t)` multiplied by the coefficient.
 39
 40    Coefficients are measured on the original scale of the training data.
 41
 42    Parameters
 43    ----------
 44    m: Prophet model object, after fitting.
 45
 46    Returns
 47    -------
 48    pd.DataFrame containing:
 49    - `regressor`: Name of the regressor
 50    - `regressor_mode`: Whether the regressor has an additive or multiplicative
 51        effect on `y`.
 52    - `center`: The mean of the regressor if it was standardized. Otherwise 0.
 53    - `coef_lower`: Lower bound for the coefficient, estimated from the MCMC samples.
 54        Only different to `coef` if `mcmc_samples > 0`.
 55    - `coef`: Expected value of the coefficient.
 56    - `coef_upper`: Upper bound for the coefficient, estimated from MCMC samples.
 57        Only different to `coef` if `mcmc_samples > 0`.
 58    """
 59    assert len(m.extra_regressors) > 0, 'No extra regressors found.'
 60    coefs = []
 61    for regressor, params in m.extra_regressors.items():
 62        beta = m.params['beta'][:, regressor_index(m, regressor)]
 63        if params['mode'] == 'additive':
 64            coef = beta * m.y_scale / params['std']
 65        else:
 66            coef = beta / params['std']
 67        percentiles = [
 68            (1 - m.interval_width) / 2,
 69            1 - (1 - m.interval_width) / 2,
 70        ]
 71        coef_bounds = np.quantile(coef, q=percentiles)
 72        record = {
 73            'regressor': regressor,
 74            'regressor_mode': params['mode'],
 75            'center': params['mu'],
 76            'coef_lower': coef_bounds[0],
 77            'coef': np.mean(coef),
 78            'coef_upper': coef_bounds[1],
 79        }
 80        coefs.append(record)
 81
 82    return pd.DataFrame(coefs)
 83
 84def warm_start_params(m: Prophet) -> dict[str, npt.NDArray[np.float64] | np.float64]:
 85    """
 86    Retrieve parameters from a trained model in the format used to initialize a new Stan model.
 87    Note that the new Stan model must have these same settings:
 88        n_changepoints, seasonality features, mcmc sampling
 89    for the retrieved parameters to be valid for the new model.
 90
 91    Parameters
 92    ----------
 93    m: A trained model of the Prophet class.
 94
 95    Returns
 96    -------
 97    A Dictionary containing retrieved parameters of m.
 98    """
 99    res = {}
100    for pname in ['k', 'm', 'sigma_obs']:
101        if m.mcmc_samples == 0:
102            res[pname] = m.params[pname][0][0]
103        else:
104            res[pname] = np.mean(m.params[pname])
105    for pname in ['delta', 'beta']:
106        if m.mcmc_samples == 0:
107            res[pname] = m.params[pname][0]
108        else:
109            res[pname] = np.mean(m.params[pname], axis=0)
110    return res
def regressor_index(m: prophet.Prophet, name: str) -> numpy.int64:
19def regressor_index(m: Prophet, name: str) -> np.intp:
20    """Given the name of a regressor, return its (column) index in the `beta` matrix.
21
22    Parameters
23    ----------
24    m: Prophet model object, after fitting.
25    name: Name of the regressor, as passed into the `add_regressor` function.
26
27    Returns
28    -------
29    The column index of the regressor in the `beta` matrix.
30    """
31    cols = cast(pd.DataFrame, m.train_component_cols)
32    return np.extract(cols[name] == 1, cols.index)[0]

Given the name of a regressor, return its (column) index in the beta matrix.

Parameters
  • m (Prophet model object, after fitting.):

  • name (Name of the regressor, as passed into the add_regressor function.):

Returns
  • The column index of the regressor in the beta matrix.
def regressor_coefficients(m: prophet.Prophet) -> pandas.DataFrame:
34def regressor_coefficients(m: Prophet) -> pd.DataFrame:
35    """Summarise the coefficients of the extra regressors used in the model.
36
37    For additive regressors, the coefficient represents the incremental impact
38    on `y` of a unit increase in the regressor. For multiplicative regressors,
39    the incremental impact is equal to `trend(t)` multiplied by the coefficient.
40
41    Coefficients are measured on the original scale of the training data.
42
43    Parameters
44    ----------
45    m: Prophet model object, after fitting.
46
47    Returns
48    -------
49    pd.DataFrame containing:
50    - `regressor`: Name of the regressor
51    - `regressor_mode`: Whether the regressor has an additive or multiplicative
52        effect on `y`.
53    - `center`: The mean of the regressor if it was standardized. Otherwise 0.
54    - `coef_lower`: Lower bound for the coefficient, estimated from the MCMC samples.
55        Only different to `coef` if `mcmc_samples > 0`.
56    - `coef`: Expected value of the coefficient.
57    - `coef_upper`: Upper bound for the coefficient, estimated from MCMC samples.
58        Only different to `coef` if `mcmc_samples > 0`.
59    """
60    assert len(m.extra_regressors) > 0, 'No extra regressors found.'
61    coefs = []
62    for regressor, params in m.extra_regressors.items():
63        beta = m.params['beta'][:, regressor_index(m, regressor)]
64        if params['mode'] == 'additive':
65            coef = beta * m.y_scale / params['std']
66        else:
67            coef = beta / params['std']
68        percentiles = [
69            (1 - m.interval_width) / 2,
70            1 - (1 - m.interval_width) / 2,
71        ]
72        coef_bounds = np.quantile(coef, q=percentiles)
73        record = {
74            'regressor': regressor,
75            'regressor_mode': params['mode'],
76            'center': params['mu'],
77            'coef_lower': coef_bounds[0],
78            'coef': np.mean(coef),
79            'coef_upper': coef_bounds[1],
80        }
81        coefs.append(record)
82
83    return pd.DataFrame(coefs)

Summarise the coefficients of the extra regressors used in the model.

For additive regressors, the coefficient represents the incremental impact on y of a unit increase in the regressor. For multiplicative regressors, the incremental impact is equal to trend(t) multiplied by the coefficient.

Coefficients are measured on the original scale of the training data.

Parameters
  • m (Prophet model object, after fitting.):
Returns
  • pd.DataFrame containing:
  • - regressor (Name of the regressor):

  • - regressor_mode (Whether the regressor has an additive or multiplicative): effect on y.

  • - center (The mean of the regressor if it was standardized. Otherwise 0.):

  • - coef_lower (Lower bound for the coefficient, estimated from the MCMC samples.): Only different to coef if mcmc_samples > 0.

  • - coef (Expected value of the coefficient.):

  • - coef_upper (Upper bound for the coefficient, estimated from MCMC samples.): Only different to coef if mcmc_samples > 0.

def warm_start_params( m: prophet.Prophet) -> dict[str, NDArray[numpy.float64] | numpy.float64]:
 85def warm_start_params(m: Prophet) -> dict[str, npt.NDArray[np.float64] | np.float64]:
 86    """
 87    Retrieve parameters from a trained model in the format used to initialize a new Stan model.
 88    Note that the new Stan model must have these same settings:
 89        n_changepoints, seasonality features, mcmc sampling
 90    for the retrieved parameters to be valid for the new model.
 91
 92    Parameters
 93    ----------
 94    m: A trained model of the Prophet class.
 95
 96    Returns
 97    -------
 98    A Dictionary containing retrieved parameters of m.
 99    """
100    res = {}
101    for pname in ['k', 'm', 'sigma_obs']:
102        if m.mcmc_samples == 0:
103            res[pname] = m.params[pname][0][0]
104        else:
105            res[pname] = np.mean(m.params[pname])
106    for pname in ['delta', 'beta']:
107        if m.mcmc_samples == 0:
108            res[pname] = m.params[pname][0]
109        else:
110            res[pname] = np.mean(m.params[pname], axis=0)
111    return res

Retrieve parameters from a trained model in the format used to initialize a new Stan model. Note that the new Stan model must have these same settings: n_changepoints, seasonality features, mcmc sampling for the retrieved parameters to be valid for the new model.

Parameters
  • m (A trained model of the Prophet class.):
Returns
  • A Dictionary containing retrieved parameters of m.