Skip to content

ForecasterDirectMultiVariate¶

skforecast.direct._forecaster_direct_multivariate.ForecasterDirectMultiVariate ¶

ForecasterDirectMultiVariate(
    estimator,
    level,
    steps,
    lags=None,
    window_features=None,
    calendar_features=None,
    transformer_series=StandardScaler(),
    transformer_exog=None,
    categorical_features="auto",
    weight_func=None,
    differentiation=None,
    dropna_from_series=False,
    fit_kwargs=None,
    binner_kwargs=None,
    n_jobs="auto",
    forecaster_id=None,
)

Bases: ForecasterBase

This class turns any estimator compatible with the scikit-learn API into an autoregressive multivariate direct multi-step forecaster. A separate model is created for each forecast time step. See documentation for more details.

Parameters:

Name Type Description Default
estimator estimator or pipeline compatible with the scikit-learn API

An instance of an estimator or pipeline compatible with the scikit-learn API.

required
level str

Name of the time series to be predicted.

required
steps int

Maximum number of future steps the forecaster will predict when using method predict(). Since a different model is created for each step, this value must be defined before training.

required
lags int, list, numpy ndarray, range, dict

Lags used as predictors. Index starts at 1, so lag 1 is equal to t-1.

  • int: include lags from 1 to lags (included).
  • list, 1d numpy ndarray or range: include only lags present in lags, all elements must be int.
  • dict: create different lags for each series. {'series_column_name': lags}.
  • None: no lags are included as predictors.
None
window_features (object, list)

Instance or list of instances used to create window features. Window features are created from the original time series and are included as predictors. Skforecast provides the RollingFeatures class, but a custom object can also be passed as long as it implements the required interface.

None
calendar_features object

Instance of CalendarFeatures used to create calendar features from the datetime index. Calendar features are included as predictors and are generated automatically during both training and prediction. Only supported when the index of the input data is a pandas.DatetimeIndex. New in version 0.23.0

None
transformer_series (transformer(preprocessor), dict)

An instance of a transformer (preprocessor) compatible with the scikit-learn preprocessing API with methods: fit, transform, fit_transform and inverse_transform. Transformation is applied to each series before training the forecaster. ColumnTransformers are not allowed since they do not have inverse_transform method.

  • If single transformer: it is cloned and applied to all series.
  • If dict of transformers: a different transformer can be used for each series.
`sklearn.preprocessing.StandardScaler`
transformer_exog transformer

An instance of a transformer (preprocessor) compatible with the scikit-learn preprocessing API. The transformation is applied to exog before training the forecaster. inverse_transform is not available when using ColumnTransformers.

None
categorical_features (str, list)

Specifies which exogenous variables should be treated as categorical features. Categorical features are encoded using an OrdinalEncoder internally managed by the forecaster.

  • If 'auto': after applying transformer_exog, any column with a non-numeric dtype is treated as categorical.
  • If list: a list of column names to be treated as categorical.
  • If None: no categorical encoding is applied internally. New in version 0.22.0
'auto'
weight_func Callable

Function that defines the individual weights for each sample based on the index. For example, a function that assigns a lower weight to certain dates. Ignored if estimator does not have the argument sample_weight in its fit method. The resulting sample_weight cannot have negative values.

None
differentiation int

Order of differencing applied to the time series before training the forecaster. If None, no differencing is applied. The order of differentiation is the number of times the differencing operation is applied to a time series. Differencing involves computing the differences between consecutive data points in the series. Before returning a prediction, the differencing operation is reversed.

None
dropna_from_series bool

Determine whether NaN detected in the training matrices will be dropped. Relevant when series or exog contain interspersed NaN values.

  • If True, drop NaNs in X_train and same rows in y_train.
  • If False, leave NaNs in X_train and warn the user. New in version 0.22.0
False
fit_kwargs dict

Additional arguments to be passed to the fit method of the estimator.

None
binner_kwargs dict

Additional arguments to pass to the QuantileBinner used to discretize the residuals into k bins according to the predicted values associated with each residual. Available arguments are: n_bins, method, subsample, random_state and dtype. Argument method is passed internally to the function numpy.percentile.

None
n_jobs (int, 'auto')

The number of jobs to run in parallel. If -1, then the number of jobs is set to the number of cores. If 'auto', n_jobs is set using the function skforecast.utils.select_n_jobs_fit_forecaster.

'auto'
forecaster_id (str, int)

Name used as an identifier of the forecaster.

None

Attributes:

Name Type Description
estimator estimator or pipeline compatible with the scikit-learn API

An instance of an estimator or pipeline compatible with the scikit-learn API. An instance of this estimator is trained for each step. All of them are stored in self.estimators_.

estimators_ dict

Dictionary with estimators trained for each step. They are initialized as a copy of estimator.

steps numpy array

Future steps the forecaster will predict when using method predict(). Since a different model is created for each step, this value should be defined before training.

max_step int

Maximum step the forecaster is able to predict. It is the maximum value included in steps.

lags numpy ndarray, dict

Lags used as predictors.

lags_ dict

Dictionary with the lags of each series. Created from lags when creating the training matrices and used internally to avoid overwriting.

lags_names dict

Names of the lags of each series.

max_lag int

Maximum lag included in lags.

window_features list

Class or list of classes used to create window features.

window_features_names list

Names of the window features to be included in the X_train matrix.

window_features_class_names list

Names of the classes used to create the window features.

max_size_window_features int

Maximum window size required by the window features.

calendar_features object

Instance of CalendarFeatures used to create calendar features from the datetime index.

calendar_features_names list

Names of the calendar features to extract, taken from the features attribute of the calendar_features object.

window_size int

The window size needed to create the predictors. It is calculated as the maximum value between max_lag and max_size_window_features. If differentiation is used, window_size is increased by n units equal to the order of differentiation so that predictors can be generated correctly.

transformer_series transformer (preprocessor), dict, default None

An instance of a transformer (preprocessor) compatible with the scikit-learn preprocessing API with methods: fit, transform, fit_transform and inverse_transform. Transformation is applied to each series before training the forecaster. ColumnTransformers are not allowed since they do not have inverse_transform method.

  • If single transformer: it is cloned and applied to all series.
  • If dict of transformers: a different transformer can be used for each series.
transformer_series_ dict

Dictionary with the transformer for each series. It is created cloning the objects in transformer_series and is used internally to avoid overwriting.

transformer_exog transformer

An instance of a transformer (preprocessor) compatible with the scikit-learn preprocessing API. The transformation is applied to exog before training the forecaster. inverse_transform is not available when using ColumnTransformers.

weight_func Callable

Function that defines the individual weights for each sample based on the index. For example, a function that assigns a lower weight to certain dates. Ignored if estimator does not have the argument sample_weight in its fit method. The resulting sample_weight cannot have negative values.

source_code_weight_func str

Source code of the custom function used to create weights.

differentiation int

Order of differencing applied to the time series before training the forecaster.

differentiation_max int

Maximum order of differentiation. For this Forecaster, it is equal to the value of the differentiation parameter.

differentiator TimeSeriesDifferentiator

Skforecast object used to differentiate the time series.

differentiator_ dict

Dictionary with the differentiator for each series. It is created cloning the objects in differentiator and is used internally to avoid overwriting.

dropna_from_series bool

Determine whether NaN detected in the training matrices will be dropped.

last_window_ pandas DataFrame

This window represents the most recent data observed by the predictor during its training phase. It contains the values needed to predict the next step immediately after the training data. These values are stored in the original scale of the time series before undergoing any transformations or differentiation. When differentiation parameter is specified, the dimensions of the last_window_ are expanded as many values as the order of differentiation. For example, if lags = 7 and differentiation = 1, last_window_ will have 8 values.

index_type_ type

Type of index of the input used in training.

index_freq_ str

Frequency of Index of the input used in training.

training_range_ pandas Index

First and last values of index of the data used during training.

series_names_in_ list

Names of the series used during training.

exog_in_ bool

If the forecaster has been trained using exogenous variable/s.

exog_names_in_ list

Names of the exogenous variables used during training.

exog_type_in_ type

Type of exogenous variable/s used in training.

exog_dtypes_in_ dict

Type of each exogenous variable/s used in training before the transformation applied by transformer_exog. If transformer_exog is not used, it is equal to exog_dtypes_out_.

exog_dtypes_out_ dict

Type of each exogenous variable/s used in training after the transformation applied by transformer_exog. If transformer_exog is not used, it is equal to exog_dtypes_in_.

X_train_series_names_in_ list

Names of the series added to X_train when creating the training matrices with _create_train_X_y method. It is a subset of series_names_in_.

X_train_window_features_names_out_ list

Names of the window features included in the matrix X_train created internally for training.

X_train_calendar_features_names_out_ list

Names of the calendar features included in the matrix X_train created internally for training.

X_train_exog_names_out_ list

Names of the exogenous variables included in the matrix X_train created internally for training. It can be different from exog_names_in_ if some exogenous variables are transformed during the training process.

X_train_direct_exog_names_out_ list

Same as X_train_exog_names_out_ but using the direct format. The same exogenous variable is repeated for each step.

X_train_features_names_out_ list

Names of the features seen by each individual step estimator. These are the autoregressive features (lags + window features) and exogenous variable names.

X_train_direct_features_names_out_ list

Names of all columns of the full training matrix created internally. Same as X_train_features_names_out_ but with exogenous variables expanded with the _step_N suffix (direct format).

categorical_features (str, list)

How categorical features are identified among the exogenous variables. It can be 'auto', a list of column names or None.

categorical_features_names_in_ list

Names of the exogenous variables considered as categorical.

categorical_encoder sklearn OrdinalEncoder

OrdinalEncoder used internally to encode categorical features.

fit_kwargs dict

Additional arguments to be passed to the fit method of the estimator.

in_sample_residuals_ dict

Residuals of the model when predicting training data. Only stored up to 10_000 values per series in the form {series: residuals}. If transformer_series is not None, residuals are stored in the transformed scale. If differentiation is not None, residuals are stored after differentiation.

in_sample_residuals_by_bin_ dict

In-sample residuals binned according to the predicted value each residual is associated with. The number of residuals stored per bin is limited to 10_000 // self.binner.n_bins_ per series in the form {series: residuals}. If transformer_series is not None, residuals are stored in the transformed scale. If differentiation is not None, residuals are stored after differentiation.

out_sample_residuals_ dict

Residuals of the model when predicting non-training data. Only stored up to 10_000 values per series in the form {series: residuals}. Use set_out_sample_residuals() method to set values. If transformer_series is not None, residuals are stored in the transformed scale. If differentiation is not None, residuals are stored after differentiation.

out_sample_residuals_by_bin_ dict

Out of sample residuals binned according to the predicted value each residual is associated with. The number of residuals stored per bin is limited to 10_000 // self.binner.n_bins_ per series in the form {series: residuals}. If transformer_series is not None, residuals are stored in the transformed scale. If differentiation is not None, residuals are stored after differentiation.

binner dict

Dictionary of skforecast.preprocessing.QuantileBinner used to discretize residuals of each series into k bins according to the predicted values associated with each residual. In the form {series: binner}.

binner_intervals_ dict

Intervals used to discretize residuals into k bins according to the predicted values associated with each residual. In the form {series: binner_intervals_}.

binner_kwargs dict

Additional arguments to pass to the QuantileBinner.

filter_train_X_y_index_cache_ dict

Cache storing column indices for each forecasting step to speed up the creation of training matrices during backtesting. The cache uses step numbers as keys and numpy arrays of column indices as values. This avoids repeated calculations when filtering X_train for specific steps. The cache is cleared during fit() and when set_lags() or set_window_features() are called.

filter_train_X_y_columns_cache_ dict

Cache storing column names for each forecasting step to speed up the creation of training matrices during backtesting. The cache uses step numbers as keys and lists of column names as values. This avoids repeated string operations when removing step suffixes from column names. The cache is cleared during fit() and when set_lags() or set_window_features() are called.

creation_date str

Date of creation.

is_fitted bool

Tag to identify if the estimator has been fitted (trained).

fit_date str

Date of last fit.

skforecast_version str

Version of skforecast library used to create the forecaster.

python_version str

Version of python used to create the forecaster.

n_jobs (int, 'auto')

The number of jobs to run in parallel. If -1, then the number of jobs is set to the number of cores. If 'auto', n_jobs is set using the function skforecast.utils.select_n_jobs_fit_forecaster.

forecaster_id (str, int)

Name used as an identifier of the forecaster.

__skforecast_tags__ dict

Tags associated with the forecaster.

_probabilistic_mode (str, bool)

Private attribute used to indicate whether the forecaster should perform some calculations during backtesting.

encoding Ignored

Not used, present here for API consistency by convention.

Notes

A separate model is created for each forecasting time step. It is important to note that all models share the same parameter and hyperparameter configuration.

Methods:

Name Description
create_train_X_y

Create training matrices from multiple time series and exogenous

filter_train_X_y_for_step

Select the columns needed to train a forecaster for a specific step.

create_sample_weights

Create weights for each observation according to the forecaster's attribute

fit

Training Forecaster.

create_predict_X

Create the predictors needed to predict steps ahead.

predict

Predict n steps ahead

predict_bootstrapping

Generate multiple forecasting predictions using a bootstrapping process.

predict_interval

Predict n steps ahead and estimate prediction intervals using either

