Core Module Documentation#

neuralprophet.utils.check_for_regularization(configs: list)#

Check if any regularization is specified in the configs

Parameters

configs (list) – List of configurations

Returns

True if any regularization is specified

Return type

bool

neuralprophet.utils.config_events_to_model_dims(config_events: Optional[ConfigEvents], config_country_holidays)#
Convert user specified events configurations along with country specific

holidays to input dims for TimeNet model.

Parameters
  • config_events (configure.ConfigEvents) – Configurations (upper, lower windows, regularization) for user specified events

  • config_country_holidays (configure.ConfigCountryHolidays) – Configurations (holiday_names, upper, lower windows, regularization) for country specific holidays

Returns

input dims for TimeNet model

Note

This dictionaries’ keys correspond to individual holidays and contains configs such as the mode, list of event delims of the event corresponding to the offsets and indices in the input dataframe corresponding to each event.

Return type

OrderedDict

neuralprophet.utils.config_regressors_to_model_dims(config_regressors)#

Convert the NeuralProphet user specified regressors configurations to input dims for TimeNet model.

Parameters

config_regressors (configure.ConfigFutureRegressors) – Configurations for user specified regressors

Returns

Input dims for TimeNet model.

Note

This dictionaries’ keys correspond to individual regressor and values in a dict containing the mode and the indices in the input dataframe corresponding to each regressor.

Return type

OrderedDict

neuralprophet.utils.config_seasonality_to_model_dims(config_seasonality: ConfigSeasonality)#

Convert the NeuralProphet seasonal model configuration to input dims for TimeNet model.

Parameters

config_seasonality (configure.ConfigSeasonality) – NeuralProphet seasonal model configuration

Returns

Input dims for TimeNet model

Return type

dict(int)

neuralprophet.utils.configure_trainer(config_train: Train, config: dict, metrics_logger, early_stopping: bool = False, early_stopping_target: str = 'Loss', accelerator: Optional[str] = None, progress_bar_enabled: bool = True, metrics_enabled: bool = False, checkpointing_enabled: bool = False, num_batches_per_epoch: int = 100)#

Configures the PyTorch Lightning trainer.

Parameters
  • config_train (Dict) – dictionary containing the overall training configuration.

  • config (dict) – dictionary containing the custom PyTorch Lightning trainer configuration.

  • metrics_logger (MetricsLogger) – MetricsLogger object to log metrics to.

  • early_stopping (bool) – If True, early stopping is enabled.

  • early_stopping_target (str) – Target metric to use for early stopping.

  • accelerator (str) – Accelerator to use for training.

  • progress_bar_enabled (bool) – If False, no progress bar is shown.

  • metrics_enabled (bool) – If False, no metrics are logged. Calculating metrics is computationally expensive and reduces the training speed.

  • checkpointing_enabled (bool) – If False, no checkpointing is performed. Checkpointing reduces the training speed.

  • num_batches_per_epoch (int) – Number of batches per epoch.

Returns

  • pl.Trainer – PyTorch Lightning trainer

  • checkpoint_callback – PyTorch Lightning checkpoint callback to load the best model

neuralprophet.utils.create_event_names_for_offsets(event_name, offset)#

Create names for offsets of every event

Parameters
  • event_name (str) – Name of the event

  • offset (int) – Offset of the event

Returns

Name created for the offset of the event

Return type

str

neuralprophet.utils.fcst_df_to_latest_forecast(fcst, quantiles, n_last=1)#

Converts from line-per-lag to line-per-forecast.

Parameters
  • fcst (pd.DataFrame) – Forecast df

  • quantiles (list, default None) – A list of float values between (0, 1) which indicate the set of quantiles to be estimated.

  • n_last (int) – Number of latest forecasts to include

Returns

Dataframe where origin-0 is latest forecast, origin-1 second to latest etc

Return type

pd.DataFrame

neuralprophet.utils.get_holidays_from_country(country: Union[str, Iterable[str]], df=None)#

Return all possible holiday names of given country

Parameters
  • country (str, list) – List of country names to retrieve country specific holidays

  • df (pd.Dataframe) – Dataframe from which datestamps will be retrieved from

Returns

All possible holiday names of given country

Return type

set

neuralprophet.utils.load(path: str, map_location=None)#

retrieve a fitted model from a .np file that was saved by save.

Parameters
  • path (str) – path and filename to be saved. filename could be any but suggested to have extension .np.

  • map_location (str, optional) – specifying the location where the model should be loaded. If you are running on a CPU-only machine, set map_location=’cpu’ to map your storages to the CPU. If you are running on CUDA, set map_location=’cuda:device_id’ (e.g. ‘cuda:2’). Default is None, which means the model is loaded to the same device as it was saved on.

Returns

previously saved model

Return type

np.forecaster.NeuralProphet

Examples

Saved model could be loaded from disk file test_save_model.np
>>> from neuralprophet import load
>>> model = load("test_save_model.np")
neuralprophet.utils.reg_func_abs(weights)#