predict_quantiles

Calculate the specified quantiles for each step. After generating

predict_dist

Fit a given probability distribution for each step. After generating

set_params

Set new values to the parameters of the scikit-learn model stored in the

set_lags

Set new value to the attribute lags. Attributes lags_names,

set_window_features

Set new value to the attribute window_features. Attributes

set_fit_kwargs

Set new values for the additional keyword arguments passed to the fit

set_in_sample_residuals

Set in-sample residuals in case they were not calculated during the

set_out_sample_residuals

Set new values to the attribute out_sample_residuals_. Out of sample

get_feature_importances

Return feature importance of the model stored in the forecaster for a

Source code in skforecast/direct/_forecaster_direct_multivariate.py
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
def __init__(
    self,
    estimator: object,
    level: str,
    steps: int,
    lags: int | list[int] | np.ndarray[int] | range[int] | dict[str, int | list] | None = None,
    window_features: object | list[object] | None = None,
    calendar_features: object | None = None,
    transformer_series: object | dict[str, object] | None = StandardScaler(),
    transformer_exog: object | None = None,
    categorical_features: str | list[str] | None = 'auto',
    weight_func: Callable | None = None,
    differentiation: int | None = None,
    dropna_from_series: bool = False,
    fit_kwargs: dict[str, object] | None = None,
    binner_kwargs: dict[str, object] | None = None,
    n_jobs: int | str = 'auto',
    forecaster_id: str | int | None = None
) -> None:

    self.estimator                            = clone(estimator)
    self.calendar_features                    = (
        clone(calendar_features) if calendar_features is not None else None
    )
    self.calendar_features_names              = getattr(calendar_features, 'features', None)
    self.level                                = level
    self.lags_                                = None
    self.transformer_series                   = transformer_series
    self.transformer_series_                  = None
    self.transformer_exog                     = transformer_exog
    self.categorical_features                 = categorical_features
    self.weight_func                          = weight_func
    self.source_code_weight_func              = None
    self.differentiation                      = differentiation
    self.differentiation_max                  = None
    self.differentiator                       = None
    self.differentiator_                      = None
    self.dropna_from_series                   = dropna_from_series
    self.last_window_                         = None
    self.index_type_                          = None
    self.index_freq_                          = None
    self.training_range_                      = None
    self.series_names_in_                     = None
    self.exog_in_                             = False
    self.exog_names_in_                       = None
    self.exog_type_in_                        = None
    self.exog_dtypes_in_                      = None
    self.exog_dtypes_out_                     = None
    self.categorical_features_names_in_       = None
    self.X_train_series_names_in_             = None
    self.X_train_window_features_names_out_   = None
    self.X_train_calendar_features_names_out_ = None
    self.X_train_exog_names_out_              = None
    self.X_train_direct_exog_names_out_       = None
    self.X_train_features_names_out_          = None
    self.X_train_direct_features_names_out_   = None
    self.in_sample_residuals_                 = None
    self.out_sample_residuals_                = None
    self.in_sample_residuals_by_bin_          = None
    self.out_sample_residuals_by_bin_         = None
    self.filter_train_X_y_index_cache_        = {}
    self.filter_train_X_y_columns_cache_      = {}
    self.creation_date                        = pd.Timestamp.today().strftime('%Y-%m-%d %H:%M:%S')
    self.is_fitted                            = False
    self.fit_date                             = None
    self.skforecast_version                   = __version__
    self.python_version                       = sys.version.split(" ")[0]
    self.forecaster_id                        = forecaster_id
    self._probabilistic_mode                  = "binned"
    self.encoding                             = None   # Ignored in this forecaster

    if not isinstance(level, str):
        raise TypeError(
            f"`level` argument must be a str. Got {type(level)}."
        )

    if not isinstance(steps, int):
        raise TypeError(
            f"`steps` argument must be an int greater than or equal to 1. "
            f"Got {type(steps)}."
        )

    if steps < 1:
        raise ValueError(
            f"`steps` argument must be greater than or equal to 1. Got {steps}."
        )

    self.steps    = np.arange(steps) + 1
    self.max_step = steps

    self.estimators_ = {step: clone(self.estimator) for step in self.steps}

    if isinstance(lags, dict):
        self.lags = {}
        self.lags_names = {}
        list_max_lags = []
        for key in lags:
            if lags[key] is None:
                self.lags[key] = None
                self.lags_names[key] = None
            else:
                self.lags[key], lags_names, max_lag = initialize_lags(
                    forecaster_name = type(self).__name__,
                    lags            = lags[key]
                )
                self.lags_names[key] = (
                    [f'{key}_{lag}' for lag in lags_names] 
                     if lags_names is not None 
                     else None
                )
                if max_lag is not None:
                    list_max_lags.append(max_lag)

        self.max_lag = max(list_max_lags) if len(list_max_lags) != 0 else None
    else:
        self.lags, self.lags_names, self.max_lag = initialize_lags(
            forecaster_name = type(self).__name__, 
            lags            = lags
        )

    self.window_features, self.window_features_names, self.max_size_window_features = (
        initialize_window_features(window_features)
    )
    if self.window_features is None and (self.lags is None or self.max_lag is None):
        raise ValueError(
            "At least one of the arguments `lags` or `window_features` "
            "must be different from None. This is required to create the "
            "predictors used in training the forecaster."
        )

    self.window_size = max(
        [ws for ws in [self.max_lag, self.max_size_window_features] 
         if ws is not None]
    )
    self.window_features_class_names = None
    if window_features is not None:
        self.window_features_class_names = [
            type(wf).__name__ for wf in self.window_features
        ]

    if categorical_features is not None:
        if not (
            (isinstance(categorical_features, str) and categorical_features == 'auto')
            or isinstance(categorical_features, list)
        ):
            raise ValueError(
                f"Argument `categorical_features` must be `'auto'`, a list of "
                f"column names, or `None`. Got {categorical_features}."
            )
        if isinstance(categorical_features, list):
            if len(categorical_features) == 0:
                raise ValueError(
                    "Argument `categorical_features` must not be an empty list. "
                    "Use `None` to disable categorical encoding."
                )

    self.categorical_encoder = OrdinalEncoder(
                                   dtype                 = float,
                                   handle_unknown        = 'use_encoded_value',
                                   unknown_value         = np.nan,
                                   encoded_missing_value = np.nan
                               ).set_output(transform="pandas")

    self.weight_func, self.source_code_weight_func, _ = initialize_weights(
        forecaster_name = type(self).__name__, 
        estimator       = estimator, 
        weight_func     = weight_func, 
        series_weights  = None
    )

    if differentiation is not None:
        if not isinstance(differentiation, int) or differentiation < 1:
            raise ValueError(
                f"Argument `differentiation` must be an integer equal to or "
                f"greater than 1. Got {differentiation}."
            )
        self.differentiation = differentiation
        self.differentiation_max = differentiation
        self.window_size += differentiation
        self.differentiator = TimeSeriesDifferentiator(
            order=differentiation, window_size=self.window_size
        )

    self.fit_kwargs = check_select_fit_kwargs(
                          estimator  = estimator,
                          fit_kwargs = fit_kwargs
                      )

    self.binner = {}
    self.binner_intervals_ = {}
    self.binner_kwargs = binner_kwargs
    if binner_kwargs is None:
        self.binner_kwargs = {
            'n_bins': 10, 'method': 'linear', 'subsample': 200000,
            'random_state': 789654, 'dtype': np.float64
        }

    if n_jobs == 'auto':
        self.n_jobs = select_n_jobs_fit_forecaster(
                          forecaster_name = type(self).__name__,
                          estimator       = self.estimator
                      )
    else:
        if not isinstance(n_jobs, int):
            raise TypeError(
                f"`n_jobs` must be an integer or `'auto'`. Got {type(n_jobs)}."
            )
        self.n_jobs = n_jobs if n_jobs > 0 else cpu_count()

    self.__skforecast_tags__ = {
        "library": "skforecast",
        "forecaster_name": "ForecasterDirectMultiVariate",
        "forecaster_task": "regression",
        "forecasting_scope": "global",  # single-series | global
        "forecasting_strategy": "direct",  # recursive | direct | deep_learning | foundation
        "multiple_estimators": False,
        "index_types_supported": ["pandas.RangeIndex", "pandas.DatetimeIndex"],
        "requires_index_frequency": True,

        "allowed_input_types_series": ["pandas.DataFrame"],
        "supports_exog": True,
        "allowed_input_types_exog": ["pandas.Series", "pandas.DataFrame"],
        "handles_missing_values_series": True, 
        "handles_missing_values_exog": True, 

        "supports_lags": True,
        "supports_window_features": True,
        "supports_calendar_features": True,
        "supports_transformer_series": True,
        "supports_transformer_exog": True,
        "supports_categorical_features": True,
        "supports_weight_func": True,
        "supports_series_weights": False,
        "supports_differentiation": True,

        "prediction_types": ["point", "interval", "bootstrapping", "quantiles", "distribution"],
        "supports_probabilistic": True,
        "probabilistic_methods": ["bootstrapping", "conformal"],
        "handles_binned_residuals": True
    }

Attributes¶

estimator instance-attribute ¶

estimator = clone(estimator)

calendar_features instance-attribute ¶

calendar_features = (
    clone(calendar_features)
    if calendar_features is not None
    else None
)

calendar_features_names instance-attribute ¶

calendar_features_names = getattr(
    calendar_features, "features", None
)

level instance-attribute ¶

level = level

lags_ instance-attribute ¶

lags_ = None

transformer_series instance-attribute ¶

transformer_series = transformer_series

transformer_series_ instance-attribute ¶

transformer_series_ = None

transformer_exog instance-attribute ¶

transformer_exog = transformer_exog

categorical_features instance-attribute ¶

categorical_features = categorical_features

weight_func instance-attribute ¶

weight_func = weight_func

source_code_weight_func instance-attribute ¶

source_code_weight_func = None

differentiation instance-attribute ¶

differentiation = differentiation

differentiation_max instance-attribute ¶

differentiation_max = None

differentiator instance-attribute ¶

differentiator = None

differentiator_ instance-attribute ¶

differentiator_ = None

dropna_from_series instance-attribute ¶

dropna_from_series = dropna_from_series

last_window_ instance-attribute ¶

last_window_ = None

index_type_ instance-attribute ¶

index_type_ = None

index_freq_ instance-attribute ¶

index_freq_ = None

training_range_ instance-attribute ¶

training_range_ = None

series_names_in_ instance-attribute ¶

series_names_in_ = None

exog_in_ instance-attribute ¶

exog_in_ = False

exog_names_in_ instance-attribute ¶

exog_names_in_ = None

exog_type_in_ instance-attribute ¶

exog_type_in_ = None

exog_dtypes_in_ instance-attribute ¶

exog_dtypes_in_ = None

exog_dtypes_out_ instance-attribute ¶

exog_dtypes_out_ = None

categorical_features_names_in_ instance-attribute ¶

categorical_features_names_in_ = None

X_train_series_names_in_ instance-attribute ¶

X_train_series_names_in_ = None

X_train_window_features_names_out_ instance-attribute ¶

X_train_window_features_names_out_ = None

X_train_calendar_features_names_out_ instance-attribute ¶

X_train_calendar_features_names_out_ = None

X_train_exog_names_out_ instance-attribute ¶

X_train_exog_names_out_ = None

X_train_direct_exog_names_out_ instance-attribute ¶

X_train_direct_exog_names_out_ = None

X_train_features_names_out_ instance-attribute ¶

X_train_features_names_out_ = None

X_train_direct_features_names_out_ instance-attribute ¶

X_train_direct_features_names_out_ = None

in_sample_residuals_ instance-attribute ¶

in_sample_residuals_ = None

out_sample_residuals_ instance-attribute ¶

out_sample_residuals_ = None

in_sample_residuals_by_bin_ instance-attribute ¶

in_sample_residuals_by_bin_ = None

out_sample_residuals_by_bin_ instance-attribute ¶

out_sample_residuals_by_bin_ = None

filter_train_X_y_index_cache_ instance-attribute ¶

filter_train_X_y_index_cache_ = {}

filter_train_X_y_columns_cache_ instance-attribute ¶

filter_train_X_y_columns_cache_ = {}

creation_date instance-attribute ¶

creation_date = pd.Timestamp.today().strftime(
    "%Y-%m-%d %H:%M:%S"
)

is_fitted instance-attribute ¶

is_fitted = False

fit_date instance-attribute ¶

fit_date = None

skforecast_version instance-attribute ¶

skforecast_version = __version__

python_version instance-attribute ¶

python_version = sys.version.split(' ')[0]

forecaster_id instance-attribute ¶

forecaster_id = forecaster_id

encoding instance-attribute ¶

encoding = None

steps instance-attribute ¶

steps = np.arange(steps) + 1

max_step instance-attribute ¶

max_step = steps

estimators_ instance-attribute ¶

estimators_ = {
    step: clone(self.estimator) for step in self.steps
}

lags instance-attribute ¶

lags = {}

lags_names instance-attribute ¶

lags_names = {}

max_lag instance-attribute ¶

max_lag = (
    max(list_max_lags) if len(list_max_lags) != 0 else None
)

window_size instance-attribute ¶

window_size = max(
    [
        ws
        for ws in [
            self.max_lag,
            self.max_size_window_features,
        ]
        if ws is not None
    ]
)

window_features_class_names instance-attribute ¶

window_features_class_names = None

categorical_encoder instance-attribute ¶

categorical_encoder = OrdinalEncoder(
    dtype=float,
    handle_unknown="use_encoded_value",
    unknown_value=np.nan,
    encoded_missing_value=np.nan,
).set_output(transform="pandas")

fit_kwargs instance-attribute ¶

fit_kwargs = check_select_fit_kwargs(
    estimator=estimator, fit_kwargs=fit_kwargs
)

binner instance-attribute ¶

binner = {}

binner_intervals_ instance-attribute ¶

binner_intervals_ = {}

binner_kwargs instance-attribute ¶

binner_kwargs = binner_kwargs

n_jobs instance-attribute ¶

n_jobs = select_n_jobs_fit_forecaster(
    forecaster_name=type(self).__name__,
    estimator=self.estimator,
)

Methods:¶

create_train_X_y ¶

create_train_X_y(
    series, exog=None, suppress_warnings=False
)

Create training matrices from multiple time series and exogenous variables. The resulting matrices contain the target variable and predictors needed to train all the estimators (one per step).

Parameters:

Name Type Description Default
series pandas DataFrame

Training time series.

required
exog pandas Series, pandas DataFrame

Exogenous variable/s included as predictor/s. Must have the same number of observations as series and their indexes must be aligned.

None
suppress_warnings bool

If True, skforecast warnings will be suppressed during the creation of the training matrices. See skforecast.exceptions.warn_skforecast_categories for more information.

False

Returns:

Name Type Description
X_train pandas DataFrame

Training values (predictors) for each step. Note that the index corresponds to that of the last step. It is updated for the corresponding step in the filter_train_X_y_for_step method.

y_train dict

Values of the time series related to each row of X_train for each step in the form {step: y_step_[i]}.

Notes

If series or exog contain interspersed NaN values, rows where y_train is NaN are always removed per step. Rows where X_train contains NaN (from lagged NaN in series or from NaN in exog) are removed only if dropna_from_series=True; otherwise a warning is issued. Because each step has its own target, NaN filtering is applied per step during fitting rather than globally.

Source code in skforecast/direct/_forecaster_direct_multivariate.py
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
@manage_warnings
def create_train_X_y(
    self,
    series: pd.DataFrame,
    exog: pd.Series | pd.DataFrame | None = None,
    suppress_warnings: bool = False
) -> tuple[pd.DataFrame, dict[int, pd.Series]]:
    """
    Create training matrices from multiple time series and exogenous
    variables. The resulting matrices contain the target variable and predictors
    needed to train all the estimators (one per step).

    Parameters
    ----------
    series : pandas DataFrame
        Training time series.
    exog : pandas Series, pandas DataFrame, default None
        Exogenous variable/s included as predictor/s. Must have the same
        number of observations as `series` and their indexes must be aligned.
    suppress_warnings : bool, default False
        If `True`, skforecast warnings will be suppressed during the creation
        of the training matrices. See skforecast.exceptions.warn_skforecast_categories 
        for more information.

    Returns
    -------
    X_train : pandas DataFrame
        Training values (predictors) for each step. Note that the index 
        corresponds to that of the last step. It is updated for the corresponding 
        step in the filter_train_X_y_for_step method.
    y_train : dict
        Values of the time series related to each row of `X_train` for each 
        step in the form {step: y_step_[i]}.

    Notes
    -----
    If `series` or `exog` contain interspersed NaN values, rows where `y_train`
    is NaN are always removed per step. Rows where `X_train` contains NaN
    (from lagged NaN in `series` or from NaN in `exog`) are removed only if
    `dropna_from_series=True`; otherwise a warning is issued. Because each
    step has its own target, NaN filtering is applied per step during
    fitting rather than globally.

    """

    (
        X_train_autoreg,
        X_train_exog,
        X_train_calendar,
        y_train,
        train_index,
        _,
        _,
        _,
        _,
        _,
        _,
        X_train_direct_features_names_out_,
        _,
        exog_dtypes_out_
    ) = self._create_train_X_y(series=series, exog=exog)

    X_train = [X_train_autoreg]
    if X_train_exog is not None:
        exog_direct, _ = exog_to_direct_numpy(
            exog=X_train_exog, steps=self.max_step
        )
        X_train.append(exog_direct)
    if X_train_calendar is not None:
        calendar_direct, _ = exog_to_direct_numpy(
            exog=X_train_calendar, steps=self.max_step
        )
        X_train.append(calendar_direct)

    if len(X_train) == 1:
        X_train = X_train[0]
    else:
        X_train = np.concatenate(X_train, axis=1)

    X_train = pd.DataFrame(
                  data    = X_train,
                  index   = train_index[self.max_step],
                  columns = X_train_direct_features_names_out_
              )

    if exog_dtypes_out_ is not None:
        X_train_dtypes = {col: float for col in X_train_direct_features_names_out_}
        exog_dtypes_direct = {
            f"{col}_step_{i + 1}": dtype
            for col, dtype in exog_dtypes_out_.items()
            for i in range(self.max_step)
        }
        X_train_dtypes.update(exog_dtypes_direct)
        X_train = X_train.astype(X_train_dtypes, copy=False)

    y_train = {
        step: pd.Series(
                  data  = y_train[step],
                  index = train_index[step],
                  name  = f"{self.level}_step_{step}"
              )
        for step in self.steps
    }

    return X_train, y_train

filter_train_X_y_for_step ¶

filter_train_X_y_for_step(
    step, X_train, y_train, remove_suffix=False
)

Select the columns needed to train a forecaster for a specific step.
The input matrices should be created using create_train_X_y method. This method updates the index of X_train to the corresponding one according to y_train. If remove_suffix=True the suffix "_step_i" will be removed from the column names.

Parameters:

Name Type Description Default
step int

Step for which columns must be selected. Starts at 1.

required
X_train pandas DataFrame

Training data created with create_train_X_y.

required
y_train dict

Dict created with create_train_X_y.

required
remove_suffix bool

If True, suffix "_step_i" is removed from the column names.

False

Returns:

Name Type Description
X_train_step pandas DataFrame

Training values (predictors) for the selected step.

y_train_step pandas Series

Values of the time series related to each row of X_train.

Source code in skforecast/direct/_forecaster_direct_multivariate.py
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
def filter_train_X_y_for_step(
    self,
    step: int,
    X_train: pd.DataFrame,
    y_train: dict[int, pd.Series],
    remove_suffix: bool = False
) -> tuple[pd.DataFrame, pd.Series]:
    """
    Select the columns needed to train a forecaster for a specific step.  
    The input matrices should be created using `create_train_X_y` method. 
    This method updates the index of `X_train` to the corresponding one 
    according to `y_train`. If `remove_suffix=True` the suffix "_step_i" 
    will be removed from the column names.

    Parameters
    ----------
    step : int
        Step for which columns must be selected. Starts at 1.
    X_train : pandas DataFrame
        Training data created with `create_train_X_y`.
    y_train : dict
        Dict created with `create_train_X_y`.
    remove_suffix : bool, default False
        If True, suffix "_step_i" is removed from the column names.

    Returns
    -------
    X_train_step : pandas DataFrame
        Training values (predictors) for the selected step.
    y_train_step : pandas Series
        Values of the time series related to each row of `X_train`.

    """

    if (step < 1) or (step > self.max_step):
        raise ValueError(
            f"Invalid value `step`. For this forecaster, minimum value is 1 "
            f"and the maximum step is {self.max_step}."
        )

    y_train_step = y_train[step]

    has_exog = self.exog_in_
    has_calendar = self.calendar_features is not None
    if not has_exog and not has_calendar:
        X_train_step = X_train
    else:
        if step not in self.filter_train_X_y_index_cache_:

            n_lags = len(list(
                chain(*[v for v in self.lags_.values() if v is not None])
            ))
            n_window_features = (
                len(self.X_train_window_features_names_out_) if self.window_features is not None else 0
            )
            n_autoreg = n_lags + n_window_features
            idx_columns = [np.arange(n_autoreg)]
            offset = n_autoreg

            if has_exog:
                n_exog = len(self.X_train_direct_exog_names_out_) // self.max_step
                idx_columns.append(
                    np.arange(
                        offset + (step - 1) * n_exog,
                        offset + step * n_exog
                    )
                )
                offset += n_exog * self.max_step

            if has_calendar:
                n_calendar = len(self.X_train_calendar_features_names_out_)
                idx_columns.append(
                    np.arange(
                        offset + (step - 1) * n_calendar,
                        offset + step * n_calendar
                    )
                )
                offset += n_calendar * self.max_step

            idx_columns = np.concatenate(idx_columns)
            self.filter_train_X_y_index_cache_[step] = idx_columns

        idx_columns = self.filter_train_X_y_index_cache_[step]
        X_train_step = X_train.iloc[:, idx_columns]

    X_train_step.index = y_train_step.index

    if remove_suffix:
        if step not in self.filter_train_X_y_columns_cache_:
            new_columns = [
                col_name.replace(f"_step_{step}", "")
                for col_name in X_train_step.columns
            ]
            self.filter_train_X_y_columns_cache_[step] = new_columns

        X_train_step.columns = self.filter_train_X_y_columns_cache_[step]
        y_train_step.name = y_train_step.name.replace(f"_step_{step}", "")

    # NaN filtering: same logic as _filter_nan_X_y_step but on pandas
    nan_y = y_train_step.isna()
    if nan_y.any():
        y_train_step = y_train_step[~nan_y]
        X_train_step = X_train_step[~nan_y]

    if self.dropna_from_series:
        nan_X = X_train_step.isna().any(axis=1)
        if nan_X.any():
            X_train_step = X_train_step[~nan_X]
            y_train_step = y_train_step[~nan_X]

    return X_train_step, y_train_step

create_sample_weights ¶

create_sample_weights(X_train)

Create weights for each observation according to the forecaster's attribute weight_func.

Parameters:

Name Type Description Default
X_train pandas DataFrame, pandas Index

Dataframe created with _create_train_X_y and filter_train_X_y_for_step methods, first return, or the index of the dataframe.

required

Returns:

Name Type Description
sample_weight numpy ndarray

Weights to use in fit method.

Source code in skforecast/direct/_forecaster_direct_multivariate.py
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
def create_sample_weights(
    self,
    X_train: pd.DataFrame | pd.Index
) -> np.ndarray:
    """
    Create weights for each observation according to the forecaster's attribute
    `weight_func`. 

    Parameters
    ----------
    X_train : pandas DataFrame, pandas Index
        Dataframe created with `_create_train_X_y` and `filter_train_X_y_for_step`
        methods, first return, or the index of the dataframe.

    Returns
    -------
    sample_weight : numpy ndarray
        Weights to use in `fit` method.

    """

    sample_weight = None

    if self.weight_func is not None:
        sample_weight = self.weight_func(
            X_train.index if isinstance(X_train, pd.DataFrame) else X_train
        )

    if sample_weight is not None:
        if np.isnan(sample_weight).any():
            raise ValueError(
                "The resulting `sample_weight` cannot have NaN values."
            )
        if np.any(sample_weight < 0):
            raise ValueError(
                "The resulting `sample_weight` cannot have negative values."
            )
        if np.sum(sample_weight) == 0:
            raise ValueError(
                ("The resulting `sample_weight` cannot be normalized because "
                 "the sum of the weights is zero.")
            )

    return sample_weight

fit ¶

fit(
    series,
    exog=None,
    store_last_window=True,
    store_in_sample_residuals=False,
    random_state=123,
    suppress_warnings=False,
)

Training Forecaster.

Additional arguments to be passed to the fit method of the estimator can be added with the fit_kwargs argument when initializing the forecaster.

Parameters:

Name Type Description Default
series pandas DataFrame

Training time series.

required
exog pandas Series, pandas DataFrame

Exogenous variable/s included as predictor/s. Must have the same number of observations as series and their indexes must be aligned so that series[i] is regressed on exog[i].

None
store_last_window bool

Whether or not to store the last window (last_window_) of training data.

True
store_in_sample_residuals bool

If True, in-sample residuals will be stored in the forecaster object after fitting (in_sample_residuals_ and in_sample_residuals_by_bin_ attributes). If False, only the intervals of the bins are stored.

False
random_state int

Set a seed for the random generator so that the stored sample residuals are always deterministic.

123
suppress_warnings bool

If True, skforecast warnings will be suppressed during the training process. See skforecast.exceptions.warn_skforecast_categories for more information.

False

Returns:

Type Description
None
Source code in skforecast/direct/_forecaster_direct_multivariate.py
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
@manage_warnings
def fit(
    self,
    series: pd.DataFrame,
    exog: pd.Series | pd.DataFrame | None = None,
    store_last_window: bool = True,
    store_in_sample_residuals: bool = False,
    random_state: int = 123,
    suppress_warnings: bool = False
) -> None:
    """
    Training Forecaster.

    Additional arguments to be passed to the `fit` method of the estimator 
    can be added with the `fit_kwargs` argument when initializing the forecaster.

    Parameters
    ----------
    series : pandas DataFrame
        Training time series.
    exog : pandas Series, pandas DataFrame, default None
        Exogenous variable/s included as predictor/s. Must have the same
        number of observations as `series` and their indexes must be aligned so
        that series[i] is regressed on exog[i].
    store_last_window : bool, default True
        Whether or not to store the last window (`last_window_`) of training data.
    store_in_sample_residuals : bool, default False
        If `True`, in-sample residuals will be stored in the forecaster object
        after fitting (`in_sample_residuals_` and `in_sample_residuals_by_bin_`
        attributes).
        If `False`, only the intervals of the bins are stored.
    random_state : int, default 123
        Set a seed for the random generator so that the stored sample 
        residuals are always deterministic.
    suppress_warnings : bool, default False
        If `True`, skforecast warnings will be suppressed during the training 
        process. See skforecast.exceptions.warn_skforecast_categories for more
        information.

    Returns
    -------
    None

    """

    # Reset values in case the forecaster has already been fitted.
    self.lags_                                = None
    self.last_window_                         = None
    self.index_type_                          = None
    self.index_freq_                          = None
    self.training_range_                      = None
    self.series_names_in_                     = None
    self.exog_in_                             = False
    self.exog_names_in_                       = None
    self.exog_type_in_                        = None
    self.exog_dtypes_in_                      = None
    self.exog_dtypes_out_                     = None
    self.categorical_features_names_in_       = None
    self.X_train_series_names_in_             = None
    self.X_train_window_features_names_out_   = None
    self.X_train_calendar_features_names_out_ = None
    self.X_train_exog_names_out_              = None
    self.X_train_direct_exog_names_out_       = None
    self.X_train_features_names_out_          = None
    self.X_train_direct_features_names_out_   = None
    self.in_sample_residuals_                 = None
    self.in_sample_residuals_by_bin_          = None
    self.out_sample_residuals_                = None
    self.out_sample_residuals_by_bin_         = None
    self.binner                               = {}
    self.binner_intervals_                    = {}
    self.filter_train_X_y_index_cache_        = {}
    self.filter_train_X_y_columns_cache_      = {}
    self.is_fitted                            = False
    self.fit_date                             = None

    (
        X_train_autoreg,
        X_train_exog,
        X_train_calendar,
        y_train,
        train_index,
        series_names_in_,
        X_train_series_names_in_,
        exog_names_in_,
        categorical_features_names_in_,
        X_train_exog_names_out_,
        X_train_features_names_out_,
        X_train_direct_features_names_out_,
        exog_dtypes_in_,
        exog_dtypes_out_
    ) = self._create_train_X_y(series=series, exog=exog)

    if X_train_exog_names_out_ is not None:
        # NOTE: Need here as configure_estimator_categorical_features uses it
        self.categorical_features_names_in_ = categorical_features_names_in_

    results_fit = Parallel(n_jobs=self.n_jobs)(
        delayed(_fit_one_step_estimator)(
            forecaster                  = self,
            estimator                   = clone(self.estimator),
            X_train_autoreg             = X_train_autoreg,
            X_train_exog                = X_train_exog,
            X_train_calendar            = X_train_calendar,
            y_train                     = y_train,
            train_index                 = train_index,
            X_train_features_names_out_ = X_train_features_names_out_,
            step                        = step
        )
        for step in self.steps
    )

    self.estimators_ = {step: estimator for step, estimator, *_ in results_fit}

    self.in_sample_residuals_ = {}
    self.in_sample_residuals_by_bin_ = {}
    if self._probabilistic_mode is not False:
        for level in [self.level]:
            y_true_level = [y_true_step for _, _, y_true_step, _ in results_fit]
            y_pred_level = [y_pred_step for _, _, _, y_pred_step in results_fit]
            self._binning_in_sample_residuals(
                level                     = level,
                y_true                    = np.concatenate(y_true_level),
                y_pred                    = np.concatenate(y_pred_level),
                store_in_sample_residuals = store_in_sample_residuals,
                random_state              = random_state
            )

    if not store_in_sample_residuals:
        for level in [self.level]:
            self.in_sample_residuals_[level] = None
            self.in_sample_residuals_by_bin_[level] = None

    self.series_names_in_ = series_names_in_
    self.X_train_series_names_in_ = X_train_series_names_in_
    self.X_train_features_names_out_ = X_train_features_names_out_
    self.X_train_direct_features_names_out_ = X_train_direct_features_names_out_

    self.is_fitted = True
    self.fit_date = pd.Timestamp.today().strftime('%Y-%m-%d %H:%M:%S')
    self.training_range_ = series.index[[0, -1]]
    self.index_type_ = type(series.index)
    if isinstance(series.index, pd.DatetimeIndex):
        self.index_freq_ = series.index.freq
    else: 
        self.index_freq_ = series.index.step

    if exog is not None:
        self.exog_in_ = True
        self.exog_names_in_ = exog_names_in_
        self.exog_type_in_ = type(exog)
        self.exog_dtypes_in_ = exog_dtypes_in_
        self.exog_dtypes_out_ = exog_dtypes_out_
        self.X_train_exog_names_out_ = X_train_exog_names_out_

    if store_last_window:
        self.last_window_ = series.iloc[-self.window_size:, ][
            self.X_train_series_names_in_
        ].copy()

create_predict_X ¶

create_predict_X(
    steps=None,
    last_window=None,
    exog=None,
    suppress_warnings=False,
    check_inputs=True,
    levels=None,
)

Create the predictors needed to predict steps ahead.

Parameters:

Name Type Description Default
steps (int, list, None)

Predict n steps. The value of steps must be less than or equal to the value of steps defined when initializing the forecaster. Starts at 1.

  • If int: Only steps within the range of 1 to int are predicted.
  • If list: List of ints. Only the steps contained in the list are predicted.
  • If None: As many steps are predicted as were defined at initialization.
None
last_window pandas DataFrame

Series values used to create the predictors (lags) needed to predict steps. If last_window = None, the values stored in self.last_window_ are used to calculate the initial predictors, and the predictions start right after training data.

None
exog pandas Series, pandas DataFrame

Exogenous variable/s included as predictor/s.

None
suppress_warnings bool

If True, skforecast warnings will be suppressed during the prediction process. See skforecast.exceptions.warn_skforecast_categories for more information.

False
check_inputs bool

If True, the input is checked for possible warnings and errors with the check_predict_input function. This argument is created for internal use and is not recommended to be changed.

True
levels Ignored

Not used, present here for API consistency by convention.

None

Returns:

Name Type Description
X_predict pandas DataFrame

Pandas DataFrame with the predictors for each step. The index is the same as the prediction index.

Source code in skforecast/direct/_forecaster_direct_multivariate.py
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
@manage_warnings
def create_predict_X(
    self,
    steps: int | list[int] | None = None,
    last_window: pd.DataFrame | None = None,
    exog: pd.Series | pd.DataFrame | None = None,
    suppress_warnings: bool = False,
    check_inputs: bool = True,
    levels: Any = None
) -> pd.DataFrame:
    """
    Create the predictors needed to predict `steps` ahead.

    Parameters
    ----------
    steps : int, list, None, default None
        Predict n steps. The value of `steps` must be less than or equal to the 
        value of steps defined when initializing the forecaster. Starts at 1.

        - If `int`: Only steps within the range of 1 to int are predicted.
        - If `list`: List of ints. Only the steps contained in the list 
        are predicted.
        - If `None`: As many steps are predicted as were defined at 
        initialization.
    last_window : pandas DataFrame, default None
        Series values used to create the predictors (lags) needed to 
        predict `steps`.
        If `last_window = None`, the values stored in `self.last_window_` are
        used to calculate the initial predictors, and the predictions start
        right after training data.
    exog : pandas Series, pandas DataFrame, default None
        Exogenous variable/s included as predictor/s.
    suppress_warnings : bool, default False
        If `True`, skforecast warnings will be suppressed during the prediction 
        process. See skforecast.exceptions.warn_skforecast_categories for more
        information.
    check_inputs : bool, default True
        If `True`, the input is checked for possible warnings and errors 
        with the `check_predict_input` function. This argument is created 
        for internal use and is not recommended to be changed.
    levels : Ignored
        Not used, present here for API consistency by convention.

    Returns
    -------
    X_predict : pandas DataFrame
        Pandas DataFrame with the predictors for each step. The index 
        is the same as the prediction index.

    """

    (
        Xs,
        Xs_col_names,
        steps,
        prediction_index,
        _
    ) = self._create_predict_inputs(
            steps        = steps,
            last_window  = last_window,
            exog         = exog,
            check_inputs = check_inputs
        )

    X_predict = pd.DataFrame(
                    data    = np.concatenate(Xs, axis=0), 
                    columns = Xs_col_names, 
                    index   = prediction_index
                )
    X_predict.insert(0, 'level', np.tile([self.level], len(steps)))

    if self.exog_in_:
        X_predict_dtypes = {col: float for col in Xs_col_names}
        X_predict_dtypes.update(self.exog_dtypes_out_)
        X_predict = X_predict.astype(X_predict_dtypes, copy=False)

    if self.transformer_series is not None or self.differentiation is not None:
        warnings.warn(
            "The output matrix is in the transformed scale due to the "
            "inclusion of transformations or differentiation in the Forecaster. "
            "As a result, any predictions generated using this matrix will also "
            "be in the transformed scale. Please refer to the documentation "
            "for more details: "
            "https://skforecast.org/latest/user_guides/training-and-prediction-matrices.html",
            DataTransformationWarning
        )

    return X_predict

predict ¶

predict(
    steps=None,
    last_window=None,
    exog=None,
    suppress_warnings=False,
    check_inputs=True,
    levels=None,
)

Predict n steps ahead

Parameters:

Name Type Description Default
steps (int, list, None)

Predict n steps. The value of steps must be less than or equal to the value of steps defined when initializing the forecaster. Starts at 1.

  • If int: Only steps within the range of 1 to int are predicted.
  • If list: List of ints. Only the steps contained in the list are predicted.
  • If None: As many steps are predicted as were defined at initialization.
None
last_window pandas DataFrame

Series values used to create the predictors (lags) needed to predict steps. If last_window = None, the values stored in self.last_window_ are used to calculate the initial predictors, and the predictions start right after training data.

None
exog pandas Series, pandas DataFrame

Exogenous variable/s included as predictor/s.

None
suppress_warnings bool

If True, skforecast warnings will be suppressed during the prediction process. See skforecast.exceptions.warn_skforecast_categories for more information.

False
check_inputs bool

If True, the input is checked for possible warnings and errors with the check_predict_input function. This argument is created for internal use and is not recommended to be changed.

True
levels Ignored

Not used, present here for API consistency by convention.

None

Returns:

Name Type Description
predictions pandas DataFrame

Long-format DataFrame with the predictions. The columns are level and pred.

Source code in skforecast/direct/_forecaster_direct_multivariate.py
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
@manage_warnings
def predict(
    self,
    steps: int | list[int] | None = None,
    last_window: pd.DataFrame | None = None,
    exog: pd.Series | pd.DataFrame | None = None,
    suppress_warnings: bool = False,
    check_inputs: bool = True,
    levels: Any = None
) -> pd.DataFrame:
    """
    Predict n steps ahead

    Parameters
    ----------
    steps : int, list, None, default None
        Predict n steps. The value of `steps` must be less than or equal to the 
        value of steps defined when initializing the forecaster. Starts at 1.

        - If `int`: Only steps within the range of 1 to int are predicted.
        - If `list`: List of ints. Only the steps contained in the list 
        are predicted.
        - If `None`: As many steps are predicted as were defined at 
        initialization.
    last_window : pandas DataFrame, default None
        Series values used to create the predictors (lags) needed to 
        predict `steps`.
        If `last_window = None`, the values stored in `self.last_window_` are
        used to calculate the initial predictors, and the predictions start
        right after training data.
    exog : pandas Series, pandas DataFrame, default None
        Exogenous variable/s included as predictor/s.
    suppress_warnings : bool, default False
        If `True`, skforecast warnings will be suppressed during the prediction 
        process. See skforecast.exceptions.warn_skforecast_categories for more
        information.
    check_inputs : bool, default True
        If `True`, the input is checked for possible warnings and errors 
        with the `check_predict_input` function. This argument is created 
        for internal use and is not recommended to be changed.
    levels : Ignored
        Not used, present here for API consistency by convention.

    Returns
    -------
    predictions : pandas DataFrame
        Long-format DataFrame with the predictions. The columns are `level`
        and `pred`.

    """

    (
        Xs,
        _,
        steps,
        prediction_index,
        differentiator
    ) = self._create_predict_inputs(
            steps        = steps,
            last_window  = last_window,
            exog         = exog,
            check_inputs = check_inputs,
        )

    predictions = self._direct_predict(steps=steps, Xs=Xs)

    if differentiator is not None:
        predictions = differentiator.inverse_transform_next_window(predictions)

    predictions = transform_numpy(
                      array             = predictions,
                      transformer       = self.transformer_series_[self.level],
                      fit               = False,
                      inverse_transform = True
                  )

    # NOTE: This DataFrame has freq because it only contain 1 level
    predictions = pd.DataFrame(
        {"level": np.tile([self.level], len(steps)), "pred": predictions},
        index = prediction_index,
    )

    return predictions

predict_bootstrapping ¶

predict_bootstrapping(
    steps=None,
    last_window=None,
    exog=None,
    n_boot=250,
    random_state=123,
    use_in_sample_residuals=True,
    use_binned_residuals=True,
    suppress_warnings=False,
    levels=None,
)