Regularization of weights to induce sparcity

Parameters

weights (torch.Tensor) – Model weights to be regularized towards zero

Returns

Regularization loss

Return type

torch.Tensor

neuralprophet.utils.reg_func_covariates(config_lagged_regressors: ConfigLaggedRegressors, model)#

Regularization of lagged covariates to induce sparsity

Parameters
  • config_lagged_regressors (configure.ConfigLaggedRegressors) – Configurations for lagged regressors

  • model (TimeNet) – TimeNet model object

Returns

Regularization loss

Return type

scalar

neuralprophet.utils.reg_func_events(config_events: Optional[ConfigEvents], config_country_holidays, model)#

Regularization of events coefficients to induce sparcity

Parameters
  • config_events (configure.ConfigEvents) – Configurations (upper, lower windows, regularization) for user specified events

  • config_country_holidays (configure.ConfigCountryHolidays) – Configurations (holiday_names, upper, lower windows, regularization) for country specific holidays

  • model (TimeNet) – The TimeNet model object

Returns

Regularization loss

Return type

scalar

neuralprophet.utils.reg_func_regressors(config_regressors, model)#

Regularization of regressors coefficients to induce sparsity

Parameters
Returns

Regularization loss

Return type

scalar

neuralprophet.utils.reg_func_seasonality_glocal(season_params, seasonality_local_reg)#

Regularization of weights to induce similarity between global and local trend :param # season_params: :type # season_params: torch.Tensor :param # Local season params: :param # seasonality_local_reg: :type # seasonality_local_reg: float :param # glocal season regularization coefficient:

Returns

regularization loss

Return type

torch.Tensor

neuralprophet.utils.reg_func_trend(weights, threshold=None)#

Regularization of weights to induce sparcity

Parameters
  • weights (torch.Tensor) – Model weights to be regularized towards zero

  • threshold (float) – Value below which not to regularize weights

Returns

regularization loss

Return type

torch.Tensor

neuralprophet.utils.reg_func_trend_glocal(trend_k0, trend_deltas, trend_local_reg)#

Regularization of weights to induce similarity between global and local trend :param # trend_k0: :type # trend_k0: torch.Tensor :param # Local trend intercept: :param # trend_deltas: :type # trend_deltas: torch.Tensor :param # Local trend slopes: :param # trend_local_reg: :type # trend_local_reg: float :param # glocal trend regularization coefficient:

Returns

regularization loss

Return type

torch.Tensor

neuralprophet.utils.save(forecaster, path: str)#

Save a fitted Neural Prophet model to disk.

Parameters
  • forecaster – np.forecaster.NeuralProphet input forecaster that is fitted

  • path – str path and filename to be saved. filename could be any but suggested to have extension .np.

After you fitted a model, you may save the model to save_test_model.np
>>> from neuralprophet import save
>>> save(forecaster, "test_save_model.np")
neuralprophet.utils.set_auto_seasonalities(df, config_seasonality: ConfigSeasonality)#

Set seasonalities that were left on auto or set by user.

Note

Turns on yearly seasonality if there is >=2 years of history.

Turns on weekly seasonality if there is >=2 weeks of history, and the spacing between dates in the history is <7 days.

Turns on daily seasonality if there is >=2 days of history, and the spacing between dates in the history is <1 day.

Parameters
  • df (pd.Dataframe) – Dataframe from which datestamps will be retrieved from

  • config_seasonality (configure.ConfigSeasonality) – NeuralProphet seasonal model configuration, as after __init__

Returns

Processed NeuralProphet seasonal model configuration

Return type

configure.ConfigSeasonality

neuralprophet.utils.set_log_level(log_level: str = 'INFO', include_handlers: bool = False)#

Set the log level of all logger objects

Parameters
  • log_level (str) – The log level of the logger objects used for printing procedure status updates for debugging/monitoring. Should be one of NOTSET, DEBUG, INFO, WARNING, ERROR or CRITICAL

  • include_handlers (bool) – Include any specified file/stream handlers

Example

>>> from neuralprophet import set_log_level
>>> set_log_level("ERROR")
neuralprophet.utils.set_random_seed(seed: int = 0)#

Sets the random number generator to a fixed seed.

Parameters

seed (numeric) – Seed value for random number generator

Note

This needs to be set each time before fitting the model.

Example

>>> from neuralprophet import set_random_seed
>>> set_random_seed(seed=42)
neuralprophet.utils.smooth_loss_and_suggest(lr_finder_results, window=10)#

Smooth loss using a Hamming filter.

Parameters

loss (np.array) – Loss values

Returns

  • loss_smoothed (np.array) – Smoothed loss values

  • lr (np.array) – Learning rate values

  • suggested_lr (float) – Suggested learning rate based on gradient

neuralprophet.utils.symmetric_total_percentage_error(values, estimates)#

Compute STPE

Parameters
  • values (np.array) – Input values

  • estimates (np.array) – Respective estimates of input values

Returns

Symmetric total percentage error

Return type

float