Generate multiple forecasting predictions using a bootstrapping process. By sampling from a collection of past observed errors (the residuals), each iteration of bootstrapping generates a different set of predictions. See the References section for more information.

Parameters:

Name Type Description Default
steps (int, list, None)

Predict n steps. The value of steps must be less than or equal to the value of steps defined when initializing the forecaster. Starts at 1.

  • If int: Only steps within the range of 1 to int are predicted.
  • If list: List of ints. Only the steps contained in the list are predicted.
  • If None: As many steps are predicted as were defined at initialization.
None
last_window pandas DataFrame

Series values used to create the predictors (lags) needed to predict steps. If last_window = None, the values stored inself.last_window_ are used to calculate the initial predictors, and the predictions start right after training data.

None
exog pandas Series, pandas DataFrame

Exogenous variable/s included as predictor/s.

None
n_boot int

Number of bootstrapping iterations to perform when estimating prediction intervals.

250
use_in_sample_residuals bool

If True, residuals from the training data are used as proxy of prediction error to create predictions. If False, out of sample residuals (calibration) are used. Out-of-sample residuals must be precomputed using Forecaster's set_out_sample_residuals() method.

True
use_binned_residuals bool

If True, residuals are selected based on the predicted values (binned selection). If False, residuals are selected randomly.

True
random_state int

Seed for the random number generator to ensure reproducibility.

123
suppress_warnings bool

If True, skforecast warnings will be suppressed during the prediction process. See skforecast.exceptions.warn_skforecast_categories for more information.

False
levels Ignored

Not used, present here for API consistency by convention.

None

Returns:

Name Type Description
boot_predictions pandas DataFrame

Long-format DataFrame with the bootstrapping predictions. The columns are level, pred_boot_0, pred_boot_1, ..., pred_boot_n_boot.

References

.. [1] MAPIE - Model Agnostic Prediction Interval Estimator. https://mapie.readthedocs.io/en/stable/content/conformal-prediction/regression/#2-the-split-method

Source code in skforecast/direct/_forecaster_direct_multivariate.py
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
@manage_warnings
def predict_bootstrapping(
    self,
    steps: int | list[int] | None = None,
    last_window: pd.DataFrame | None = None,
    exog: pd.Series | pd.DataFrame | None = None,
    n_boot: int = 250,
    random_state: int = 123,
    use_in_sample_residuals: bool = True,
    use_binned_residuals: bool = True,
    suppress_warnings: bool = False,
    levels: Any = None
) -> pd.DataFrame:
    """
    Generate multiple forecasting predictions using a bootstrapping process.
    By sampling from a collection of past observed errors (the residuals),
    each iteration of bootstrapping generates a different set of predictions.
    See the References section for more information.

    Parameters
    ----------
    steps : int, list, None, default None
        Predict n steps. The value of `steps` must be less than or equal to the 
        value of steps defined when initializing the forecaster. Starts at 1.

        - If `int`: Only steps within the range of 1 to int are predicted.
        - If `list`: List of ints. Only the steps contained in the list 
        are predicted.
        - If `None`: As many steps are predicted as were defined at 
        initialization.
    last_window : pandas DataFrame, default None
        Series values used to create the predictors (lags) needed to 
        predict `steps`.
        If `last_window = None`, the values stored in` self.last_window_` are
        used to calculate the initial predictors, and the predictions start
        right after training data.
    exog : pandas Series, pandas DataFrame, default None
        Exogenous variable/s included as predictor/s.     
    n_boot : int, default 250
        Number of bootstrapping iterations to perform when estimating prediction
        intervals.            
    use_in_sample_residuals : bool, default True
        If `True`, residuals from the training data are used as proxy of
        prediction error to create predictions. 
        If `False`, out of sample residuals (calibration) are used. 
        Out-of-sample residuals must be precomputed using Forecaster's
        `set_out_sample_residuals()` method.
    use_binned_residuals : bool, default True
        If `True`, residuals are selected based on the predicted values 
        (binned selection).
        If `False`, residuals are selected randomly.
    random_state : int, default 123
        Seed for the random number generator to ensure reproducibility.   
    suppress_warnings : bool, default False
        If `True`, skforecast warnings will be suppressed during the prediction 
        process. See skforecast.exceptions.warn_skforecast_categories for more
        information.
    levels : Ignored
        Not used, present here for API consistency by convention.

    Returns
    -------
    boot_predictions : pandas DataFrame
        Long-format DataFrame with the bootstrapping predictions. The columns
        are `level`, `pred_boot_0`, `pred_boot_1`, ..., `pred_boot_n_boot`.

    References
    ----------
    .. [1] MAPIE - Model Agnostic Prediction Interval Estimator.
           https://mapie.readthedocs.io/en/stable/content/conformal-prediction/regression/#2-the-split-method

    """

    (
        Xs,
        _,
        steps,
        prediction_index,
        differentiator
    ) = self._create_predict_inputs(
            steps                   = steps, 
            last_window             = last_window, 
            exog                    = exog,
            predict_probabilistic   = True, 
            use_in_sample_residuals = use_in_sample_residuals,
            use_binned_residuals    = use_binned_residuals
        )

    if use_in_sample_residuals:
        residuals = self.in_sample_residuals_[self.level]
        residuals_by_bin = self.in_sample_residuals_by_bin_[self.level]
    else:
        residuals = self.out_sample_residuals_[self.level]
        residuals_by_bin = self.out_sample_residuals_by_bin_[self.level]

    # NOTE: Predictors and residuals are transformed and differentiated
    predictions = self._direct_predict(steps=steps, Xs=Xs)

    rng = np.random.default_rng(seed=random_state)
    if not use_binned_residuals:
        sampled_residuals = residuals[
            rng.integers(low=0, high=residuals.size, size=(len(steps), n_boot))
        ]
    else:
        predicted_bins = self.binner[self.level].transform(predictions)
        sampled_residuals = np.full(
                                shape      = (predicted_bins.size, n_boot),
                                fill_value = np.nan,
                                order      = 'C',
                                dtype      = float
                            )
        for i, bin in enumerate(predicted_bins):
            sampled_residuals[i, :] = residuals_by_bin[bin][
                rng.integers(low=0, high=residuals_by_bin[bin].size, size=n_boot)
            ]

    boot_predictions = np.tile(predictions, (n_boot, 1)).T
    boot_columns = [f"pred_boot_{i}" for i in range(n_boot)]
    boot_predictions = boot_predictions + sampled_residuals

    if differentiator is not None:
        boot_predictions = (
            differentiator.inverse_transform_next_window(boot_predictions)
        )

    if self.transformer_series_[self.level]:
        boot_predictions = transform_numpy(
                               array             = boot_predictions,
                               transformer       = self.transformer_series_[self.level],
                               fit               = False,
                               inverse_transform = True
                           )

    # NOTE: This DataFrame has freq because it only contain 1 level
    boot_predictions = pd.DataFrame(
                           data    = boot_predictions,
                           index   = prediction_index,
                           columns = boot_columns
                       )
    boot_predictions.insert(0, 'level', np.tile([self.level], len(steps)))

    return boot_predictions

predict_interval ¶

predict_interval(
    steps=None,
    last_window=None,
    exog=None,
    method="conformal",
    interval=[0.05, 0.95],
    n_boot=250,
    use_in_sample_residuals=True,
    use_binned_residuals=True,
    random_state=123,
    suppress_warnings=False,
    levels=None,
)

Predict n steps ahead and estimate prediction intervals using either bootstrapping or conformal prediction methods. Refer to the References section for additional details on these methods.

Parameters:

Name Type Description Default
steps (int, list, None)

Predict n steps. The value of steps must be less than or equal to the value of steps defined when initializing the forecaster. Starts at 1.

  • If int: Only steps within the range of 1 to int are predicted.
  • If list: List of ints. Only the steps contained in the list are predicted.
  • If None: As many steps are predicted as were defined at initialization.
None
last_window pandas DataFrame

Series values used to create the predictors (lags) needed to predict steps. If last_window = None, the values stored inself.last_window_ are used to calculate the initial predictors, and the predictions start right after training data.

None
exog pandas Series, pandas DataFrame

Exogenous variable/s included as predictor/s.

None
method str

Technique used to estimate prediction intervals. Available options:

  • 'bootstrapping': Bootstrapping is used to generate prediction intervals [1]_.
  • 'conformal': Employs the conformal prediction split method for interval estimation [2]_.
'conformal'
interval (float, list, tuple)

Confidence level of the prediction interval. Interpretation depends on the method used:

  • If float, represents the nominal (expected) coverage (between 0 and 1). For instance, interval=0.95 corresponds to [0.025, 0.975] quantiles.
  • If list or tuple, defines the exact quantiles to compute, which must be between 0 and 1 inclusive. For example, interval of 95% should be as interval = [0.025, 0.975].
  • When using method='conformal', the interval must be a float or a list/tuple defining a symmetric interval.

Changed in version 0.23.0: interval is now expressed as quantiles (0-1) instead of percentiles (0-100). Passing percentiles is not longer supported and will raise a ValueError.

[0.05, 0.95]
n_boot int

Number of bootstrapping iterations to perform when estimating prediction intervals.

250
use_in_sample_residuals bool

If True, residuals from the training data are used as proxy of prediction error to create predictions. If False, out of sample residuals (calibration) are used. Out-of-sample residuals must be precomputed using Forecaster's set_out_sample_residuals() method.

True
use_binned_residuals bool

If True, residuals are selected based on the predicted values (binned selection). If False, residuals are selected randomly.

True
random_state int

Seed for the random number generator to ensure reproducibility.

123
suppress_warnings bool

If True, skforecast warnings will be suppressed during the prediction process. See skforecast.exceptions.warn_skforecast_categories for more information.

False
levels Ignored

Not used, present here for API consistency by convention.

None

Returns:

Name Type Description
predictions pandas DataFrame

Long-format DataFrame with the predictions and the lower and upper bounds of the estimated interval. The columns are level, pred, lower_bound, upper_bound.

References

.. [1] Forecasting: Principles and Practice (3rd ed) Rob J Hyndman and George Athanasopoulos. https://otexts.com/fpp3/prediction-intervals.html

.. [2] MAPIE - Model Agnostic Prediction Interval Estimator. https://mapie.readthedocs.io/en/stable/content/conformal-prediction/regression/#2-the-split-method

Source code in skforecast/direct/_forecaster_direct_multivariate.py
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
@manage_warnings
def predict_interval(
    self,
    steps: int | list[int] | None = None,
    last_window: pd.DataFrame | None = None,
    exog: pd.Series | pd.DataFrame | None = None,
    method: str = 'conformal',
    interval: float | list[float] | tuple[float] = [0.05, 0.95],
    n_boot: int = 250,
    use_in_sample_residuals: bool = True,
    use_binned_residuals: bool = True,
    random_state: int = 123,
    suppress_warnings: bool = False,
    levels: Any = None
) -> pd.DataFrame:
    """
    Predict n steps ahead and estimate prediction intervals using either 
    bootstrapping or conformal prediction methods. Refer to the References 
    section for additional details on these methods.

    Parameters
    ----------
    steps : int, list, None, default None
        Predict n steps. The value of `steps` must be less than or equal to the 
        value of steps defined when initializing the forecaster. Starts at 1.

        - If `int`: Only steps within the range of 1 to int are predicted.
        - If `list`: List of ints. Only the steps contained in the list 
        are predicted.
        - If `None`: As many steps are predicted as were defined at 
        initialization.
    last_window : pandas DataFrame, default None
        Series values used to create the predictors (lags) needed to 
        predict `steps`.
        If `last_window = None`, the values stored in` self.last_window_` are
        used to calculate the initial predictors, and the predictions start
        right after training data.
    exog : pandas Series, pandas DataFrame, default None
        Exogenous variable/s included as predictor/s.
    method : str, default 'conformal'
        Technique used to estimate prediction intervals. Available options:

        - 'bootstrapping': Bootstrapping is used to generate prediction 
        intervals [1]_.
        - 'conformal': Employs the conformal prediction split method for 
        interval estimation [2]_.
    interval : float, list, tuple, default [0.05, 0.95]
        Confidence level of the prediction interval. Interpretation depends 
        on the method used:

        - If `float`, represents the nominal (expected) coverage (between 0 
        and 1). For instance, `interval=0.95` corresponds to `[0.025, 0.975]` 
        quantiles.
        - If `list` or `tuple`, defines the exact quantiles to compute, which 
        must be between 0 and 1 inclusive. For example, interval 
        of 95% should be as `interval = [0.025, 0.975]`.
        - When using `method='conformal'`, the interval must be a float or 
        a list/tuple defining a symmetric interval.

        **Changed in version 0.23.0:** `interval` is now expressed as
        quantiles (0-1) instead of percentiles (0-100). Passing percentiles
        is not longer supported and will raise a `ValueError`.
    n_boot : int, default 250
        Number of bootstrapping iterations to perform when estimating prediction
        intervals.
    use_in_sample_residuals : bool, default True
        If `True`, residuals from the training data are used as proxy of
        prediction error to create predictions. 
        If `False`, out of sample residuals (calibration) are used. 
        Out-of-sample residuals must be precomputed using Forecaster's
        `set_out_sample_residuals()` method.
    use_binned_residuals : bool, default True
        If `True`, residuals are selected based on the predicted values 
        (binned selection).
        If `False`, residuals are selected randomly.
    random_state : int, default 123
        Seed for the random number generator to ensure reproducibility.
    suppress_warnings : bool, default False
        If `True`, skforecast warnings will be suppressed during the prediction 
        process. See skforecast.exceptions.warn_skforecast_categories for more
        information.
    levels : Ignored
        Not used, present here for API consistency by convention.

    Returns
    -------
    predictions : pandas DataFrame
        Long-format DataFrame with the predictions and the lower and upper
        bounds of the estimated interval. The columns are `level`, `pred`,
        `lower_bound`, `upper_bound`.

    References
    ----------
    .. [1] Forecasting: Principles and Practice (3rd ed) Rob J Hyndman and George Athanasopoulos.
           https://otexts.com/fpp3/prediction-intervals.html

    .. [2] MAPIE - Model Agnostic Prediction Interval Estimator.
           https://mapie.readthedocs.io/en/stable/content/conformal-prediction/regression/#2-the-split-method

    """

    if method == "bootstrapping":

        if isinstance(interval, (list, tuple)):
            check_interval(interval=interval, ensure_symmetric_intervals=False)
            interval = np.array(interval)
        else:
            check_interval(alpha=interval, alpha_literal='interval')
            interval = np.array([0.5 - interval / 2, 0.5 + interval / 2])

        boot_predictions = self.predict_bootstrapping(
                               steps                   = steps,
                               last_window             = last_window,
                               exog                    = exog,
                               n_boot                  = n_boot,
                               random_state            = random_state,
                               use_in_sample_residuals = use_in_sample_residuals,
                               use_binned_residuals    = use_binned_residuals
                           )

        predictions = self.predict(
                          steps        = steps,
                          last_window  = last_window,
                          exog         = exog,
                          check_inputs = False
                      )

        boot_predictions[['lower_bound', 'upper_bound']] = (
            boot_predictions.iloc[:, 1:].quantile(q=interval, axis=1).transpose()
        )
        predictions = pd.concat([
            predictions, boot_predictions[['lower_bound', 'upper_bound']]
        ], axis=1)

    elif method == 'conformal':

        if isinstance(interval, (list, tuple)):
            check_interval(interval=interval, ensure_symmetric_intervals=True)
            nominal_coverage = interval[1] - interval[0]
        else:
            check_interval(alpha=interval, alpha_literal='interval')
            nominal_coverage = interval

        predictions = self._predict_interval_conformal(
                          steps                   = steps,
                          last_window             = last_window,
                          exog                    = exog,
                          nominal_coverage        = nominal_coverage,
                          use_in_sample_residuals = use_in_sample_residuals,
                          use_binned_residuals    = use_binned_residuals
                      )
    else:
        raise ValueError(
            f"Invalid `method` '{method}'. Choose 'bootstrapping' or 'conformal'."
        )

    return predictions

predict_quantiles ¶

predict_quantiles(
    steps=None,
    last_window=None,
    exog=None,
    quantiles=[0.05, 0.5, 0.95],
    n_boot=250,
    use_in_sample_residuals=True,
    use_binned_residuals=True,
    random_state=123,
    suppress_warnings=False,
    levels=None,
)

Calculate the specified quantiles for each step. After generating multiple forecasting predictions through a bootstrapping process, each quantile is calculated for each step.

Parameters:

Name Type Description Default
steps (int, list, None)

Predict n steps. The value of steps must be less than or equal to the value of steps defined when initializing the forecaster. Starts at 1.

  • If int: Only steps within the range of 1 to int are predicted.
  • If list: List of ints. Only the steps contained in the list are predicted.
  • If None: As many steps are predicted as were defined at initialization.
None
last_window pandas DataFrame

Series values used to create the predictors (lags) needed to predict steps. If last_window = None, the values stored inself.last_window_ are used to calculate the initial predictors, and the predictions start right after training data.

None
exog pandas Series, pandas DataFrame

Exogenous variable/s included as predictor/s.

None
quantiles (list, tuple)

Sequence of quantiles to compute, which must be between 0 and 1 inclusive. For example, quantiles of 0.05, 0.5 and 0.95 should be as quantiles = [0.05, 0.5, 0.95].

[0.05, 0.5, 0.95]
n_boot int

Number of bootstrapping iterations to perform when estimating quantiles.

250
use_in_sample_residuals bool

If True, residuals from the training data are used as proxy of prediction error to create predictions. If False, out of sample residuals (calibration) are used. Out-of-sample residuals must be precomputed using Forecaster's set_out_sample_residuals() method.

True
use_binned_residuals bool

If True, residuals are selected based on the predicted values (binned selection). If False, residuals are selected randomly.

True
random_state int

Seed for the random number generator to ensure reproducibility.

123
suppress_warnings bool

If True, skforecast warnings will be suppressed during the prediction process. See skforecast.exceptions.warn_skforecast_categories for more information.

False
levels Ignored

Not used, present here for API consistency by convention.

None

Returns:

Name Type Description
predictions pandas DataFrame

Long-format DataFrame with the quantiles predicted by the forecaster. For example, if quantiles = [0.05, 0.5, 0.95], the columns are level, q_0.05, q_0.5, q_0.95.

References

.. [1] Forecasting: Principles and Practice (3rd ed) Rob J Hyndman and George Athanasopoulos. https://otexts.com/fpp3/prediction-intervals.html

Source code in skforecast/direct/_forecaster_direct_multivariate.py
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
@manage_warnings
def predict_quantiles(
    self,
    steps: int | list[int] | None = None,
    last_window: pd.DataFrame | None = None,
    exog: pd.Series | pd.DataFrame | None = None,
    quantiles: list[float] | tuple[float] = [0.05, 0.5, 0.95],
    n_boot: int = 250,
    use_in_sample_residuals: bool = True,
    use_binned_residuals: bool = True,
    random_state: int = 123,
    suppress_warnings: bool = False,
    levels: Any = None
) -> pd.DataFrame:
    """
    Calculate the specified quantiles for each step. After generating 
    multiple forecasting predictions through a bootstrapping process, each 
    quantile is calculated for each step.

    Parameters
    ----------
    steps : int, list, None, default None
        Predict n steps. The value of `steps` must be less than or equal to the 
        value of steps defined when initializing the forecaster. Starts at 1.

        - If `int`: Only steps within the range of 1 to int are predicted.
        - If `list`: List of ints. Only the steps contained in the list 
        are predicted.
        - If `None`: As many steps are predicted as were defined at 
        initialization.
    last_window : pandas DataFrame, default None
        Series values used to create the predictors (lags) needed to 
        predict `steps`.
        If `last_window = None`, the values stored in` self.last_window_` are
        used to calculate the initial predictors, and the predictions start
        right after training data.
    exog : pandas Series, pandas DataFrame, default None
        Exogenous variable/s included as predictor/s.
    quantiles : list, tuple, default [0.05, 0.5, 0.95]
        Sequence of quantiles to compute, which must be between 0 and 1 
        inclusive. For example, quantiles of 0.05, 0.5 and 0.95 should be as 
        `quantiles = [0.05, 0.5, 0.95]`.
    n_boot : int, default 250
        Number of bootstrapping iterations to perform when estimating quantiles.
    use_in_sample_residuals : bool, default True
        If `True`, residuals from the training data are used as proxy of
        prediction error to create predictions. 
        If `False`, out of sample residuals (calibration) are used. 
        Out-of-sample residuals must be precomputed using Forecaster's
        `set_out_sample_residuals()` method.
    use_binned_residuals : bool, default True
        If `True`, residuals are selected based on the predicted values 
        (binned selection).
        If `False`, residuals are selected randomly.
    random_state : int, default 123
        Seed for the random number generator to ensure reproducibility.
    suppress_warnings : bool, default False
        If `True`, skforecast warnings will be suppressed during the prediction 
        process. See skforecast.exceptions.warn_skforecast_categories for more
        information.
    levels : Ignored
        Not used, present here for API consistency by convention.

    Returns
    -------
    predictions : pandas DataFrame
        Long-format DataFrame with the quantiles predicted by the forecaster.
        For example, if `quantiles = [0.05, 0.5, 0.95]`, the columns are
        `level`, `q_0.05`, `q_0.5`, `q_0.95`.

    References
    ----------
    .. [1] Forecasting: Principles and Practice (3rd ed) Rob J Hyndman and George Athanasopoulos.
           https://otexts.com/fpp3/prediction-intervals.html

    """

    check_interval(quantiles=quantiles)

    predictions = self.predict_bootstrapping(
                      steps                   = steps,
                      last_window             = last_window,
                      exog                    = exog,
                      n_boot                  = n_boot,
                      random_state            = random_state,
                      use_in_sample_residuals = use_in_sample_residuals,
                      use_binned_residuals    = use_binned_residuals
                  )

    quantiles_cols = [f'q_{q}' for q in quantiles]
    predictions[quantiles_cols] = (
        predictions.iloc[:, 1:].quantile(q=quantiles, axis=1).transpose()
    )
    predictions = predictions[['level'] + quantiles_cols]

    return predictions

predict_dist ¶

predict_dist(
    distribution,
    steps=None,
    last_window=None,
    exog=None,
    n_boot=250,
    use_in_sample_residuals=True,
    use_binned_residuals=True,
    random_state=123,
    suppress_warnings=False,
    levels=None,
)

Fit a given probability distribution for each step. After generating multiple forecasting predictions through a bootstrapping process, each step is fitted to the given distribution.

Parameters:

Name Type Description Default
distribution object

A distribution object from scipy.stats with methods _pdf and fit. For example scipy.stats.norm.

required
steps (int, list, None)

Predict n steps. The value of steps must be less than or equal to the value of steps defined when initializing the forecaster. Starts at 1.

  • If int: Only steps within the range of 1 to int are predicted.
  • If list: List of ints. Only the steps contained in the list are predicted.
  • If None: As many steps are predicted as were defined at initialization.
None
last_window pandas DataFrame

Series values used to create the predictors (lags) needed to predict steps. If last_window = None, the values stored inself.last_window_ are used to calculate the initial predictors, and the predictions start right after training data.

None
exog pandas Series, pandas DataFrame

Exogenous variable/s included as predictor/s.

None
n_boot int

Number of bootstrapping iterations to perform when estimating prediction intervals.

250
use_in_sample_residuals bool

If True, residuals from the training data are used as proxy of prediction error to create predictions. If False, out of sample residuals (calibration) are used. Out-of-sample residuals must be precomputed using Forecaster's set_out_sample_residuals() method.

True
use_binned_residuals bool

If True, residuals are selected based on the predicted values (binned selection). If False, residuals are selected randomly.

True
random_state int

Seed for the random number generator to ensure reproducibility.

123
suppress_warnings bool

If True, skforecast warnings will be suppressed during the prediction process. See skforecast.exceptions.warn_skforecast_categories for more information.

False
levels Ignored

Not used, present here for API consistency by convention.

None

Returns:

Name Type Description
predictions pandas DataFrame

Long-format DataFrame with the parameters of the fitted distribution for each step. The columns are level, param_0, param_1, ..., param_n, where param_i are the parameters of the distribution.

References

.. [1] Forecasting: Principles and Practice (3rd ed) Rob J Hyndman and George Athanasopoulos. https://otexts.com/fpp3/prediction-intervals.html

Source code in skforecast/direct/_forecaster_direct_multivariate.py
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
@manage_warnings
def predict_dist(
    self,
    distribution: object,
    steps: int | list[int] | None = None,
    last_window: pd.DataFrame | None = None,
    exog: pd.Series | pd.DataFrame | None = None,
    n_boot: int = 250,
    use_in_sample_residuals: bool = True,
    use_binned_residuals: bool = True,
    random_state: int = 123,
    suppress_warnings: bool = False,
    levels: Any = None
) -> pd.DataFrame:
    """
    Fit a given probability distribution for each step. After generating 
    multiple forecasting predictions through a bootstrapping process, each 
    step is fitted to the given distribution.

    Parameters
    ----------
    distribution : object
        A distribution object from scipy.stats with methods `_pdf` and `fit`. 
        For example scipy.stats.norm.
    steps : int, list, None, default None
        Predict n steps. The value of `steps` must be less than or equal to the 
        value of steps defined when initializing the forecaster. Starts at 1.

        - If `int`: Only steps within the range of 1 to int are predicted.
        - If `list`: List of ints. Only the steps contained in the list 
        are predicted.
        - If `None`: As many steps are predicted as were defined at 
        initialization.
    last_window : pandas DataFrame, default None
        Series values used to create the predictors (lags) needed to 
        predict `steps`.
        If `last_window = None`, the values stored in` self.last_window_` are
        used to calculate the initial predictors, and the predictions start
        right after training data.
    exog : pandas Series, pandas DataFrame, default None
        Exogenous variable/s included as predictor/s.
    n_boot : int, default 250
        Number of bootstrapping iterations to perform when estimating prediction
        intervals.
    use_in_sample_residuals : bool, default True
        If `True`, residuals from the training data are used as proxy of
        prediction error to create predictions. 
        If `False`, out of sample residuals (calibration) are used. 
        Out-of-sample residuals must be precomputed using Forecaster's
        `set_out_sample_residuals()` method.
    use_binned_residuals : bool, default True
        If `True`, residuals are selected based on the predicted values 
        (binned selection).
        If `False`, residuals are selected randomly.
    random_state : int, default 123
        Seed for the random number generator to ensure reproducibility.
    suppress_warnings : bool, default False
        If `True`, skforecast warnings will be suppressed during the prediction 
        process. See skforecast.exceptions.warn_skforecast_categories for more
        information.
    levels : Ignored
        Not used, present here for API consistency by convention.

    Returns
    -------
    predictions : pandas DataFrame
        Long-format DataFrame with the parameters of the fitted distribution
        for each step. The columns are `level`, `param_0`, `param_1`, ..., 
        `param_n`, where `param_i` are the parameters of the distribution.

    References
    ----------
    .. [1] Forecasting: Principles and Practice (3rd ed) Rob J Hyndman and George Athanasopoulos.
           https://otexts.com/fpp3/prediction-intervals.html

    """

    if not hasattr(distribution, "_pdf") or not callable(getattr(distribution, "fit", None)):
        raise TypeError(
            "`distribution` must be a valid probability distribution object "
            "from scipy.stats, with methods `_pdf` and `fit`."
        )

    predictions = self.predict_bootstrapping(
                      steps                   = steps,
                      last_window             = last_window,
                      exog                    = exog,
                      n_boot                  = n_boot,
                      random_state            = random_state,
                      use_in_sample_residuals = use_in_sample_residuals,
                      use_binned_residuals    = use_binned_residuals
                  )

    param_names = [
        p for p in inspect.signature(distribution._pdf).parameters if not p == "x"
    ] + ["loc", "scale"]

    predictions[param_names] = (
        predictions.iloc[:, 1:].apply(
            lambda x: distribution.fit(x), axis=1, result_type='expand'
        )
    )
    predictions = predictions[['level'] + param_names]

    return predictions

set_params ¶

set_params(params)

Set new values to the parameters of the scikit-learn model stored in the forecaster. It is important to note that all models share the same configuration of parameters and hyperparameters. After calling this method, the forecaster is reset to an unfitted state. The fit method must be called before prediction.

Parameters:

Name Type Description Default
params dict

Parameters values.

required

Returns:

Type Description
None
Source code in skforecast/direct/_forecaster_direct_multivariate.py
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
def set_params(
    self, 
    params: dict[str, object]
) -> None:
    """
    Set new values to the parameters of the scikit-learn model stored in the
    forecaster. It is important to note that all models share the same 
    configuration of parameters and hyperparameters. After calling this method, 
    the forecaster is reset to an unfitted state. The `fit` method must be 
    called before prediction.

    Parameters
    ----------
    params : dict
        Parameters values.

    Returns
    -------
    None

    """

    self.estimator = clone(self.estimator)
    self.estimator.set_params(**params)
    self.estimators_ = {
        step: clone(self.estimator)
        for step in self.steps
    }
    self.is_fitted = False

set_lags ¶

set_lags(lags=None)

Set new value to the attribute lags. Attributes lags_names, max_lag and window_size are also updated.

Parameters:

Name Type Description Default
lags int, list, numpy ndarray, range, dict

Lags used as predictors. Index starts at 1, so lag 1 is equal to t-1.

  • int: include lags from 1 to lags (included).
  • list, 1d numpy ndarray or range: include only lags present in lags, all elements must be int.
  • dict: create different lags for each series. {'series_column_name': lags}.
  • None: no lags are included as predictors.
None

Returns:

Type Description
None
Source code in skforecast/direct/_forecaster_direct_multivariate.py
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
def set_lags(
    self, 
    lags: int | list[int] | np.ndarray[int] | range[int] | dict[str, int | list] | None = None,
) -> None:
    """
    Set new value to the attribute `lags`. Attributes `lags_names`, 
    `max_lag` and `window_size` are also updated.

    Parameters
    ----------
    lags : int, list, numpy ndarray, range, dict, default None
        Lags used as predictors. Index starts at 1, so lag 1 is equal to t-1.

        - `int`: include lags from 1 to `lags` (included).
        - `list`, `1d numpy ndarray` or `range`: include only lags present in 
        `lags`, all elements must be int.
        - `dict`: create different lags for each series. {'series_column_name': lags}.
        - `None`: no lags are included as predictors. 

    Returns
    -------
    None

    """

    if self.window_features is None and lags is None:
        raise ValueError(
            "At least one of the arguments `lags` or `window_features` "
            "must be different from None. This is required to create the "
            "predictors used in training the forecaster."
        )

    if isinstance(lags, dict):
        self.lags = {}
        self.lags_names = {}
        list_max_lags = []
        for key in lags:
            if lags[key] is None:
                self.lags[key] = None
                self.lags_names[key] = None
            else:
                self.lags[key], lags_names, max_lag = initialize_lags(
                    forecaster_name = type(self).__name__,
                    lags            = lags[key]
                )
                self.lags_names[key] = (
                    [f'{key}_{lag}' for lag in lags_names] 
                     if lags_names is not None 
                     else None
                )
                if max_lag is not None:
                    list_max_lags.append(max_lag)

        self.max_lag = max(list_max_lags) if len(list_max_lags) != 0 else None
    else:
        self.lags, self.lags_names, self.max_lag = initialize_lags(
            forecaster_name = type(self).__name__, 
            lags            = lags
        )

    # Repeated here in case of lags is a dict with all values as None
    if self.window_features is None and (lags is None or self.max_lag is None):
        raise ValueError(
            "At least one of the arguments `lags` or `window_features` "
            "must be different from None. This is required to create the "
            "predictors used in training the forecaster."
        )

    self.window_size = max(
        [ws for ws in [self.max_lag, self.max_size_window_features] 
         if ws is not None]
    )
    if self.differentiation is not None:
        self.window_size += self.differentiation
        self.differentiator.set_params(window_size=self.window_size)

    self.filter_train_X_y_index_cache_ = {}
    self.filter_train_X_y_columns_cache_ = {}

set_window_features ¶

set_window_features(window_features=None)

Set new value to the attribute window_features. Attributes max_size_window_features, window_features_names, window_features_class_names and window_size are also updated.

Parameters:

Name Type Description Default
window_features (object, list)

Instance or list of instances used to create window features. Window features are created from the original time series and are included as predictors.

None

Returns:

Type Description
None
Source code in skforecast/direct/_forecaster_direct_multivariate.py
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
def set_window_features(
    self, 
    window_features: object | list[object] | None = None
) -> None:
    """
    Set new value to the attribute `window_features`. Attributes 
    `max_size_window_features`, `window_features_names`, 
    `window_features_class_names` and `window_size` are also updated.

    Parameters
    ----------
    window_features : object, list, default None
        Instance or list of instances used to create window features. Window features
        are created from the original time series and are included as predictors.

    Returns
    -------
    None

    """

    if window_features is None and self.max_lag is None:
        raise ValueError(
            "At least one of the arguments `lags` or `window_features` "
            "must be different from None. This is required to create the "
            "predictors used in training the forecaster."
        )

    self.window_features, self.window_features_names, self.max_size_window_features = (
        initialize_window_features(window_features)
    )
    self.window_features_class_names = None
    if window_features is not None:
        self.window_features_class_names = [
            type(wf).__name__ for wf in self.window_features
        ] 
    self.window_size = max(
        [ws for ws in [self.max_lag, self.max_size_window_features] 
         if ws is not None]
    )
    if self.differentiation is not None:
        self.window_size += self.differentiation
        self.differentiator.set_params(window_size=self.window_size)

    self.filter_train_X_y_index_cache_ = {}
    self.filter_train_X_y_columns_cache_ = {}

set_fit_kwargs ¶

set_fit_kwargs(fit_kwargs)

Set new values for the additional keyword arguments passed to the fit method of the estimator.

Parameters:

Name Type Description Default
fit_kwargs dict

Dict of the form {"argument": new_value}.

required

Returns:

Type Description
None
Source code in skforecast/direct/_forecaster_direct_multivariate.py
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
def set_fit_kwargs(
    self, 
    fit_kwargs: dict[str, object]
) -> None:
    """
    Set new values for the additional keyword arguments passed to the `fit` 
    method of the estimator.

    Parameters
    ----------
    fit_kwargs : dict
        Dict of the form {"argument": new_value}.

    Returns
    -------
    None

    """

    self.fit_kwargs = check_select_fit_kwargs(self.estimator, fit_kwargs=fit_kwargs)

set_in_sample_residuals ¶

set_in_sample_residuals(
    series,
    exog=None,
    random_state=123,
    suppress_warnings=False,
)

Set in-sample residuals in case they were not calculated during the training process.

In-sample residuals are calculated as the difference between the true values and the predictions made by the forecaster using the training data. The following internal attributes are updated:

  • in_sample_residuals_: Dictionary containing a numpy ndarray with the residuals for each series in the form {series: residuals}.
  • binner_intervals_: intervals used to bin the residuals are calculated using the quantiles of the predicted values.
  • in_sample_residuals_by_bin_: residuals are binned according to the predicted value they are associated with and stored in a dictionary, where the keys are the intervals of the predicted values and the values are the residuals associated with that range.

A total of 10_000 residuals are stored in the attribute in_sample_residuals_. If the number of residuals is greater than 10_000, a random sample of 10_000 residuals is stored. The number of residuals stored per bin is limited to 10_000 // self.binner.n_bins_.

Parameters:

Name Type Description Default
series pandas DataFrame

Training time series.

required
exog pandas Series, pandas DataFrame

Exogenous variable/s included as predictor/s. Must have the same number of observations as y and their indexes must be aligned so that y[i] is regressed on exog[i].

None
random_state int

Sets a seed to the random sampling for reproducible output.

123
suppress_warnings bool

If True, skforecast warnings will be suppressed during the sampling process. See skforecast.exceptions.warn_skforecast_categories for more information.

False

Returns:

Type Description
None
Source code in skforecast/direct/_forecaster_direct_multivariate.py
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
@manage_warnings
def set_in_sample_residuals(
    self,
    series: pd.DataFrame,
    exog: pd.Series | pd.DataFrame | None = None,
    random_state: int = 123,
    suppress_warnings: bool = False
) -> None:
    """
    Set in-sample residuals in case they were not calculated during the
    training process. 

    In-sample residuals are calculated as the difference between the true 
    values and the predictions made by the forecaster using the training 
    data. The following internal attributes are updated:

    + `in_sample_residuals_`: Dictionary containing a numpy ndarray with the
    residuals for each series in the form `{series: residuals}`.
    + `binner_intervals_`: intervals used to bin the residuals are calculated
    using the quantiles of the predicted values.
    + `in_sample_residuals_by_bin_`: residuals are binned according to the
    predicted value they are associated with and stored in a dictionary, where
    the keys are the intervals of the predicted values and the values are
    the residuals associated with that range. 

    A total of 10_000 residuals are stored in the attribute `in_sample_residuals_`.
    If the number of residuals is greater than 10_000, a random sample of
    10_000 residuals is stored. The number of residuals stored per bin is
    limited to `10_000 // self.binner.n_bins_`.

    Parameters
    ----------
    series : pandas DataFrame
        Training time series.
    exog : pandas Series, pandas DataFrame, default None
        Exogenous variable/s included as predictor/s. Must have the same
        number of observations as `y` and their indexes must be aligned so
        that y[i] is regressed on exog[i].
    random_state : int, default 123
        Sets a seed to the random sampling for reproducible output.
    suppress_warnings : bool, default False
        If `True`, skforecast warnings will be suppressed during the sampling 
        process. See skforecast.exceptions.warn_skforecast_categories for more
        information.

    Returns
    -------
    None

    """

    if not self.is_fitted:
        raise NotFittedError(
            "This forecaster is not fitted yet. Call `fit` with appropriate "
            "arguments before using `set_in_sample_residuals()`."
        )

    check_y(y=series[self.level], allow_nan=True, series_id='`series`')
    series_index_range = check_extract_values_and_index(
        data=series, data_label='`series`', return_values=False
    )[1][[0, -1]]
    if not series_index_range.equals(self.training_range_):
        raise IndexError(
            f"The index range of `series` does not match the range "
            f"used during training. Please ensure the index is aligned "
            f"with the training data.\n"
            f"    Expected : {self.training_range_}\n"
            f"    Received : {series_index_range}"
        )

    # NOTE: This attributes are modified in _create_train_X_y, store original values
    original_exog_in_ = self.exog_in_
    original_X_train_window_features_names_out_ = self.X_train_window_features_names_out_
    original_X_train_direct_exog_names_out_ = self.X_train_direct_exog_names_out_
    original_X_train_calendar_features_names_out_ = self.X_train_calendar_features_names_out_

    (
        X_train_autoreg,
        X_train_exog,
        X_train_calendar,
        y_train,
        _,
        _,
        _,
        _,
        _,
        _,
        _,
        X_train_direct_features_names_out_,
        _,
        _
    ) = self._create_train_X_y(series=series, exog=exog)

    if not X_train_direct_features_names_out_ == self.X_train_direct_features_names_out_:

        # NOTE: Reset attributes modified in _create_train_X_y to their original values
        self.exog_in_ = original_exog_in_
        self.X_train_window_features_names_out_ = original_X_train_window_features_names_out_
        self.X_train_direct_exog_names_out_ = original_X_train_direct_exog_names_out_
        self.X_train_calendar_features_names_out_ = original_X_train_calendar_features_names_out_

        raise ValueError(
            f"Feature mismatch detected after matrix creation. The features "
            f"generated from the provided data do not match those used during "
            f"the training process. To correctly set in-sample residuals, "
            f"ensure that the same data and preprocessing steps are applied.\n"
            f"    Expected output : {self.X_train_direct_features_names_out_}\n"
            f"    Current output  : {X_train_direct_features_names_out_}"
        )

    y_true_steps = []
    y_pred_steps = []
    self.in_sample_residuals_ = {}
    for step in self.steps:
        X_train_step, y_train_step = self._create_train_X_y_step(
                                         X_train_autoreg  = X_train_autoreg,
                                         X_train_exog     = X_train_exog,
                                         X_train_calendar = X_train_calendar,
                                         y_train          = y_train,
                                         step             = step,
                                     )
        X_train_step, y_train_step, _ = self._filter_nan_X_y_step(
                                            X_train_step = X_train_step,
                                            y_train_step = y_train_step,
                                        )

        with warnings.catch_warnings():
            warnings.filterwarnings(
                "ignore",
                message="X does not have valid feature names",
                category=UserWarning
            )
            y_pred = self.estimators_[step].predict(X_train_step)

        y_true_steps.append(y_train_step)
        y_pred_steps.append(y_pred)

    self._binning_in_sample_residuals(
        level                     = self.level,
        y_true                    = np.concatenate(y_true_steps),
        y_pred                    = np.concatenate(y_pred_steps),
        store_in_sample_residuals = True,
        random_state              = random_state
    )

    # NOTE: Reset attributes modified in _create_train_X_y to their original values
    self.exog_in_ = original_exog_in_
    self.X_train_window_features_names_out_ = original_X_train_window_features_names_out_
    self.X_train_direct_exog_names_out_ = original_X_train_direct_exog_names_out_
    self.X_train_calendar_features_names_out_ = original_X_train_calendar_features_names_out_

set_out_sample_residuals ¶

set_out_sample_residuals(
    y_true, y_pred, append=False, random_state=123
)

Set new values to the attribute out_sample_residuals_. Out of sample residuals are meant to be calculated using observations that did not participate in the training process. y_true and y_pred are expected to be in the original scale of the time series. Residuals are calculated as y_true - y_pred, after applying the necessary transformations and differentiations if the forecaster includes them (self.transformer_series and self.differentiation).

A total of 10_000 residuals are stored in the attribute out_sample_residuals_. If the number of residuals is greater than 10_000, a random sample of 10_000 residuals is stored.

Parameters:

Name Type Description Default
y_true dict

Dictionary of numpy ndarrays or pandas Series with the true values of the time series for each series in the form {series: y_true}.

required
y_pred dict

Dictionary of numpy ndarrays or pandas Series with the predicted values of the time series for each series in the form {series: y_pred}.

required
append bool

If True, new residuals are added to the once already stored in the attribute out_sample_residuals_. If after appending the new residuals, the limit of 10_000 samples is exceeded, a random sample of 10_000 is kept.

False
random_state int

Sets a seed to the random sampling for reproducible output.

123

Returns:

Type Description
None
Source code in skforecast/direct/_forecaster_direct_multivariate.py
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
def set_out_sample_residuals(
    self,
    y_true: dict[str, np.ndarray | pd.Series],
    y_pred: dict[str, np.ndarray | pd.Series],
    append: bool = False,
    random_state: int = 123
) -> None:
    """
    Set new values to the attribute `out_sample_residuals_`. Out of sample
    residuals are meant to be calculated using observations that did not
    participate in the training process. `y_true` and `y_pred` are expected
    to be in the original scale of the time series. Residuals are calculated
    as `y_true` - `y_pred`, after applying the necessary transformations and
    differentiations if the forecaster includes them (`self.transformer_series`
    and `self.differentiation`).

    A total of 10_000 residuals are stored in the attribute `out_sample_residuals_`.
    If the number of residuals is greater than 10_000, a random sample of
    10_000 residuals is stored.

    Parameters
    ----------
    y_true : dict
        Dictionary of numpy ndarrays or pandas Series with the true values of
        the time series for each series in the form {series: y_true}.
    y_pred : dict
        Dictionary of numpy ndarrays or pandas Series with the predicted values
        of the time series for each series in the form {series: y_pred}.
    append : bool, default False
        If `True`, new residuals are added to the once already stored in the
        attribute `out_sample_residuals_`. If after appending the new residuals,
        the limit of 10_000 samples is exceeded, a random sample of 10_000 is
        kept.
    random_state : int, default 123
        Sets a seed to the random sampling for reproducible output.

    Returns
    -------
    None

    """

    if not self.is_fitted:
        raise NotFittedError(
            "This forecaster is not fitted yet. Call `fit` with appropriate "
            "arguments before using `set_out_sample_residuals()`."
        )

    if not isinstance(y_true, dict):
        raise TypeError(
            f"`y_true` must be a dictionary of numpy ndarrays or pandas Series. "
            f"Got {type(y_true)}."
        )

    if not isinstance(y_pred, dict):
        raise TypeError(
            f"`y_pred` must be a dictionary of numpy ndarrays or pandas Series. "
            f"Got {type(y_pred)}."
        )

    if not set(y_true.keys()) == set(y_pred.keys()):
        raise ValueError(
            f"`y_true` and `y_pred` must have the same keys. "
            f"Got {set(y_true.keys())} and {set(y_pred.keys())}."
        )

    for k in y_true.keys():
        if not isinstance(y_true[k], (np.ndarray, pd.Series)):
            raise TypeError(
                f"Values of `y_true` must be numpy ndarrays or pandas Series. "
                f"Got {type(y_true[k])} for series {k}."
            )
        if not isinstance(y_pred[k], (np.ndarray, pd.Series)):
            raise TypeError(
                f"Values of `y_pred` must be numpy ndarrays or pandas Series. "
                f"Got {type(y_pred[k])} for series {k}."
            )
        if len(y_true[k]) != len(y_pred[k]):
            raise ValueError(
                f"`y_true` and `y_pred` must have the same length. "
                f"Got {len(y_true[k])} and {len(y_pred[k])} for series {k}."
            )
        if isinstance(y_true[k], pd.Series) and isinstance(y_pred[k], pd.Series):
            if not y_true[k].index.equals(y_pred[k].index):
                raise ValueError(
                    f"When containing pandas Series, elements in `y_true` and "
                    f"`y_pred` must have the same index. Error in series {k}."
                )

    if not set(y_pred.keys()) == {self.level}:
        raise ValueError(
            f"`y_pred` and `y_true` must have only the key '{self.level}'. " 
            f"Got {set(y_pred.keys())}."
        )

    y_true = y_true[self.level]
    y_pred = y_pred[self.level]
    if not isinstance(y_pred, np.ndarray):
        y_pred = y_pred.to_numpy()
    if not isinstance(y_true, np.ndarray):
        y_true = y_true.to_numpy()

    if self.transformer_series:
        y_true = transform_numpy(
                     array             = y_true,
                     transformer       = self.transformer_series_[self.level],
                     fit               = False,
                     inverse_transform = False
                 )
        y_pred = transform_numpy(
                     array             = y_pred,
                     transformer       = self.transformer_series_[self.level],
                     fit               = False,
                     inverse_transform = False
                 )

    if self.differentiation is not None:
        differentiator = copy(self.differentiator)
        differentiator.set_params(window_size=None)
        y_true = differentiator.fit_transform(y_true)[self.differentiation:]
        y_pred = differentiator.fit_transform(y_pred)[self.differentiation:]

    data = pd.DataFrame(
        {'prediction': y_pred, 'residuals': y_true - y_pred}
    ).dropna()
    y_pred = data['prediction'].to_numpy()
    residuals = data['residuals'].to_numpy()

    data['bin'] = self.binner[self.level].transform(y_pred).astype(int)
    residuals_by_bin = data.groupby('bin')['residuals'].apply(np.array).to_dict()

    if self.out_sample_residuals_ is None:
        self.out_sample_residuals_ = {self.level: None}
        self.out_sample_residuals_by_bin_ = {self.level: None}

    out_sample_residuals = (
        np.array([]) 
        if self.out_sample_residuals_[self.level] is None
        else self.out_sample_residuals_[self.level]
    )
    out_sample_residuals_by_bin = (
        {} 
        if self.out_sample_residuals_by_bin_[self.level] is None
        else self.out_sample_residuals_by_bin_[self.level]
    )
    if append:
        out_sample_residuals = np.concatenate([out_sample_residuals, residuals])
        for k, v in residuals_by_bin.items():
            if k in out_sample_residuals_by_bin:
                out_sample_residuals_by_bin[k] = np.concatenate(
                    (out_sample_residuals_by_bin[k], v)
                )
            else:
                out_sample_residuals_by_bin[k] = v
    else:
        out_sample_residuals = residuals
        out_sample_residuals_by_bin = residuals_by_bin

    max_samples = 10_000 // self.binner[self.level].n_bins_
    rng = np.random.default_rng(seed=random_state)
    for k, v in out_sample_residuals_by_bin.items():
        if len(v) > max_samples:
            sample = rng.choice(a=v, size=max_samples, replace=False)
            out_sample_residuals_by_bin[k] = sample

    for k in self.binner_intervals_.get(self.level, {}).keys():
        if k not in out_sample_residuals_by_bin:
            out_sample_residuals_by_bin[k] = np.array([])

    empty_bins = [
        k for k, v in out_sample_residuals_by_bin.items() 
        if v.size == 0
    ]
    if empty_bins:
        warnings.warn(
            f"The following bins of level '{self.level}' have no out of sample residuals: "
            f"{empty_bins}. No predicted values fall in the interval "
            f"{[self.binner_intervals_[self.level][bin] for bin in empty_bins]}. "
            f"Empty bins will be filled with a random sample of residuals.", 
            ResidualsUsageWarning
        )
        empty_bin_size = min(max_samples, len(out_sample_residuals))
        for k in empty_bins:
            out_sample_residuals_by_bin[k] = rng.choice(
                a       = out_sample_residuals,
                size    = empty_bin_size,
                replace = False
            )

    if len(out_sample_residuals) > 10_000:
        out_sample_residuals = rng.choice(
            a       = out_sample_residuals, 
            size    = 10_000, 
            replace = False
        )

    self.out_sample_residuals_[self.level] = out_sample_residuals
    self.out_sample_residuals_by_bin_[self.level] = out_sample_residuals_by_bin

get_feature_importances ¶

get_feature_importances(step, sort_importance=True)

Return feature importance of the model stored in the forecaster for a specific step. Since a separate model is created for each forecast time step, it is necessary to select the model from which retrieve information. Only valid when estimator stores internally the feature importances in the attribute feature_importances_ or coef_. Otherwise, it returns
None.

Parameters:

Name Type Description Default
step int

Model from which retrieve information (a separate model is created for each forecast time step). First step is 1.

required
sort_importance bool

If True, sorts the feature importances in descending order.

True

Returns:

Name Type Description
feature_importances pandas DataFrame

Feature importances associated with each predictor.

Source code in skforecast/direct/_forecaster_direct_multivariate.py
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
def get_feature_importances(
    self,
    step: int,
    sort_importance: bool = True
) -> pd.DataFrame:
    """
    Return feature importance of the model stored in the forecaster for a
    specific step. Since a separate model is created for each forecast time
    step, it is necessary to select the model from which retrieve information.
    Only valid when estimator stores internally the feature importances in
    the attribute `feature_importances_` or `coef_`. Otherwise, it returns  
    `None`.

    Parameters
    ----------
    step : int
        Model from which retrieve information (a separate model is created 
        for each forecast time step). First step is 1.
    sort_importance: bool, default True
        If `True`, sorts the feature importances in descending order.

    Returns
    -------
    feature_importances : pandas DataFrame
        Feature importances associated with each predictor.

    """

    if not isinstance(step, int):
        raise TypeError(
            f"`step` must be an integer. Got {type(step)}."
        )

    if not self.is_fitted:
        raise NotFittedError(
            "This forecaster is not fitted yet. Call `fit` with appropriate "
            "arguments before using `get_feature_importances()`."
        )

    if (step < 1) or (step > self.max_step):
        raise ValueError(
            f"The step must have a value from 1 to the maximum number of steps "
            f"({self.max_step}). Got {step}."
        )

    if isinstance(self.estimator, Pipeline):
        estimator = self.estimators_[step][-1]
    else:
        estimator = self.estimators_[step]

    if hasattr(estimator, 'feature_importances_'):
        feature_importances = estimator.feature_importances_
    elif hasattr(estimator, 'coef_'):
        feature_importances = estimator.coef_
    else:
        warnings.warn(
            f"Impossible to access feature importances for estimator of type "
            f"{type(estimator)}. This method is only valid when the "
            f"estimator stores internally the feature importances in the "
            f"attribute `feature_importances_` or `coef_`."
        )
        feature_importances = None

    if feature_importances is not None:
        feature_importances = pd.DataFrame({
                                  'feature': self.X_train_features_names_out_,
                                  'importance': feature_importances
                              })
        if sort_importance:
            feature_importances = feature_importances.sort_values(
                                      by='importance', ascending=False
                                  )

    return feature_importances