Skip to content

utils

skforecast.utils.utils.save_forecaster

save_forecaster(
    forecaster,
    file_name,
    save_custom_functions=True,
    verbose=True,
)

Save forecaster model using joblib. If custom functions are used to create weights, they are saved as .py files.

Parameters:

Name Type Description Default
forecaster Forecaster

Forecaster created with skforecast library.

required
file_name str

File name given to the object. The save extension will be .joblib.

required
save_custom_functions bool

If True, save custom functions used in the forecaster (weight_func) as .py files. Custom functions need to be available in the environment where the forecaster is going to be loaded.

True
verbose bool

Print summary about the forecaster saved.

True

Returns:

Type Description
None
Source code in skforecast\utils\utils.py
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
def save_forecaster(
    forecaster: object, 
    file_name: str,
    save_custom_functions: bool = True, 
    verbose: bool = True
) -> None:
    """
    Save forecaster model using joblib. If custom functions are used to create
    weights, they are saved as .py files.

    Parameters
    ----------
    forecaster : Forecaster
        Forecaster created with skforecast library.
    file_name : str
        File name given to the object. The save extension will be .joblib.
    save_custom_functions : bool, default True
        If True, save custom functions used in the forecaster (weight_func) as 
        .py files. Custom functions need to be available in the environment 
        where the forecaster is going to be loaded.
    verbose : bool, default True
        Print summary about the forecaster saved.

    Returns
    -------
    None

    """

    file_name = Path(file_name).with_suffix('.joblib')

    # Save forecaster
    joblib.dump(forecaster, filename=file_name)

    if save_custom_functions:
        # Save custom functions to create weights
        if hasattr(forecaster, 'weight_func') and forecaster.weight_func is not None:
            if isinstance(forecaster.weight_func, dict):
                for fun in set(forecaster.weight_func.values()):
                    file_name = fun.__name__ + '.py'
                    with open(file_name, 'w') as file:
                        file.write(inspect.getsource(fun))
            else:
                file_name = forecaster.weight_func.__name__ + '.py'
                with open(file_name, 'w') as file:
                    file.write(inspect.getsource(forecaster.weight_func))
    else:
        if hasattr(forecaster, 'weight_func') and forecaster.weight_func is not None:
            warnings.warn(
                "Custom function(s) used to create weights are not saved. To save them, "
                "set `save_custom_functions` to `True`.",
                SaveLoadSkforecastWarning
            )

    if hasattr(forecaster, 'window_features') and forecaster.window_features is not None:
        skforecast_classes = {'RollingFeatures'}
        custom_classes = set(forecaster.window_features_class_names) - skforecast_classes
        if custom_classes:
            warnings.warn(
                "The Forecaster includes custom user-defined classes in the "
                "`window_features` argument. These classes are not saved automatically "
                "when saving the Forecaster. Please ensure you save these classes "
                "manually and import them before loading the Forecaster.\n"
                "    Custom classes: " + ', '.join(custom_classes) + "\n"
                "Visit the documentation for more information: "
                "https://skforecast.org/latest/user_guides/save-load-forecaster.html#saving-and-loading-a-forecaster-model-with-custom-features",
                SaveLoadSkforecastWarning
            )

    if verbose:
        forecaster.summary()

skforecast.utils.utils.load_forecaster

load_forecaster(file_name, verbose=True)

Load forecaster model using joblib. If the forecaster was saved with custom user-defined classes as as window features or custom functions to create weights, these objects must be available in the environment where the forecaster is going to be loaded.

Parameters:

Name Type Description Default
file_name str

Object file name.

required
verbose bool

Print summary about the forecaster loaded.

True

Returns:

Name Type Description
forecaster Forecaster

Forecaster created with skforecast library.

Source code in skforecast\utils\utils.py
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
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
def load_forecaster(
    file_name: str,
    verbose: bool = True
) -> object:
    """
    Load forecaster model using joblib. If the forecaster was saved with 
    custom user-defined classes as as window features or custom
    functions to create weights, these objects must be available
    in the environment where the forecaster is going to be loaded.

    Parameters
    ----------
    file_name: str
        Object file name.
    verbose: bool, default `True`
        Print summary about the forecaster loaded.

    Returns
    -------
    forecaster: Forecaster
        Forecaster created with skforecast library.

    """

    forecaster = joblib.load(filename=Path(file_name))

    skforecast_v = skforecast.__version__
    forecaster_v = forecaster.skforecast_version

    if forecaster_v != skforecast_v:
        warnings.warn(
            f"The skforecast version installed in the environment differs "
            f"from the version used to create the forecaster.\n"
            f"    Installed Version  : {skforecast_v}\n"
            f"    Forecaster Version : {forecaster_v}\n"
            f"This may create incompatibilities when using the library.",
             SkforecastVersionWarning
        )

    if verbose:
        forecaster.summary()

    return forecaster

skforecast.utils.utils.initialize_lags

initialize_lags(forecaster_name, lags)

Check lags argument input and generate the corresponding numpy ndarray.

Parameters:

Name Type Description Default
forecaster_name str

Forecaster name.

required
lags Any

Lags used as predictors.

required

Returns:

Name Type Description
lags numpy ndarray, None

Lags used as predictors.

lags_names (list, None)

Names of the lags used as predictors.

max_lag (int, None)

Maximum value of the lags.

Source code in skforecast\utils\utils.py
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
def initialize_lags(
    forecaster_name: str,
    lags: Any
) -> Union[Optional[np.ndarray], Optional[list], Optional[int]]:
    """
    Check lags argument input and generate the corresponding numpy ndarray.

    Parameters
    ----------
    forecaster_name : str
        Forecaster name.
    lags : Any
        Lags used as predictors.

    Returns
    -------
    lags : numpy ndarray, None
        Lags used as predictors.
    lags_names : list, None
        Names of the lags used as predictors.
    max_lag : int, None
        Maximum value of the lags.

    """

    lags_names = None
    max_lag = None
    if lags is not None:
        if isinstance(lags, int):
            if lags < 1:
                raise ValueError("Minimum value of lags allowed is 1.")
            lags = np.arange(1, lags + 1)

        if isinstance(lags, (list, tuple, range)):
            lags = np.array(lags)

        if isinstance(lags, np.ndarray):
            if lags.size == 0:
                return None, None, None
            if lags.ndim != 1:
                raise ValueError("`lags` must be a 1-dimensional array.")
            if not np.issubdtype(lags.dtype, np.integer):
                raise TypeError("All values in `lags` must be integers.")
            if np.any(lags < 1):
                raise ValueError("Minimum value of lags allowed is 1.")
        else:
            if forecaster_name != 'ForecasterDirectMultiVariate':
                raise TypeError(
                    (f"`lags` argument must be an int, 1d numpy ndarray, range, "
                     f"tuple or list. Got {type(lags)}.")
                )
            else:
                raise TypeError(
                    (f"`lags` argument must be a dict, int, 1d numpy ndarray, range, "
                     f"tuple or list. Got {type(lags)}.")
                )

        lags_names = [f'lag_{i}' for i in lags]
        max_lag = max(lags)

    return lags, lags_names, max_lag

skforecast.utils.utils.initialize_weights

initialize_weights(
    forecaster_name, regressor, weight_func, series_weights
)

Check weights arguments, weight_func and series_weights for the different forecasters. Create source_code_weight_func, source code of the custom function(s) used to create weights.

Parameters:

Name Type Description Default
forecaster_name str

Forecaster name.

required
regressor regressor or pipeline compatible with the scikit-learn API

Regressor of the forecaster.

required
weight_func (Callable, dict)

Argument weight_func of the forecaster.

required
series_weights dict

Argument series_weights of the forecaster.

required

Returns:

Name Type Description
weight_func (Callable, dict)

Argument weight_func of the forecaster.

source_code_weight_func (str, dict)

Argument source_code_weight_func of the forecaster.

series_weights dict

Argument series_weights of the forecaster.

Source code in skforecast\utils\utils.py
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
def initialize_weights(
    forecaster_name: str,
    regressor: object,
    weight_func: Union[Callable, dict],
    series_weights: dict
) -> Tuple[Union[Callable, dict], Union[str, dict], dict]:
    """
    Check weights arguments, `weight_func` and `series_weights` for the different 
    forecasters. Create `source_code_weight_func`, source code of the custom 
    function(s) used to create weights.

    Parameters
    ----------
    forecaster_name : str
        Forecaster name.
    regressor : regressor or pipeline compatible with the scikit-learn API
        Regressor of the forecaster.
    weight_func : Callable, dict
        Argument `weight_func` of the forecaster.
    series_weights : dict
        Argument `series_weights` of the forecaster.

    Returns
    -------
    weight_func : Callable, dict
        Argument `weight_func` of the forecaster.
    source_code_weight_func : str, dict
        Argument `source_code_weight_func` of the forecaster.
    series_weights : dict
        Argument `series_weights` of the forecaster.

    """

    source_code_weight_func = None

    if weight_func is not None:

        if forecaster_name in ['ForecasterRecursiveMultiSeries']:
            if not isinstance(weight_func, (Callable, dict)):
                raise TypeError(
                    (f"Argument `weight_func` must be a Callable or a dict of "
                     f"Callables. Got {type(weight_func)}.")
                )
        elif not isinstance(weight_func, Callable):
            raise TypeError(
                f"Argument `weight_func` must be a Callable. Got {type(weight_func)}."
            )

        if isinstance(weight_func, dict):
            source_code_weight_func = {}
            for key in weight_func:
                source_code_weight_func[key] = inspect.getsource(weight_func[key])
        else:
            source_code_weight_func = inspect.getsource(weight_func)

        if 'sample_weight' not in inspect.signature(regressor.fit).parameters:
            warnings.warn(
                (f"Argument `weight_func` is ignored since regressor {regressor} "
                 f"does not accept `sample_weight` in its `fit` method."),
                 IgnoredArgumentWarning
            )
            weight_func = None
            source_code_weight_func = None

    if series_weights is not None:
        if not isinstance(series_weights, dict):
            raise TypeError(
                (f"Argument `series_weights` must be a dict of floats or ints."
                 f"Got {type(series_weights)}.")
            )
        if 'sample_weight' not in inspect.signature(regressor.fit).parameters:
            warnings.warn(
                (f"Argument `series_weights` is ignored since regressor {regressor} "
                 f"does not accept `sample_weight` in its `fit` method."),
                 IgnoredArgumentWarning
            )
            series_weights = None

    return weight_func, source_code_weight_func, series_weights

skforecast.utils.utils.initialize_transformer_series

initialize_transformer_series(
    forecaster_name,
    series_names_in_,
    encoding=None,
    transformer_series=None,
)

Initialize transformer_series_ attribute for the Forecasters Multiseries.

  • If transformer_series is None, no transformation is applied.
  • If transformer_series is a scikit-learn transformer (object), the same transformer is applied to all series (series_names_in_).
  • If transformer_series is a dict, a different transformer can be applied to each series. The keys of the dictionary must be the same as the names of the series in series_names_in_.

Parameters:

Name Type Description Default
forecaster_name str

Forecaster name.

required
series_names_in_ list

Names of the series (levels) used during training.

required
encoding str

Encoding used to identify the different series (ForecasterRecursiveMultiSeries).

`None`
transformer_series (object, dict)

An instance of a transformer (preprocessor) compatible with the scikit-learn preprocessing API with methods: fit, transform, fit_transform and inverse_transform.

`None`

Returns:

Name Type Description
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.

Source code in skforecast\utils\utils.py
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
def initialize_transformer_series(
    forecaster_name: str,
    series_names_in_: list,
    encoding: Optional[str] = None,
    transformer_series: Optional[Union[object, dict]] = None
) -> dict:
    """
    Initialize `transformer_series_` attribute for the Forecasters Multiseries.

    - If `transformer_series` is `None`, no transformation is applied.
    - If `transformer_series` is a scikit-learn transformer (object), the same 
    transformer is applied to all series (`series_names_in_`).
    - If `transformer_series` is a `dict`, a different transformer can be
    applied to each series. The keys of the dictionary must be the same as the
    names of the series in `series_names_in_`.

    Parameters
    ----------
    forecaster_name : str
        Forecaster name.
    series_names_in_ : list
        Names of the series (levels) used during training.
    encoding : str, default `None`
        Encoding used to identify the different series (`ForecasterRecursiveMultiSeries`).
    transformer_series : object, 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. 

    Returns
    -------
    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.

    """

    multiseries_forecasters = [
        'ForecasterRecursiveMultiSeries'
    ]

    if forecaster_name in multiseries_forecasters:
        if encoding is None:
            series_names_in_ = ['_unknown_level']
        else:
            series_names_in_ = series_names_in_ + ['_unknown_level']

    if transformer_series is None:
        transformer_series_ = {serie: None for serie in series_names_in_}
    elif not isinstance(transformer_series, dict):
        transformer_series_ = {serie: clone(transformer_series) 
                               for serie in series_names_in_}
    else:
        transformer_series_ = {serie: None for serie in series_names_in_}
        # Only elements already present in transformer_series_ are updated
        transformer_series_.update(
            (k, v) for k, v in deepcopy(transformer_series).items() 
            if k in transformer_series_
        )

        series_not_in_transformer_series = (
            set(series_names_in_) - set(transformer_series.keys())
        ) - {'_unknown_level'}
        if series_not_in_transformer_series:
            warnings.warn(
                (f"{series_not_in_transformer_series} not present in `transformer_series`."
                f" No transformation is applied to these series."),
                IgnoredArgumentWarning
            )

    return transformer_series_

skforecast.utils.utils.check_select_fit_kwargs

check_select_fit_kwargs(regressor, fit_kwargs=None)

Check if fit_kwargs is a dict and select only the keys that are used by the fit method of the regressor.

Parameters:

Name Type Description Default
regressor object

Regressor object.

required
fit_kwargs dict

Dictionary with the arguments to pass to the `fit' method of the forecaster.

`None`

Returns:

Name Type Description
fit_kwargs dict

Dictionary with the arguments to be passed to the fit method of the regressor after removing the unused keys.

Source code in skforecast\utils\utils.py
372
373
374
375
376
377
378
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
def check_select_fit_kwargs(
    regressor: object,
    fit_kwargs: Optional[dict] = None
) -> dict:
    """
    Check if `fit_kwargs` is a dict and select only the keys that are used by
    the `fit` method of the regressor.

    Parameters
    ----------
    regressor : object
        Regressor object.
    fit_kwargs : dict, default `None`
        Dictionary with the arguments to pass to the `fit' method of the forecaster.

    Returns
    -------
    fit_kwargs : dict
        Dictionary with the arguments to be passed to the `fit` method of the 
        regressor after removing the unused keys.

    """

    if fit_kwargs is None:
        fit_kwargs = {}
    else:
        if not isinstance(fit_kwargs, dict):
            raise TypeError(
                f"Argument `fit_kwargs` must be a dict. Got {type(fit_kwargs)}."
            )

        # Non used keys
        non_used_keys = [k for k in fit_kwargs.keys()
                         if k not in inspect.signature(regressor.fit).parameters]
        if non_used_keys:
            warnings.warn(
                (f"Argument/s {non_used_keys} ignored since they are not used by the "
                 f"regressor's `fit` method."),
                 IgnoredArgumentWarning
            )

        if 'sample_weight' in fit_kwargs.keys():
            warnings.warn(
                ("The `sample_weight` argument is ignored. Use `weight_func` to pass "
                 "a function that defines the individual weights for each sample "
                 "based on its index."),
                 IgnoredArgumentWarning
            )
            del fit_kwargs['sample_weight']

        # Select only the keyword arguments allowed by the regressor's `fit` method.
        fit_kwargs = {k: v for k, v in fit_kwargs.items()
                      if k in inspect.signature(regressor.fit).parameters}

    return fit_kwargs

skforecast.utils.utils.check_y

check_y(y, series_id='`y`')

Raise Exception if y is not pandas Series or if it has missing values.

Parameters:

Name Type Description Default
y Any

Time series values.

required
series_id str

Identifier of the series used in the warning message.

'`y`'

Returns:

Type Description
None
Source code in skforecast\utils\utils.py
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
def check_y(
    y: Any,
    series_id: str = "`y`"
) -> None:
    """
    Raise Exception if `y` is not pandas Series or if it has missing values.

    Parameters
    ----------
    y : Any
        Time series values.
    series_id : str, default '`y`'
        Identifier of the series used in the warning message.

    Returns
    -------
    None

    """

    if not isinstance(y, pd.Series):
        raise TypeError(f"{series_id} must be a pandas Series.")

    if y.isnull().any():
        raise ValueError(f"{series_id} has missing values.")

    return

skforecast.utils.utils.check_exog

check_exog(exog, allow_nan=True, series_id='`exog`')

Raise Exception if exog is not pandas Series or pandas DataFrame. If allow_nan = True, issue a warning if exog contains NaN values.

Parameters:

Name Type Description Default
exog pandas DataFrame, pandas Series

Exogenous variable/s included as predictor/s.

required
allow_nan bool

If True, allows the presence of NaN values in exog. If False (default), issue a warning if exog contains NaN values.

`True`
series_id str

Identifier of the series for which the exogenous variable/s are used in the warning message.

'`exog`'

Returns:

Type Description
None
Source code in skforecast\utils\utils.py
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
def check_exog(
    exog: Union[pd.Series, pd.DataFrame],
    allow_nan: bool = True,
    series_id: str = "`exog`"
) -> None:
    """
    Raise Exception if `exog` is not pandas Series or pandas DataFrame.
    If `allow_nan = True`, issue a warning if `exog` contains NaN values.

    Parameters
    ----------
    exog : pandas DataFrame, pandas Series
        Exogenous variable/s included as predictor/s.
    allow_nan : bool, default `True`
        If True, allows the presence of NaN values in `exog`. If False (default),
        issue a warning if `exog` contains NaN values.
    series_id : str, default '`exog`'
        Identifier of the series for which the exogenous variable/s are used
        in the warning message.

    Returns
    -------
    None

    """

    if not isinstance(exog, (pd.Series, pd.DataFrame)):
        raise TypeError(
            f"{series_id} must be a pandas Series or DataFrame. Got {type(exog)}."
        )

    if isinstance(exog, pd.Series) and exog.name is None:
        raise ValueError(f"When {series_id} is a pandas Series, it must have a name.")

    if not allow_nan:
        if exog.isnull().any().any():
            warnings.warn(
                (f"{series_id} has missing values. Most machine learning models "
                 f"do not allow missing values. Fitting the forecaster may fail."), 
                 MissingValuesWarning
            )

    return

skforecast.utils.utils.get_exog_dtypes

get_exog_dtypes(exog)

Store dtypes of exog.

Parameters:

Name Type Description Default
exog pandas DataFrame, pandas Series

Exogenous variable/s included as predictor/s.

required

Returns:

Name Type Description
exog_dtypes dict

Dictionary with the dtypes in exog.

Source code in skforecast\utils\utils.py
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
def get_exog_dtypes(
    exog: Union[pd.DataFrame, pd.Series]
) -> dict:
    """
    Store dtypes of `exog`.

    Parameters
    ----------
    exog : pandas DataFrame, pandas Series
        Exogenous variable/s included as predictor/s.

    Returns
    -------
    exog_dtypes : dict
        Dictionary with the dtypes in `exog`.

    """

    if isinstance(exog, pd.Series):
        exog_dtypes = {exog.name: exog.dtypes}
    else:
        exog_dtypes = exog.dtypes.to_dict()

    return exog_dtypes

skforecast.utils.utils.check_exog_dtypes

check_exog_dtypes(
    exog, call_check_exog=True, series_id="`exog`"
)

Raise Exception if exog has categorical columns with non integer values. This is needed when using machine learning regressors that allow categorical features. Issue a Warning if exog has columns that are not init, float, or category.

Parameters:

Name Type Description Default
exog pandas DataFrame, pandas Series

Exogenous variable/s included as predictor/s.

required
call_check_exog bool

If True, call check_exog function.

`True`
series_id str

Identifier of the series for which the exogenous variable/s are used in the warning message.

'`exog`'

Returns:

Type Description
None
Source code in skforecast\utils\utils.py
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
def check_exog_dtypes(
    exog: Union[pd.DataFrame, pd.Series],
    call_check_exog: bool = True,
    series_id: str = "`exog`"
) -> None:
    """
    Raise Exception if `exog` has categorical columns with non integer values.
    This is needed when using machine learning regressors that allow categorical
    features.
    Issue a Warning if `exog` has columns that are not `init`, `float`, or `category`.

    Parameters
    ----------
    exog : pandas DataFrame, pandas Series
        Exogenous variable/s included as predictor/s.
    call_check_exog : bool, default `True`
        If `True`, call `check_exog` function.
    series_id : str, default '`exog`'
        Identifier of the series for which the exogenous variable/s are used
        in the warning message.

    Returns
    -------
    None

    """

    if call_check_exog:
        check_exog(exog=exog, allow_nan=False, series_id=series_id)

    if isinstance(exog, pd.DataFrame):
        if not exog.select_dtypes(exclude=[np.number, 'category']).columns.empty:
            warnings.warn(
                (f"{series_id} may contain only `int`, `float` or `category` dtypes. "
                 f"Most machine learning models do not allow other types of values. "
                 f"Fitting the forecaster may fail."), 
                 DataTypeWarning
            )
        for col in exog.select_dtypes(include='category'):
            if exog[col].cat.categories.dtype not in [int, np.int32, np.int64]:
                raise TypeError(
                    ("Categorical dtypes in exog must contain only integer values. "
                     "See skforecast docs for more info about how to include "
                     "categorical features https://skforecast.org/"
                     "latest/user_guides/categorical-features.html")
                )
    else:
        if exog.dtype.name not in ['int', 'int8', 'int16', 'int32', 'int64', 'float', 
        'float16', 'float32', 'float64', 'uint8', 'uint16', 'uint32', 'uint64', 'category']:
            warnings.warn(
                (f"{series_id} may contain only `int`, `float` or `category` dtypes. Most "
                 f"machine learning models do not allow other types of values. "
                 f"Fitting the forecaster may fail."), 
                 DataTypeWarning
            )
        if exog.dtype.name == 'category' and exog.cat.categories.dtype not in [int,
        np.int32, np.int64]:
            raise TypeError(
                ("Categorical dtypes in exog must contain only integer values. "
                 "See skforecast docs for more info about how to include "
                 "categorical features https://skforecast.org/"
                 "latest/user_guides/categorical-features.html")
            )

    return

skforecast.utils.utils.check_interval

check_interval(interval=None, quantiles=None, alpha=None)

Check provided confidence interval sequence is valid.

Parameters:

Name Type Description Default
interval list

Confidence of the prediction interval estimated. Sequence of percentiles to compute, which must be between 0 and 100 inclusive. For example, interval of 95% should be as interval = [2.5, 97.5].

`None`
quantiles list

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].

`None`
alpha float

The confidence intervals used in ForecasterSarimax are (1 - alpha) %.

`None`

Returns:

Type Description
None
Source code in skforecast\utils\utils.py
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
def check_interval(
    interval: list = None,
    quantiles: float = None,
    alpha: float = None
) -> None:
    """
    Check provided confidence interval sequence is valid.

    Parameters
    ----------
    interval : list, default `None`
        Confidence of the prediction interval estimated. Sequence of percentiles
        to compute, which must be between 0 and 100 inclusive. For example, 
        interval of 95% should be as `interval = [2.5, 97.5]`.
    quantiles : list, default `None`
        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]`.
    alpha : float, default `None`
        The confidence intervals used in ForecasterSarimax are (1 - alpha) %.

    Returns
    -------
    None

    """

    if interval is not None:
        if not isinstance(interval, list):
            raise TypeError(
                ("`interval` must be a `list`. For example, interval of 95% "
                 "should be as `interval = [2.5, 97.5]`.")
            )

        if len(interval) != 2:
            raise ValueError(
                ("`interval` must contain exactly 2 values, respectively the "
                 "lower and upper interval bounds. For example, interval of 95% "
                 "should be as `interval = [2.5, 97.5]`.")
            )

        if (interval[0] < 0.) or (interval[0] >= 100.):
            raise ValueError(
                f"Lower interval bound ({interval[0]}) must be >= 0 and < 100."
            )

        if (interval[1] <= 0.) or (interval[1] > 100.):
            raise ValueError(
                f"Upper interval bound ({interval[1]}) must be > 0 and <= 100."
            )

        if interval[0] >= interval[1]:
            raise ValueError(
                (f"Lower interval bound ({interval[0]}) must be less than the "
                 f"upper interval bound ({interval[1]}).")
            )

    if quantiles is not None:
        if not isinstance(quantiles, list):
            raise TypeError(
                ("`quantiles` must be a `list`. For example, quantiles 0.05, "
                 "0.5, and 0.95 should be as `quantiles = [0.05, 0.5, 0.95]`.")
            )

        for q in quantiles:
            if (q < 0.) or (q > 1.):
                raise ValueError(
                    ("All elements in `quantiles` must be >= 0 and <= 1.")
                )

    if alpha is not None:
        if not isinstance(alpha, float):
            raise TypeError(
                ("`alpha` must be a `float`. For example, interval of 95% "
                 "should be as `alpha = 0.05`.")
            )

        if (alpha <= 0.) or (alpha >= 1):
            raise ValueError(
                f"`alpha` must have a value between 0 and 1. Got {alpha}."
            )

    return

skforecast.utils.utils.check_predict_input

check_predict_input(
    forecaster_name,
    steps,
    is_fitted,
    exog_in_,
    index_type_,
    index_freq_,
    window_size,
    last_window,
    last_window_exog=None,
    exog=None,
    exog_type_in_=None,
    exog_names_in_=None,
    interval=None,
    alpha=None,
    max_steps=None,
    levels=None,
    levels_forecaster=None,
    series_names_in_=None,
    encoding=None,
)

Check all inputs of predict method. This is a helper function to validate that inputs used in predict method match attributes of a forecaster already trained.

Parameters:

Name Type Description Default
forecaster_name str

Forecaster name.

required
steps (int, list)

Number of future steps predicted.

required
is_fitted bool

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

required
exog_in_ bool

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

required
index_type_ type

Type of index of the input used in training.

required
index_freq_ str

Frequency of Index of the input used in training.

required
window_size int

Size of the window needed to create the predictors. It is equal to max_lag.

required
last_window pandas Series, pandas DataFrame, None

Values of the series used to create the predictors (lags) need in the first iteration of prediction (t + 1).

required
last_window_exog pandas Series, pandas DataFrame

Values of the exogenous variables aligned with last_window in ForecasterSarimax predictions.

`None`
exog pandas Series, pandas DataFrame

Exogenous variable/s included as predictor/s.

`None`
exog_type_in_ type

Type of exogenous variable/s used in training.

`None`
exog_names_in_ list

Names of the exogenous variables used during training.

`None`
interval list

Confidence of the prediction interval estimated. Sequence of percentiles to compute, which must be between 0 and 100 inclusive. For example, interval of 95% should be as interval = [2.5, 97.5].

`None`
alpha float

The confidence intervals used in ForecasterSarimax are (1 - alpha) %.

`None`
max_steps Optional[int]

Maximum number of steps allowed (ForecasterDirect and ForecasterDirectMultiVariate).

None
levels (str, list)

Time series to be predicted (ForecasterRecursiveMultiSeries and `ForecasterRnn).

`None`
levels_forecaster (str, list)

Time series used as output data of a multiseries problem in a RNN problem (ForecasterRnn).

`None`
series_names_in_ list

Names of the columns used during fit (ForecasterRecursiveMultiSeries, ForecasterDirectMultiVariate and ForecasterRnn).

`None`
encoding str

Encoding used to identify the different series (ForecasterRecursiveMultiSeries).

`None`

Returns:

Type Description
None
Source code in skforecast\utils\utils.py
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
def check_predict_input(
    forecaster_name: str,
    steps: Union[int, list],
    is_fitted: bool,
    exog_in_: bool,
    index_type_: type,
    index_freq_: str,
    window_size: int,
    last_window: Union[pd.Series, pd.DataFrame, None],
    last_window_exog: Optional[Union[pd.Series, pd.DataFrame]] = None,
    exog: Optional[Union[pd.Series, pd.DataFrame]] = None,
    exog_type_in_: Optional[type] = None,
    exog_names_in_: Optional[list] = None,
    interval: Optional[list] = None,
    alpha: Optional[float] = None,
    max_steps: Optional[int] = None,
    levels: Optional[Union[str, list]] = None,
    levels_forecaster: Optional[Union[str, list]] = None,
    series_names_in_: Optional[list] = None,
    encoding: Optional[str] = None
) -> None:
    """
    Check all inputs of predict method. This is a helper function to validate
    that inputs used in predict method match attributes of a forecaster already
    trained.

    Parameters
    ----------
    forecaster_name : str
        Forecaster name.
    steps : int, list
        Number of future steps predicted.
    is_fitted: bool
        Tag to identify if the regressor has been fitted (trained).
    exog_in_ : bool
        If the forecaster has been trained using exogenous variable/s.
    index_type_ : type
        Type of index of the input used in training.
    index_freq_ : str
        Frequency of Index of the input used in training.
    window_size: int
        Size of the window needed to create the predictors. It is equal to 
        `max_lag`.
    last_window : pandas Series, pandas DataFrame, None
        Values of the series used to create the predictors (lags) need in the 
        first iteration of prediction (t + 1).
    last_window_exog : pandas Series, pandas DataFrame, default `None`
        Values of the exogenous variables aligned with `last_window` in 
        ForecasterSarimax predictions.
    exog : pandas Series, pandas DataFrame, default `None`
        Exogenous variable/s included as predictor/s.
    exog_type_in_ : type, default `None`
        Type of exogenous variable/s used in training.
    exog_names_in_ : list, default `None`
        Names of the exogenous variables used during training.
    interval : list, default `None`
        Confidence of the prediction interval estimated. Sequence of percentiles
        to compute, which must be between 0 and 100 inclusive. For example, 
        interval of 95% should be as `interval = [2.5, 97.5]`.
    alpha : float, default `None`
        The confidence intervals used in ForecasterSarimax are (1 - alpha) %.
    max_steps: int, default `None`
        Maximum number of steps allowed (`ForecasterDirect` and 
        `ForecasterDirectMultiVariate`).
    levels : str, list, default `None`
        Time series to be predicted (`ForecasterRecursiveMultiSeries`
        and `ForecasterRnn).
    levels_forecaster : str, list, default `None`
        Time series used as output data of a multiseries problem in a RNN problem
        (`ForecasterRnn`).
    series_names_in_ : list, default `None`
        Names of the columns used during fit (`ForecasterRecursiveMultiSeries`, 
        `ForecasterDirectMultiVariate` and `ForecasterRnn`).
    encoding : str, default `None`
        Encoding used to identify the different series (`ForecasterRecursiveMultiSeries`).

    Returns
    -------
    None

    """

    if not is_fitted:
        raise NotFittedError(
            ("This Forecaster instance is not fitted yet. Call `fit` with "
             "appropriate arguments before using predict.")
        )

    if isinstance(steps, (int, np.integer)) and steps < 1:
        raise ValueError(
            f"`steps` must be an integer greater than or equal to 1. Got {steps}."
        )

    if isinstance(steps, list) and min(steps) < 1:
        raise ValueError(
           (f"The minimum value of `steps` must be equal to or greater than 1. "
            f"Got {min(steps)}.")
        )

    if max_steps is not None:
        if max(steps) > max_steps:
            raise ValueError(
                (f"The maximum value of `steps` must be less than or equal to "
                 f"the value of steps defined when initializing the forecaster. "
                 f"Got {max(steps)}, but the maximum is {max_steps}.")
            )

    if interval is not None or alpha is not None:
        check_interval(interval=interval, alpha=alpha)

    if forecaster_name in ['ForecasterRecursiveMultiSeries', 
                           'ForecasterRnn']:
        if not isinstance(levels, (type(None), str, list)):
            raise TypeError(
                ("`levels` must be a `list` of column names, a `str` of a "
                 "column name or `None`.")
            )

        levels_to_check = (
            levels_forecaster if forecaster_name == 'ForecasterRnn'
            else series_names_in_
        )
        unknown_levels = set(levels) - set(levels_to_check)
        if forecaster_name == 'ForecasterRnn':
            if len(unknown_levels) != 0:
                raise ValueError(
                    (f"`levels` names must be included in the series used during fit "
                     f"({levels_to_check}). Got {levels}.")
                )
        else:
            if len(unknown_levels) != 0 and last_window is not None and encoding is not None:
                if encoding == 'onehot':
                    warnings.warn(
                        (f"`levels` {unknown_levels} were not included in training. The resulting "
                         f"one-hot encoded columns for this feature will be all zeros."),
                         UnknownLevelWarning
                    )
                else:
                    warnings.warn(
                        (f"`levels` {unknown_levels} were not included in training. "
                         f"Unknown levels are encoded as NaN, which may cause the "
                         f"prediction to fail if the regressor does not accept NaN values."),
                         UnknownLevelWarning
                    )

    if exog is None and exog_in_:
        raise ValueError(
            ("Forecaster trained with exogenous variable/s. "
             "Same variable/s must be provided when predicting.")
        )

    if exog is not None and not exog_in_:
        raise ValueError(
            ("Forecaster trained without exogenous variable/s. "
             "`exog` must be `None` when predicting.")
        )

    # Checks last_window
    # Check last_window type (pd.Series or pd.DataFrame according to forecaster)
    if isinstance(last_window, type(None)) and forecaster_name not in [
        'ForecasterRecursiveMultiSeries', 
        'ForecasterRnn'
    ]:
        raise ValueError(
            ("`last_window` was not stored during training. If you don't want "
             "to retrain the Forecaster, provide `last_window` as argument.")
        )

    if forecaster_name in ['ForecasterRecursiveMultiSeries', 
                           'ForecasterDirectMultiVariate',
                           'ForecasterRnn']:
        if not isinstance(last_window, pd.DataFrame):
            raise TypeError(
                f"`last_window` must be a pandas DataFrame. Got {type(last_window)}."
            )

        last_window_cols = last_window.columns.to_list()

        if forecaster_name in ['ForecasterRecursiveMultiSeries', 
                               'ForecasterRnn'] and \
            len(set(levels) - set(last_window_cols)) != 0:
            raise ValueError(
                (f"`last_window` must contain a column(s) named as the level(s) "
                 f"to be predicted.\n"
                 f"    `levels` : {levels}\n"
                 f"    `last_window` columns : {last_window_cols}")
            )

        if forecaster_name == 'ForecasterDirectMultiVariate':
            if len(set(series_names_in_) - set(last_window_cols)) > 0:
                raise ValueError(
                    (f"`last_window` columns must be the same as the `series` "
                     f"column names used to create the X_train matrix.\n"
                     f"    `last_window` columns    : {last_window_cols}\n"
                     f"    `series` columns X train : {series_names_in_}")
                )
    else:
        if not isinstance(last_window, (pd.Series, pd.DataFrame)):
            raise TypeError(
                f"`last_window` must be a pandas Series or DataFrame. "
                f"Got {type(last_window)}."
            )

    # Check last_window len, nulls and index (type and freq)
    if len(last_window) < window_size:
        raise ValueError(
            (f"`last_window` must have as many values as needed to "
             f"generate the predictors. For this forecaster it is {window_size}.")
        )
    if last_window.isnull().any().all():
        warnings.warn(
            ("`last_window` has missing values. Most of machine learning models do "
             "not allow missing values. Prediction method may fail."), 
             MissingValuesWarning
        )
    _, last_window_index = preprocess_last_window(
                               last_window   = last_window.iloc[:0],
                               return_values = False
                           ) 
    if not isinstance(last_window_index, index_type_):
        raise TypeError(
            (f"Expected index of type {index_type_} for `last_window`. "
             f"Got {type(last_window_index)}.")
        )
    if isinstance(last_window_index, pd.DatetimeIndex):
        if not last_window_index.freqstr == index_freq_:
            raise TypeError(
                (f"Expected frequency of type {index_freq_} for `last_window`. "
                 f"Got {last_window_index.freqstr}.")
            )

    # Checks exog
    if exog is not None:

        # Check type, nulls and expected type
        if forecaster_name in ['ForecasterRecursiveMultiSeries']:
            if not isinstance(exog, (pd.Series, pd.DataFrame, dict)):
                raise TypeError(
                    f"`exog` must be a pandas Series, DataFrame or dict. Got {type(exog)}."
                )
            if exog_type_in_ == dict and not isinstance(exog, dict):
                raise TypeError(
                    f"Expected type for `exog`: {exog_type_in_}. Got {type(exog)}."
                )
        else:
            if not isinstance(exog, (pd.Series, pd.DataFrame)):
                raise TypeError(
                    f"`exog` must be a pandas Series or DataFrame. Got {type(exog)}."
                )

        if isinstance(exog, dict):
            no_exog_levels = set(levels) - set(exog.keys())
            if no_exog_levels:
                warnings.warn(
                    (f"`exog` does not contain keys for levels {no_exog_levels}. "
                     f"Missing levels are filled with NaN. Most of machine learning "
                     f"models do not allow missing values. Prediction method may fail."),
                     MissingExogWarning
                )
            exogs_to_check = [
                (f"`exog` for series '{k}'", v) 
                for k, v in exog.items() 
                if v is not None and k in levels
            ]
        else:
            exogs_to_check = [('`exog`', exog)]

        for exog_name, exog_to_check in exogs_to_check:

            if not isinstance(exog_to_check, (pd.Series, pd.DataFrame)):
                raise TypeError(
                    f"{exog_name} must be a pandas Series or DataFrame. Got {type(exog_to_check)}"
                )

            if exog_to_check.isnull().any().any():
                warnings.warn(
                    (f"{exog_name} has missing values. Most of machine learning models "
                     f"do not allow missing values. Prediction method may fail."), 
                     MissingValuesWarning
                )

            # Check exog has many values as distance to max step predicted
            last_step = max(steps) if isinstance(steps, list) else steps
            if len(exog_to_check) < last_step:
                if forecaster_name in ['ForecasterRecursiveMultiSeries']:
                    warnings.warn(
                        (f"{exog_name} doesn't have as many values as steps "
                         f"predicted, {last_step}. Missing values are filled "
                         f"with NaN. Most of machine learning models do not "
                         f"allow missing values. Prediction method may fail."),
                         MissingValuesWarning
                    )
                else: 
                    raise ValueError(
                        (f"{exog_name} must have at least as many values as "
                         f"steps predicted, {last_step}.")
                    )

            # Check name/columns are in exog_names_in_
            if isinstance(exog_to_check, pd.DataFrame):
                col_missing = set(exog_names_in_).difference(set(exog_to_check.columns))
                if col_missing:
                    if forecaster_name in ['ForecasterRecursiveMultiSeries']:
                        warnings.warn(
                            (f"{col_missing} not present in {exog_name}. All "
                             f"values will be NaN."),
                             MissingExogWarning
                        ) 
                    else:
                        raise ValueError(
                            (f"Missing columns in {exog_name}. Expected {exog_names_in_}. "
                             f"Got {exog_to_check.columns.to_list()}.")
                        )
            else:
                if exog_to_check.name is None:
                    raise ValueError(
                        (f"When {exog_name} is a pandas Series, it must have a name. Got None.")
                    )

                if exog_to_check.name not in exog_names_in_:
                    if forecaster_name in ['ForecasterRecursiveMultiSeries']:
                        warnings.warn(
                            (f"'{exog_to_check.name}' was not observed during training. "
                             f"{exog_name} is ignored. Exogenous variables must be one "
                             f"of: {exog_names_in_}."),
                             IgnoredArgumentWarning
                        )
                    else:
                        raise ValueError(
                            (f"'{exog_to_check.name}' was not observed during training. "
                             f"Exogenous variables must be: {exog_names_in_}.")
                        )

            # Check index dtype and freq
            _, exog_index = preprocess_exog(
                                exog          = exog_to_check.iloc[:0, ],
                                return_values = False
                            )
            if not isinstance(exog_index, index_type_):
                raise TypeError(
                    (f"Expected index of type {index_type_} for {exog_name}. "
                     f"Got {type(exog_index)}.")
                )
            if forecaster_name not in ['ForecasterRecursiveMultiSeries']:
                if isinstance(exog_index, pd.DatetimeIndex):
                    if not exog_index.freqstr == index_freq_:
                        raise TypeError(
                            (f"Expected frequency of type {index_freq_} for {exog_name}. "
                             f"Got {exog_index.freqstr}.")
                        )

            # Check exog starts one step ahead of last_window end.
            expected_index = expand_index(last_window.index, 1)[0]
            if expected_index != exog_to_check.index[0]:
                if forecaster_name in ['ForecasterRecursiveMultiSeries']:
                    warnings.warn(
                        (f"To make predictions {exog_name} must start one step "
                         f"ahead of `last_window`. Missing values are filled "
                         f"with NaN.\n"
                         f"    `last_window` ends at : {last_window.index[-1]}.\n"
                         f"    {exog_name} starts at : {exog_to_check.index[0]}.\n"
                         f"     Expected index       : {expected_index}."),
                         MissingValuesWarning
                    )  
                else:
                    raise ValueError(
                        (f"To make predictions {exog_name} must start one step "
                         f"ahead of `last_window`.\n"
                         f"    `last_window` ends at : {last_window.index[-1]}.\n"
                         f"    {exog_name} starts at : {exog_to_check.index[0]}.\n"
                         f"     Expected index : {expected_index}.")
                    )

    # Checks ForecasterSarimax
    if forecaster_name == 'ForecasterSarimax':
        # Check last_window_exog type, len, nulls and index (type and freq)
        if last_window_exog is not None:
            if not exog_in_:
                raise ValueError(
                    ("Forecaster trained without exogenous variable/s. "
                     "`last_window_exog` must be `None` when predicting.")
                )

            if not isinstance(last_window_exog, (pd.Series, pd.DataFrame)):
                raise TypeError(
                    (f"`last_window_exog` must be a pandas Series or a "
                     f"pandas DataFrame. Got {type(last_window_exog)}.")
                )
            if len(last_window_exog) < window_size:
                raise ValueError(
                    (f"`last_window_exog` must have as many values as needed to "
                     f"generate the predictors. For this forecaster it is {window_size}.")
                )
            if last_window_exog.isnull().any().all():
                warnings.warn(
                    ("`last_window_exog` has missing values. Most of machine learning "
                     "models do not allow missing values. Prediction method may fail."),
                     MissingValuesWarning
            )
            _, last_window_exog_index = preprocess_last_window(
                                            last_window   = last_window_exog.iloc[:0],
                                            return_values = False
                                        ) 
            if not isinstance(last_window_exog_index, index_type_):
                raise TypeError(
                    (f"Expected index of type {index_type_} for `last_window_exog`. "
                     f"Got {type(last_window_exog_index)}.")
                )
            if isinstance(last_window_exog_index, pd.DatetimeIndex):
                if not last_window_exog_index.freqstr == index_freq_:
                    raise TypeError(
                        (f"Expected frequency of type {index_freq_} for "
                         f"`last_window_exog`. Got {last_window_exog_index.freqstr}.")
                    )

            # Check all columns are in the pd.DataFrame, last_window_exog
            if isinstance(last_window_exog, pd.DataFrame):
                col_missing = set(exog_names_in_).difference(set(last_window_exog.columns))
                if col_missing:
                    raise ValueError(
                        (f"Missing columns in `last_window_exog`. Expected {exog_names_in_}. "
                         f"Got {last_window_exog.columns.to_list()}.") 
                    )
            else:
                if last_window_exog.name is None:
                    raise ValueError(
                        ("When `last_window_exog` is a pandas Series, it must have a "
                         "name. Got None.")
                    )

                if last_window_exog.name not in exog_names_in_:
                    raise ValueError(
                        (f"'{last_window_exog.name}' was not observed during training. "
                         f"Exogenous variables must be: {exog_names_in_}.")
                    )

    return

skforecast.utils.utils.preprocess_y

preprocess_y(y, return_values=True)

Return values and index of series separately. Index is overwritten according to the next rules:

  • If index is of type DatetimeIndex and has frequency, nothing is changed.
  • If index is of type RangeIndex, nothing is changed.
  • If index is of type DatetimeIndex but has no frequency, a RangeIndex is created.
  • If index is not of type DatetimeIndex, a RangeIndex is created.

Parameters:

Name Type Description Default
y pandas Series, pandas DataFrame

Time series.

required
return_values bool

If True return the values of y as numpy ndarray. This option is intended to avoid copying data when it is not necessary.

`True`

Returns:

Name Type Description
y_values None, numpy ndarray

Numpy array with values of y.

y_index pandas Index

Index of y modified according to the rules.

Source code in skforecast\utils\utils.py
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
def preprocess_y(
    y: Union[pd.Series, pd.DataFrame],
    return_values: bool = True
) -> Tuple[Union[None, np.ndarray], pd.Index]:
    """
    Return values and index of series separately. Index is overwritten 
    according to the next rules:

    - If index is of type `DatetimeIndex` and has frequency, nothing is 
    changed.
    - If index is of type `RangeIndex`, nothing is changed.
    - If index is of type `DatetimeIndex` but has no frequency, a 
    `RangeIndex` is created.
    - If index is not of type `DatetimeIndex`, a `RangeIndex` is created.

    Parameters
    ----------
    y : pandas Series, pandas DataFrame
        Time series.
    return_values : bool, default `True`
        If `True` return the values of `y` as numpy ndarray. This option is 
        intended to avoid copying data when it is not necessary.

    Returns
    -------
    y_values : None, numpy ndarray
        Numpy array with values of `y`.
    y_index : pandas Index
        Index of `y` modified according to the rules.

    """

    if isinstance(y.index, pd.DatetimeIndex) and y.index.freq is not None:
        y_index = y.index
    elif isinstance(y.index, pd.RangeIndex):
        y_index = y.index
    elif isinstance(y.index, pd.DatetimeIndex) and y.index.freq is None:
        warnings.warn(
            ("Series has DatetimeIndex index but no frequency. "
             "Index is overwritten with a RangeIndex of step 1.")
        )
        y_index = pd.RangeIndex(
                      start = 0,
                      stop  = len(y),
                      step  = 1
                  )
    else:
        warnings.warn(
            ("Series has no DatetimeIndex nor RangeIndex index. "
             "Index is overwritten with a RangeIndex.")
        )
        y_index = pd.RangeIndex(
                      start = 0,
                      stop  = len(y),
                      step  = 1
                  )

    y_values = y.to_numpy(copy=True).ravel() if return_values else None

    return y_values, y_index

skforecast.utils.utils.preprocess_last_window

preprocess_last_window(last_window, return_values=True)

Return values and index of series separately. Index is overwritten according to the next rules:

  • If index is of type DatetimeIndex and has frequency, nothing is changed.
  • If index is of type RangeIndex, nothing is changed.
  • If index is of type DatetimeIndex but has no frequency, a RangeIndex is created.
  • If index is not of type DatetimeIndex, a RangeIndex is created.

Parameters:

Name Type Description Default
last_window pandas Series, pandas DataFrame

Time series values.

required
return_values bool

If True return the values of last_window as numpy ndarray. This option is intended to avoid copying data when it is not necessary.

`True`

Returns:

Name Type Description
last_window_values numpy ndarray

Numpy array with values of last_window.

last_window_index pandas Index

Index of last_window modified according to the rules.

Source code in skforecast\utils\utils.py
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
def preprocess_last_window(
    last_window: Union[pd.Series, pd.DataFrame],
    return_values: bool = True
 ) -> Tuple[np.ndarray, pd.Index]:
    """
    Return values and index of series separately. Index is overwritten 
    according to the next rules:

    - If index is of type `DatetimeIndex` and has frequency, nothing is 
    changed.
    - If index is of type `RangeIndex`, nothing is changed.
    - If index is of type `DatetimeIndex` but has no frequency, a 
    `RangeIndex` is created.
    - If index is not of type `DatetimeIndex`, a `RangeIndex` is created.

    Parameters
    ----------
    last_window : pandas Series, pandas DataFrame
        Time series values.
    return_values : bool, default `True`
        If `True` return the values of `last_window` as numpy ndarray. This option 
        is intended to avoid copying data when it is not necessary.

    Returns
    -------
    last_window_values : numpy ndarray
        Numpy array with values of `last_window`.
    last_window_index : pandas Index
        Index of `last_window` modified according to the rules.

    """

    if isinstance(last_window.index, pd.DatetimeIndex) and last_window.index.freq is not None:
        last_window_index = last_window.index
    elif isinstance(last_window.index, pd.RangeIndex):
        last_window_index = last_window.index
    elif isinstance(last_window.index, pd.DatetimeIndex) and last_window.index.freq is None:
        warnings.warn(
            ("`last_window` has DatetimeIndex index but no frequency. "
             "Index is overwritten with a RangeIndex of step 1.")
        )
        last_window_index = pd.RangeIndex(
                                start = 0,
                                stop  = len(last_window),
                                step  = 1
                            )
    else:
        warnings.warn(
            ("`last_window` has no DatetimeIndex nor RangeIndex index. "
             "Index is overwritten with a RangeIndex.")
        )
        last_window_index = pd.RangeIndex(
                                start = 0,
                                stop  = len(last_window),
                                step  = 1
                            )

    last_window_values = last_window.to_numpy(copy=True).ravel() if return_values else None

    return last_window_values, last_window_index

skforecast.utils.utils.preprocess_exog

preprocess_exog(exog, return_values=True)

Return values and index of series or data frame separately. Index is overwritten according to the next rules:

  • If index is of type DatetimeIndex and has frequency, nothing is changed.
  • If index is of type RangeIndex, nothing is changed.
  • If index is of type DatetimeIndex but has no frequency, a RangeIndex is created.
  • If index is not of type DatetimeIndex, a RangeIndex is created.

Parameters:

Name Type Description Default
exog pandas Series, pandas DataFrame

Exogenous variables.

required
return_values bool

If True return the values of exog as numpy ndarray. This option is intended to avoid copying data when it is not necessary.

`True`

Returns:

Name Type Description
exog_values None, numpy ndarray

Numpy array with values of exog.

exog_index pandas Index

Index of exog modified according to the rules.

Source code in skforecast\utils\utils.py
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
def preprocess_exog(
    exog: Union[pd.Series, pd.DataFrame],
    return_values: bool = True
) -> Tuple[Union[None, np.ndarray], pd.Index]:
    """
    Return values and index of series or data frame separately. Index is
    overwritten  according to the next rules:

    - If index is of type `DatetimeIndex` and has frequency, nothing is 
    changed.
    - If index is of type `RangeIndex`, nothing is changed.
    - If index is of type `DatetimeIndex` but has no frequency, a 
    `RangeIndex` is created.
    - If index is not of type `DatetimeIndex`, a `RangeIndex` is created.

    Parameters
    ----------
    exog : pandas Series, pandas DataFrame
        Exogenous variables.
    return_values : bool, default `True`
        If `True` return the values of `exog` as numpy ndarray. This option is 
        intended to avoid copying data when it is not necessary.

    Returns
    -------
    exog_values : None, numpy ndarray
        Numpy array with values of `exog`.
    exog_index : pandas Index
        Index of `exog` modified according to the rules.

    """

    if isinstance(exog.index, pd.DatetimeIndex) and exog.index.freq is not None:
        exog_index = exog.index
    elif isinstance(exog.index, pd.RangeIndex):
        exog_index = exog.index
    elif isinstance(exog.index, pd.DatetimeIndex) and exog.index.freq is None:
        warnings.warn(
            ("`exog` has DatetimeIndex index but no frequency. "
             "Index is overwritten with a RangeIndex of step 1.")
        )
        exog_index = pd.RangeIndex(
                         start = 0,
                         stop  = len(exog),
                         step  = 1
                     )

    else:
        warnings.warn(
            ("`exog` has no DatetimeIndex nor RangeIndex index. "
             "Index is overwritten with a RangeIndex.")
        )
        exog_index = pd.RangeIndex(
                         start = 0,
                         stop  = len(exog),
                         step  = 1
                     )

    exog_values = exog.to_numpy(copy=True) if return_values else None

    return exog_values, exog_index

skforecast.utils.utils.cast_exog_dtypes

cast_exog_dtypes(exog, exog_dtypes)

Cast exog to a specified types. This is done because, for a forecaster to accept a categorical exog, it must contain only integer values. Due to the internal modifications of numpy, the values may be casted to float, so they have to be re-converted to int.

  • If exog is a pandas Series, exog_dtypes must be a dict with a single value.
  • If exog_dtypes is category but the current type of exog is float, then the type is cast to int and then to category.

Parameters:

Name Type Description Default
exog pandas Series, pandas DataFrame

Exogenous variables.

required
exog_dtypes dict

Dictionary with name and type of the series or data frame columns.

required

Returns:

Name Type Description
exog pandas Series, pandas DataFrame

Exogenous variables casted to the indicated dtypes.

Source code in skforecast\utils\utils.py
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
def cast_exog_dtypes(
    exog: Union[pd.Series, pd.DataFrame],
    exog_dtypes: dict,
) -> Union[pd.Series, pd.DataFrame]:  # pragma: no cover
    """
    Cast `exog` to a specified types. This is done because, for a forecaster to 
    accept a categorical exog, it must contain only integer values. Due to the 
    internal modifications of numpy, the values may be casted to `float`, so 
    they have to be re-converted to `int`.

    - If `exog` is a pandas Series, `exog_dtypes` must be a dict with a 
    single value.
    - If `exog_dtypes` is `category` but the current type of `exog` is `float`, 
    then the type is cast to `int` and then to `category`. 

    Parameters
    ----------
    exog : pandas Series, pandas DataFrame
        Exogenous variables.
    exog_dtypes: dict
        Dictionary with name and type of the series or data frame columns.

    Returns
    -------
    exog : pandas Series, pandas DataFrame
        Exogenous variables casted to the indicated dtypes.

    """

    # Remove keys from exog_dtypes not in exog.columns
    exog_dtypes = {k: v for k, v in exog_dtypes.items() if k in exog.columns}

    if isinstance(exog, pd.Series) and exog.dtypes != list(exog_dtypes.values())[0]:
        exog = exog.astype(list(exog_dtypes.values())[0])
    elif isinstance(exog, pd.DataFrame):
        for col, initial_dtype in exog_dtypes.items():
            if exog[col].dtypes != initial_dtype:
                if initial_dtype == "category" and exog[col].dtypes == float:
                    exog[col] = exog[col].astype(int).astype("category")
                else:
                    exog[col] = exog[col].astype(initial_dtype)

    return exog

skforecast.utils.utils.exog_to_direct

exog_to_direct(exog, steps)

Transforms exog to a pandas DataFrame with the shape needed for Direct forecasting.

Parameters:

Name Type Description Default
exog pandas Series, pandas DataFrame

Exogenous variables.

required
steps int

Number of steps that will be predicted using exog.

required

Returns:

Name Type Description
exog_direct pandas DataFrame

Exogenous variables transformed.

exog_direct_names list

Names of the columns of the exogenous variables transformed. Only created if exog is a pandas Series or DataFrame.

Source code in skforecast\utils\utils.py
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
def exog_to_direct(
    exog: Union[pd.Series, pd.DataFrame],
    steps: int
) -> Union[pd.DataFrame, list]:
    """
    Transforms `exog` to a pandas DataFrame with the shape needed for Direct
    forecasting.

    Parameters
    ----------
    exog : pandas Series, pandas DataFrame
        Exogenous variables.
    steps : int
        Number of steps that will be predicted using exog.

    Returns
    -------
    exog_direct : pandas DataFrame
        Exogenous variables transformed.
    exog_direct_names : list
        Names of the columns of the exogenous variables transformed. Only 
        created if `exog` is a pandas Series or DataFrame.

    """

    if not isinstance(exog, (pd.Series, pd.DataFrame)):
        raise TypeError(f"`exog` must be a pandas Series or DataFrame. Got {type(exog)}.")

    if isinstance(exog, pd.Series):
        exog = exog.to_frame()

    n_rows = len(exog)
    exog_idx = exog.index
    exog_cols = exog.columns
    exog_direct = []
    for i in range(steps):
        exog_step = exog.iloc[i : n_rows - (steps - 1 - i), ]
        exog_step.index = pd.RangeIndex(len(exog_step))
        exog_step.columns = [f"{col}_step_{i + 1}" for col in exog_cols]
        exog_direct.append(exog_step)

    if len(exog_direct) > 1:
        exog_direct = pd.concat(exog_direct, axis=1, copy=False)
    else:
        exog_direct = exog_direct[0]

    exog_direct_names = exog_direct.columns.to_list()
    exog_direct.index = exog_idx[-len(exog_direct):]

    return exog_direct, exog_direct_names

skforecast.utils.utils.exog_to_direct_numpy

exog_to_direct_numpy(exog, steps)

Transforms exog to numpy ndarray with the shape needed for Direct forecasting.

Parameters:

Name Type Description Default
exog numpy ndarray, pandas Series, pandas DataFrame

Exogenous variables, shape(samples,). If exog is a pandas format, the direct exog names are created.

required
steps int

Number of steps that will be predicted using exog.

required

Returns:

Name Type Description
exog_direct numpy ndarray

Exogenous variables transformed.

exog_direct_names (list, None)

Names of the columns of the exogenous variables transformed. Only created if exog is a pandas Series or DataFrame.

Source code in skforecast\utils\utils.py
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
def exog_to_direct_numpy(
    exog: Union[np.ndarray, pd.Series, pd.DataFrame],
    steps: int
) -> Tuple[np.ndarray, Optional[list]]:
    """
    Transforms `exog` to numpy ndarray with the shape needed for Direct
    forecasting.

    Parameters
    ----------
    exog : numpy ndarray, pandas Series, pandas DataFrame
        Exogenous variables, shape(samples,). If exog is a pandas format, the 
        direct exog names are created.
    steps : int
        Number of steps that will be predicted using exog.

    Returns
    -------
    exog_direct : numpy ndarray
        Exogenous variables transformed.
    exog_direct_names : list, None
        Names of the columns of the exogenous variables transformed. Only 
        created if `exog` is a pandas Series or DataFrame.

    """

    if isinstance(exog, (pd.Series, pd.DataFrame)):
        exog_cols = exog.columns if isinstance(exog, pd.DataFrame) else [exog.name]
        exog_direct_names = [
            f"{col}_step_{i + 1}" for i in range(steps) for col in exog_cols
        ]
        exog = exog.to_numpy()
    else:
        exog_direct_names = None
        if not isinstance(exog, np.ndarray):
            raise TypeError(
                f"`exog` must be a numpy ndarray, pandas Series or DataFrame. "
                f"Got {type(exog)}."
            )

    if exog.ndim == 1:
        exog = np.expand_dims(exog, axis=1)

    n_rows = len(exog)
    exog_direct = []
    for i in range(steps):
        exog_step = exog[i : n_rows - (steps - 1 - i)]
        exog_direct.append(exog_step)

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

    return exog_direct, exog_direct_names

skforecast.utils.utils.expand_index

expand_index(index, steps)

Create a new index of length steps starting at the end of the index.

Parameters:

Name Type Description Default
index pandas Index, None

Original index.

required
steps int

Number of steps to expand.

required

Returns:

Name Type Description
new_index pandas Index

New index.

Source code in skforecast\utils\utils.py
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
def expand_index(
    index: Union[pd.Index, None], 
    steps: int
) -> pd.Index:
    """
    Create a new index of length `steps` starting at the end of the index.

    Parameters
    ----------
    index : pandas Index, None
        Original index.
    steps : int
        Number of steps to expand.

    Returns
    -------
    new_index : pandas Index
        New index.

    """

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

    if isinstance(index, pd.Index):

        if isinstance(index, pd.DatetimeIndex):
            new_index = pd.date_range(
                            start   = index[-1] + index.freq,
                            periods = steps,
                            freq    = index.freq
                        )
        elif isinstance(index, pd.RangeIndex):
            new_index = pd.RangeIndex(
                            start = index[-1] + 1,
                            stop  = index[-1] + 1 + steps
                        )
        else:
            raise TypeError(
                "Argument `index` must be a pandas DatetimeIndex or RangeIndex."
            )
    else:
        new_index = pd.RangeIndex(
                        start = 0,
                        stop  = steps
                    )

    return new_index

skforecast.utils.utils.transform_numpy

transform_numpy(
    array, transformer, fit=False, inverse_transform=False
)

Transform raw values of a numpy ndarray with a scikit-learn alike transformer, preprocessor or ColumnTransformer. The transformer used must have the following methods: fit, transform, fit_transform and inverse_transform. ColumnTransformers are not allowed since they do not have inverse_transform method.

Parameters:

Name Type Description Default
array numpy ndarray

Array to be transformed.

required
transformer scikit-learn alike transformer, preprocessor, or ColumnTransformer.

Scikit-learn alike transformer (preprocessor) with methods: fit, transform, fit_transform and inverse_transform.

required
fit bool

Train the transformer before applying it.

`False`
inverse_transform bool

Transform back the data to the original representation. This is not available when using transformers of class scikit-learn ColumnTransformers.

`False`

Returns:

Name Type Description
array_transformed numpy ndarray

Transformed array.

Source code in skforecast\utils\utils.py
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
1632
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
def transform_numpy(
    array: np.ndarray,
    transformer,
    fit: bool = False,
    inverse_transform: bool = False
) -> np.ndarray:
    """
    Transform raw values of a numpy ndarray with a scikit-learn alike 
    transformer, preprocessor or ColumnTransformer. The transformer used must 
    have the following methods: fit, transform, fit_transform and 
    inverse_transform. ColumnTransformers are not allowed since they do not 
    have inverse_transform method.

    Parameters
    ----------
    array : numpy ndarray
        Array to be transformed.
    transformer : scikit-learn alike transformer, preprocessor, or ColumnTransformer.
        Scikit-learn alike transformer (preprocessor) with methods: fit, transform,
        fit_transform and inverse_transform.
    fit : bool, default `False`
        Train the transformer before applying it.
    inverse_transform : bool, default `False`
        Transform back the data to the original representation. This is not available
        when using transformers of class scikit-learn ColumnTransformers.

    Returns
    -------
    array_transformed : numpy ndarray
        Transformed array.

    """

    if not isinstance(array, np.ndarray):
        raise TypeError(
            f"`array` argument must be a numpy ndarray. Got {type(array)}"
        )

    if transformer is None:
        return array

    array_ndim = array.ndim
    if array_ndim == 1:
        array = array.reshape(-1, 1)

    if inverse_transform and isinstance(transformer, ColumnTransformer):
        raise ValueError(
            "`inverse_transform` is not available when using ColumnTransformers."
        )

    if not inverse_transform:
        if fit:
            array_transformed = transformer.fit_transform(array)
        else:
            with warnings.catch_warnings():
                warnings.filterwarnings(
                    "ignore", 
                    message="X does not have valid feature names", 
                    category=UserWarning
                )
                array_transformed = transformer.transform(array)
    else:
        array_transformed = transformer.inverse_transform(array)

    if hasattr(array_transformed, 'toarray'):
        # If the returned values are in sparse matrix format, it is converted to dense
        array_transformed = array_transformed.toarray()

    if array_ndim == 1:
        array_transformed = array_transformed.ravel()

    return array_transformed

skforecast.utils.utils.transform_series

transform_series(
    series, transformer, fit=False, inverse_transform=False
)

Transform raw values of pandas Series with a scikit-learn alike transformer, preprocessor or ColumnTransformer. The transformer used must have the following methods: fit, transform, fit_transform and inverse_transform. ColumnTransformers are not allowed since they do not have inverse_transform method.

Parameters:

Name Type Description Default
series pandas Series

Series to be transformed.

required
transformer scikit-learn alike transformer, preprocessor, or ColumnTransformer.

Scikit-learn alike transformer (preprocessor) with methods: fit, transform, fit_transform and inverse_transform.

required
fit bool

Train the transformer before applying it.

`False`
inverse_transform bool

Transform back the data to the original representation. This is not available when using transformers of class scikit-learn ColumnTransformers.

`False`

Returns:

Name Type Description
series_transformed pandas Series, pandas DataFrame

Transformed Series. Depending on the transformer used, the output may be a Series or a DataFrame.

Source code in skforecast\utils\utils.py
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
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
def transform_series(
    series: pd.Series,
    transformer,
    fit: bool = False,
    inverse_transform: bool = False
) -> Union[pd.Series, pd.DataFrame]:
    """
    Transform raw values of pandas Series with a scikit-learn alike 
    transformer, preprocessor or ColumnTransformer. The transformer used must 
    have the following methods: fit, transform, fit_transform and 
    inverse_transform. ColumnTransformers are not allowed since they do not 
    have inverse_transform method.

    Parameters
    ----------
    series : pandas Series
        Series to be transformed.
    transformer : scikit-learn alike transformer, preprocessor, or ColumnTransformer.
        Scikit-learn alike transformer (preprocessor) with methods: fit, transform,
        fit_transform and inverse_transform.
    fit : bool, default `False`
        Train the transformer before applying it.
    inverse_transform : bool, default `False`
        Transform back the data to the original representation. This is not available
        when using transformers of class scikit-learn ColumnTransformers.

    Returns
    -------
    series_transformed : pandas Series, pandas DataFrame
        Transformed Series. Depending on the transformer used, the output may 
        be a Series or a DataFrame.

    """

    if not isinstance(series, pd.Series):
        raise TypeError(
            (f"`series` argument must be a pandas Series. Got {type(series)}.")
        )

    if transformer is None:
        return series

    if series.name is None:
        series.name = 'no_name'

    data = series.to_frame()

    if fit and hasattr(transformer, 'fit'):
        transformer.fit(data)

    # If argument feature_names_in_ exits, is overwritten to allow using the 
    # transformer on other series than those that were passed during fit.
    if hasattr(transformer, 'feature_names_in_') and transformer.feature_names_in_[0] != data.columns[0]:
        transformer = deepcopy(transformer)
        transformer.feature_names_in_ = np.array([data.columns[0]], dtype=object)

    with warnings.catch_warnings():
        warnings.simplefilter("ignore", category=UserWarning)
        if inverse_transform:
            values_transformed = transformer.inverse_transform(data)
        else:
            values_transformed = transformer.transform(data)   

    if hasattr(values_transformed, 'toarray'):
        # If the returned values are in sparse matrix format, it is converted to dense array.
        values_transformed = values_transformed.toarray()

    if isinstance(values_transformed, np.ndarray) and values_transformed.shape[1] == 1:
        series_transformed = pd.Series(
                                 data  = values_transformed.ravel(),
                                 index = data.index,
                                 name  = data.columns[0]
                             )
    elif isinstance(values_transformed, pd.DataFrame) and values_transformed.shape[1] == 1:
        series_transformed = values_transformed.squeeze()
    else:
        series_transformed = pd.DataFrame(
                                 data    = values_transformed,
                                 index   = data.index,
                                 columns = transformer.get_feature_names_out()
                             )

    return series_transformed

skforecast.utils.utils.transform_dataframe

transform_dataframe(
    df, transformer, fit=False, inverse_transform=False
)

Transform raw values of pandas DataFrame with a scikit-learn alike transformer, preprocessor or ColumnTransformer. The transformer used must have the following methods: fit, transform, fit_transform and inverse_transform. ColumnTransformers are not allowed since they do not have inverse_transform method.

Parameters:

Name Type Description Default
df pandas DataFrame

DataFrame to be transformed.

required
transformer scikit-learn alike transformer, preprocessor, or ColumnTransformer.

Scikit-learn alike transformer (preprocessor) with methods: fit, transform, fit_transform and inverse_transform.

required
fit bool

Train the transformer before applying it.

`False`
inverse_transform bool

Transform back the data to the original representation. This is not available when using transformers of class scikit-learn ColumnTransformers.

`False`

Returns:

Name Type Description
df_transformed pandas DataFrame

Transformed DataFrame.

Source code in skforecast\utils\utils.py
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
def transform_dataframe(
    df: pd.DataFrame,
    transformer,
    fit: bool = False,
    inverse_transform: bool = False
) -> pd.DataFrame:
    """
    Transform raw values of pandas DataFrame with a scikit-learn alike 
    transformer, preprocessor or ColumnTransformer. The transformer used must 
    have the following methods: fit, transform, fit_transform and 
    inverse_transform. ColumnTransformers are not allowed since they do not 
    have inverse_transform method.

    Parameters
    ----------
    df : pandas DataFrame
        DataFrame to be transformed.
    transformer : scikit-learn alike transformer, preprocessor, or ColumnTransformer.
        Scikit-learn alike transformer (preprocessor) with methods: fit, transform,
        fit_transform and inverse_transform.
    fit : bool, default `False`
        Train the transformer before applying it.
    inverse_transform : bool, default `False`
        Transform back the data to the original representation. This is not available
        when using transformers of class scikit-learn ColumnTransformers.

    Returns
    -------
    df_transformed : pandas DataFrame
        Transformed DataFrame.

    """

    if not isinstance(df, pd.DataFrame):
        raise TypeError(
            f"`df` argument must be a pandas DataFrame. Got {type(df)}"
        )

    if transformer is None:
        return df

    if inverse_transform and isinstance(transformer, ColumnTransformer):
        raise ValueError(
            "`inverse_transform` is not available when using ColumnTransformers."
        )

    if not inverse_transform:
        if fit:
            values_transformed = transformer.fit_transform(df)
        else:
            values_transformed = transformer.transform(df)
    else:
        values_transformed = transformer.inverse_transform(df)

    if hasattr(values_transformed, 'toarray'):
        # If the returned values are in sparse matrix format, it is converted to dense
        values_transformed = values_transformed.toarray()

    if hasattr(transformer, 'get_feature_names_out'):
        feature_names_out = transformer.get_feature_names_out()
    elif hasattr(transformer, 'categories_'):   
        feature_names_out = transformer.categories_
    else:
        feature_names_out = df.columns

    df_transformed = pd.DataFrame(
                         data    = values_transformed,
                         index   = df.index,
                         columns = feature_names_out
                     )

    return df_transformed

skforecast.utils.utils.check_optional_dependency

check_optional_dependency(package_name)

Check if an optional dependency is installed, if not raise an ImportError
with installation instructions.

Parameters:

Name Type Description Default
package_name str

Name of the package to check.

required

Returns:

Type Description
None
Source code in skforecast\utils\utils.py
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
def check_optional_dependency(
    package_name: str
) -> None:
    """
    Check if an optional dependency is installed, if not raise an ImportError  
    with installation instructions.

    Parameters
    ----------
    package_name : str
        Name of the package to check.

    Returns
    -------
    None

    """

    if importlib.util.find_spec(package_name) is None:
        try:
            extra, package_version = _find_optional_dependency(package_name=package_name)
            msg = (
                f"\n'{package_name}' is an optional dependency not included in the default "
                f"skforecast installation. Please run: `pip install \"{package_version}\"` to install it."
                f"\n\nAlternately, you can install it by running `pip install skforecast[{extra}]`"
            )
        except:
            msg = f"\n'{package_name}' is needed but not installed. Please install it."

        raise ImportError(msg)

skforecast.utils.utils.multivariate_time_series_corr

multivariate_time_series_corr(
    time_series, other, lags, method="pearson"
)

Compute correlation between a time_series and the lagged values of other time series.

Parameters:

Name Type Description Default
time_series pandas Series

Target time series.

required
other pandas DataFrame

Time series whose lagged values are correlated to time_series.

required
lags int, list, numpy ndarray

Lags to be included in the correlation analysis.

required
method str
  • 'pearson': standard correlation coefficient.
  • 'kendall': Kendall Tau correlation coefficient.
  • 'spearman': Spearman rank correlation.
'pearson'

Returns:

Name Type Description
corr pandas DataFrame

Correlation values.

Source code in skforecast\utils\utils.py
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
def multivariate_time_series_corr(
    time_series: pd.Series,
    other: pd.DataFrame,
    lags: Union[int, list, np.array],
    method: str = 'pearson'
) -> pd.DataFrame:
    """
    Compute correlation between a time_series and the lagged values of other 
    time series. 

    Parameters
    ----------
    time_series : pandas Series
        Target time series.
    other : pandas DataFrame
        Time series whose lagged values are correlated to `time_series`.
    lags : int, list, numpy ndarray
        Lags to be included in the correlation analysis.
    method : str, default 'pearson'
        - 'pearson': standard correlation coefficient.
        - 'kendall': Kendall Tau correlation coefficient.
        - 'spearman': Spearman rank correlation.

    Returns
    -------
    corr : pandas DataFrame
        Correlation values.

    """

    if not len(time_series) == len(other):
        raise ValueError("`time_series` and `other` must have the same length.")

    if not (time_series.index == other.index).all():
        raise ValueError("`time_series` and `other` must have the same index.")

    if isinstance(lags, int):
        lags = range(lags)

    corr = {}
    for col in other.columns:
        lag_values = {}
        for lag in lags:
            lag_values[lag] = other[col].shift(lag)

        lag_values = pd.DataFrame(lag_values)
        lag_values.insert(0, None, time_series)
        corr[col] = lag_values.corr(method=method).iloc[1:, 0]

    corr = pd.DataFrame(corr)
    corr.index = corr.index.astype('int64')
    corr.index.name = "lag"

    return corr

skforecast.utils.utils.select_n_jobs_fit_forecaster

select_n_jobs_fit_forecaster(forecaster_name, regressor)

Select the optimal number of jobs to use in the fitting process. This selection is based on heuristics and is not guaranteed to be optimal.

The number of jobs is chosen as follows:

  • If forecaster_name is 'ForecasterDirect' or 'ForecasterDirectMultiVariate' and regressor_name is a linear regressor then n_jobs = 1, otherwise n_jobs = cpu_count() - 1.
  • If regressor is a LGBMRegressor(n_jobs=1), then n_jobs = cpu_count() - 1.
  • If regressor is a LGBMRegressor with internal n_jobs != 1, then n_jobs = 1. This is because lightgbm is highly optimized for gradient boosting and parallelizes operations at a very fine-grained level, making additional parallelization unnecessary and potentially harmful due to resource contention.

Parameters:

Name Type Description Default
forecaster_name str

Forecaster name.

required
regressor regressor or pipeline compatible with the scikit-learn API

An instance of a regressor or pipeline compatible with the scikit-learn API.

required

Returns:

Name Type Description
n_jobs int

The number of jobs to run in parallel.

Source code in skforecast\utils\utils.py
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
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
def select_n_jobs_fit_forecaster(
    forecaster_name: str,
    regressor: object,
) -> int:
    """
    Select the optimal number of jobs to use in the fitting process. This
    selection is based on heuristics and is not guaranteed to be optimal. 

    The number of jobs is chosen as follows:

    - If forecaster_name is 'ForecasterDirect' or 'ForecasterDirectMultiVariate'
    and regressor_name is a linear regressor then `n_jobs = 1`, 
    otherwise `n_jobs = cpu_count() - 1`.
    - If regressor is a `LGBMRegressor(n_jobs=1)`, then `n_jobs = cpu_count() - 1`.
    - If regressor is a `LGBMRegressor` with internal n_jobs != 1, then `n_jobs = 1`.
    This is because `lightgbm` is highly optimized for gradient boosting and
    parallelizes operations at a very fine-grained level, making additional
    parallelization unnecessary and potentially harmful due to resource contention.

    Parameters
    ----------
    forecaster_name : str
        Forecaster name.
    regressor : regressor or pipeline compatible with the scikit-learn API
        An instance of a regressor or pipeline compatible with the scikit-learn API.

    Returns
    -------
    n_jobs : int
        The number of jobs to run in parallel.

    """

    if isinstance(regressor, Pipeline):
        regressor = regressor[-1]
        regressor_name = type(regressor).__name__
    else:
        regressor_name = type(regressor).__name__

    linear_regressors = [
        regressor_name
        for regressor_name in dir(sklearn.linear_model)
        if not regressor_name.startswith('_')
    ]

    if forecaster_name in ['ForecasterDirect', 
                           'ForecasterDirectMultiVariate']:
        if regressor_name in linear_regressors:
            n_jobs = 1
        elif regressor_name == 'LGBMRegressor':
            n_jobs = joblib.cpu_count() - 1 if regressor.n_jobs == 1 else 1
        else:
            n_jobs = joblib.cpu_count() - 1
    else:
        n_jobs = 1

    return n_jobs

skforecast.utils.utils.check_preprocess_series

check_preprocess_series(series)

Check and preprocess series argument in ForecasterRecursiveMultiSeries class.

  • If series is a pandas DataFrame, it is converted to a dict of pandas Series and index is overwritten according to the rules of preprocess_y.
  • If series is a dict, all values are converted to pandas Series. Checks if all index are pandas DatetimeIndex and, at least, one Series has a non-null frequency. No multiple frequency is allowed.

Parameters:

Name Type Description Default
series pandas DataFrame, dict

Training time series.

required

Returns:

Name Type Description
series_dict dict

Dictionary with the series used during training.

series_indexes dict

Dictionary with the index of each series.

Source code in skforecast\utils\utils.py
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
def check_preprocess_series(
    series: Union[pd.DataFrame, dict],
) -> Tuple[dict, pd.Index]:
    """
    Check and preprocess `series` argument in `ForecasterRecursiveMultiSeries` class.

    - If `series` is a pandas DataFrame, it is converted to a dict of pandas 
    Series and index is overwritten according to the rules of preprocess_y.
    - If `series` is a dict, all values are converted to pandas Series. Checks
    if all index are pandas DatetimeIndex and, at least, one Series has a non-null
    frequency. No multiple frequency is allowed.

    Parameters
    ----------
    series : pandas DataFrame, dict
        Training time series.

    Returns
    -------
    series_dict : dict
        Dictionary with the series used during training.
    series_indexes : dict
        Dictionary with the index of each series.

    """

    if isinstance(series, pd.DataFrame):

        _, series_index = preprocess_y(y=series, return_values=False)
        series = series.copy()
        series.index = series_index
        series_dict = series.to_dict("series")

    elif isinstance(series, dict):

        not_valid_series = [
            k 
            for k, v in series.items()
            if not isinstance(v, (pd.Series, pd.DataFrame))
        ]
        if not_valid_series:
            raise TypeError(
                (f"If `series` is a dictionary, all series must be a named "
                 f"pandas Series or a pandas DataFrame with a single column. "
                 f"Review series: {not_valid_series}")
            )

        series_dict = {
            k: v.copy()
            for k, v in series.items()
        }

        for k, v in series_dict.items():
            if isinstance(v, pd.DataFrame):
                if v.shape[1] != 1:
                    raise ValueError(
                        (f"If `series` is a dictionary, all series must be a named "
                         f"pandas Series or a pandas DataFrame with a single column. "
                         f"Review series: '{k}'")
                    )
                series_dict[k] = v.iloc[:, 0]

            series_dict[k].name = k

        not_valid_index = [
            k 
            for k, v in series_dict.items()
            if not isinstance(v.index, pd.DatetimeIndex)
        ]
        if not_valid_index:
            raise TypeError(
                (f"If `series` is a dictionary, all series must have a Pandas "
                 f"DatetimeIndex as index with the same frequency. "
                 f"Review series: {not_valid_index}")
            )

        indexes_freq = [f"{v.index.freq}" for v in series_dict.values()]
        indexes_freq = sorted(set(indexes_freq))
        if not len(indexes_freq) == 1:
            raise ValueError(
                (f"If `series` is a dictionary, all series must have a Pandas "
                 f"DatetimeIndex as index with the same frequency. "
                 f"Found frequencies: {indexes_freq}")
            )
    else:
        raise TypeError(
            (f"`series` must be a pandas DataFrame or a dict of DataFrames or Series. "
             f"Got {type(series)}.")
        )

    for k, v in series_dict.items():
        if np.isnan(v).all():
            raise ValueError(f"All values of series '{k}' are NaN.")

    series_indexes = {
        k: v.index
        for k, v in series_dict.items()
    }

    return series_dict, series_indexes

skforecast.utils.utils.check_preprocess_exog_multiseries

check_preprocess_exog_multiseries(
    input_series_is_dict,
    series_indexes,
    series_names_in_,
    exog,
    exog_dict,
)

Check and preprocess exog argument in ForecasterRecursiveMultiSeries class.

  • If input series is a pandas DataFrame (input_series_is_dict = False),
    checks that input exog (pandas Series, DataFrame or dict) has the same index (type, length and frequency). Index is overwritten according to the rules of preprocess_exog. Create a dict of exog with the same keys as series.
  • If input series is a dict (input_series_is_dict = True), then input exog must be a dict. Check exog has a pandas DatetimeIndex and convert all values to pandas DataFrames.

Parameters:

Name Type Description Default
input_series_is_dict bool

Indicates if input series argument is a dict.

required
series_indexes dict

Dictionary with the index of each series.

required
series_names_in_ list

Names of the series (levels) used during training.

required
exog pandas Series, pandas DataFrame, dict

Exogenous variable/s used during training.

required
exog_dict dict

Dictionary with the exogenous variable/s used during training.

required

Returns:

Name Type Description
exog_dict dict

Dictionary with the exogenous variable/s used during training.

exog_names_in_ list

Names of the exogenous variables used during training.

Source code in skforecast\utils\utils.py
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
def check_preprocess_exog_multiseries(
    input_series_is_dict: bool,
    series_indexes: dict,
    series_names_in_: list,
    exog: Union[pd.Series, pd.DataFrame, dict],
    exog_dict: dict,
) -> Tuple[dict, list]:
    """
    Check and preprocess `exog` argument in `ForecasterRecursiveMultiSeries` class.

    - If input series is a pandas DataFrame (input_series_is_dict = False),  
    checks that input exog (pandas Series, DataFrame or dict) has the same index 
    (type, length and frequency). Index is overwritten according to the rules 
    of preprocess_exog. Create a dict of exog with the same keys as series.
    - If input series is a dict (input_series_is_dict = True), then input 
    exog must be a dict. Check exog has a pandas DatetimeIndex and convert all
    values to pandas DataFrames.

    Parameters
    ----------
    input_series_is_dict : bool
        Indicates if input series argument is a dict.
    series_indexes : dict
        Dictionary with the index of each series.
    series_names_in_ : list
        Names of the series (levels) used during training.
    exog : pandas Series, pandas DataFrame, dict
        Exogenous variable/s used during training.
    exog_dict : dict
        Dictionary with the exogenous variable/s used during training.

    Returns
    -------
    exog_dict : dict
        Dictionary with the exogenous variable/s used during training.
    exog_names_in_ : list
        Names of the exogenous variables used during training.

    """

    if not isinstance(exog, (pd.Series, pd.DataFrame, dict)):
        raise TypeError(
            (f"`exog` must be a pandas Series, DataFrame, dictionary of pandas "
             f"Series/DataFrames or None. Got {type(exog)}.")
        )

    if not input_series_is_dict:
        # If input series is a pandas DataFrame, all index are the same.
        # Select the first index to check exog
        series_index = series_indexes[series_names_in_[0]]

    if isinstance(exog, (pd.Series, pd.DataFrame)): 

        if input_series_is_dict:
            raise TypeError(
                (f"`exog` must be a dict of DataFrames or Series if "
                 f"`series` is a dict. Got {type(exog)}.")
            )

        _, exog_index = preprocess_exog(exog=exog, return_values=False)
        exog = exog.copy().to_frame() if isinstance(exog, pd.Series) else exog.copy()
        exog.index = exog_index

        if len(exog) != len(series_index):
            raise ValueError(
                (f"`exog` must have same number of samples as `series`. "
                 f"length `exog`: ({len(exog)}), length `series`: ({len(series_index)})")
            )

        if not (exog_index == series_index).all():
            raise ValueError(
                ("Different index for `series` and `exog`. They must be equal "
                 "to ensure the correct alignment of values.")
            )

        exog_dict = {serie: exog for serie in series_names_in_}

    else:

        not_valid_exog = [
            k 
            for k, v in exog.items()
            if not isinstance(v, (pd.Series, pd.DataFrame, type(None)))
        ]
        if not_valid_exog:
            raise TypeError(
                (f"If `exog` is a dictionary, all exog must be a named pandas "
                 f"Series, a pandas DataFrame or None. Review exog: {not_valid_exog}")
            )

        # Only elements already present in exog_dict are updated
        exog_dict.update(
            (k, v.copy())
            for k, v in exog.items() 
            if k in exog_dict and v is not None
        )

        series_not_in_exog = set(series_names_in_) - set(exog.keys())
        if series_not_in_exog:
            warnings.warn(
                (f"{series_not_in_exog} not present in `exog`. All values "
                 f"of the exogenous variables for these series will be NaN."),
                 MissingExogWarning
            )

        for k, v in exog_dict.items():
            if v is not None:
                check_exog(exog=v, allow_nan=True)
                if isinstance(v, pd.Series):
                    v = v.to_frame()
                exog_dict[k] = v

        if not input_series_is_dict:
            for k, v in exog_dict.items():
                if v is not None:
                    if len(v) != len(series_index):
                        raise ValueError(
                            (f"`exog` for series '{k}' must have same number of "
                             f"samples as `series`. length `exog`: ({len(v)}), "
                             f"length `series`: ({len(series_index)})")
                        )

                    _, v_index = preprocess_exog(exog=v, return_values=False)
                    exog_dict[k].index = v_index
                    if not (exog_dict[k].index == series_index).all():
                        raise ValueError(
                            (f"Different index for series '{k}' and its exog. "
                             f"When `series` is a pandas DataFrame, they must be "
                             f"equal to ensure the correct alignment of values.")
                        )
        else:
            not_valid_index = [
                k
                for k, v in exog_dict.items()
                if v is not None and not isinstance(v.index, pd.DatetimeIndex)
            ]
            if not_valid_index:
                raise TypeError(
                    (f"All exog must have a Pandas DatetimeIndex as index with the "
                     f"same frequency. Check exog for series: {not_valid_index}")
                )

        # Check that all exog have the same dtypes for common columns
        exog_dtypes_buffer = [df.dtypes for df in exog_dict.values() if df is not None]
        exog_dtypes_buffer = pd.concat(exog_dtypes_buffer, axis=1)
        exog_dtypes_nunique = exog_dtypes_buffer.nunique(axis=1).eq(1)
        if not exog_dtypes_nunique.all():
            non_unique_dtyeps_exogs = exog_dtypes_nunique[exog_dtypes_nunique != 1].index.to_list()
            raise TypeError(f"Exog/s: {non_unique_dtyeps_exogs} have different dtypes in different series.")

    exog_names_in_ = list(
        set(
            column
            for df in exog_dict.values()
            if df is not None
            for column in df.columns.to_list()
        )
    )

    if len(set(exog_names_in_) - set(series_names_in_)) != len(exog_names_in_):
        raise ValueError(
            (f"`exog` cannot contain a column named the same as one of the series.\n"
             f"    `series` columns : {series_names_in_}.\n"
             f"    `exog`   columns : {exog_names_in_}.")
        )

    return exog_dict, exog_names_in_

skforecast.utils.utils.align_series_and_exog_multiseries

align_series_and_exog_multiseries(
    series_dict, input_series_is_dict, exog_dict=None
)

Align series and exog according to their index. If needed, reindexing is applied. Heading and trailing NaNs are removed from all series in series_dict.

  • If input series is a pandas DataFrame (input_series_is_dict = False),
    input exog (pandas Series, DataFrame or dict) must have the same index (type, length and frequency). Reindexing is not applied.
  • If input series is a dict (input_series_is_dict = True), then input exog must be a dict. Both must have a pandas DatetimeIndex, but can have different lengths. Reindexing is applied.

Parameters:

Name Type Description Default
series_dict dict

Dictionary with the series used during training.

required
input_series_is_dict bool

Indicates if input series argument is a dict.

required
exog_dict dict

Dictionary with the exogenous variable/s used during training.

`None`

Returns:

Name Type Description
series_dict dict

Dictionary with the series used during training.

exog_dict dict

Dictionary with the exogenous variable/s used during training.

Source code in skforecast\utils\utils.py
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
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
def align_series_and_exog_multiseries(
    series_dict: dict,
    input_series_is_dict: bool,
    exog_dict: dict = None
) -> Tuple[Union[pd.Series, pd.DataFrame], Union[pd.Series, pd.DataFrame]]:
    """
    Align series and exog according to their index. If needed, reindexing is
    applied. Heading and trailing NaNs are removed from all series in 
    `series_dict`.

    - If input series is a pandas DataFrame (input_series_is_dict = False),  
    input exog (pandas Series, DataFrame or dict) must have the same index 
    (type, length and frequency). Reindexing is not applied.
    - If input series is a dict (input_series_is_dict = True), then input 
    exog must be a dict. Both must have a pandas DatetimeIndex, but can have 
    different lengths. Reindexing is applied.

    Parameters
    ----------
    series_dict : dict
        Dictionary with the series used during training.
    input_series_is_dict : bool
        Indicates if input series argument is a dict.
    exog_dict : dict, default `None`
        Dictionary with the exogenous variable/s used during training.

    Returns
    -------
    series_dict : dict
        Dictionary with the series used during training.
    exog_dict : dict
        Dictionary with the exogenous variable/s used during training.

    """

    for k in series_dict.keys():

        first_valid_index = series_dict[k].first_valid_index()
        last_valid_index = series_dict[k].last_valid_index()

        series_dict[k] = series_dict[k].loc[first_valid_index : last_valid_index]

        if exog_dict[k] is not None:
            if input_series_is_dict:
                index_intersection = (
                    series_dict[k].index.intersection(exog_dict[k].index)
                )
                if len(index_intersection) == 0:
                    warnings.warn(
                        (f"Series '{k}' and its `exog` do not have the same index. "
                         f"All exog values will be NaN for the period of the series."),
                         MissingValuesWarning
                    )
                elif len(index_intersection) != len(series_dict[k]):
                    warnings.warn(
                        (f"Series '{k}' and its `exog` do not have the same length. "
                         f"Exog values will be NaN for the not matched period of the series."),
                         MissingValuesWarning
                    )  
                exog_dict[k] = exog_dict[k].loc[index_intersection]
                if len(index_intersection) != len(series_dict[k]):
                    exog_dict[k] = exog_dict[k].reindex(
                                       series_dict[k].index, 
                                       fill_value = np.nan
                                   )
            else:
                exog_dict[k] = exog_dict[k].loc[first_valid_index : last_valid_index]

    return series_dict, exog_dict

skforecast.utils.utils.prepare_levels_multiseries

prepare_levels_multiseries(
    X_train_series_names_in_, levels=None
)

Prepare list of levels to be predicted in multiseries Forecasters.

Parameters:

Name Type Description Default
X_train_series_names_in_ list

Names of the series (levels) included in the matrix X_train.

required
levels (str, list)

Names of the series (levels) to be predicted.

`None`

Returns:

Name Type Description
levels list

Names of the series (levels) to be predicted.

Source code in skforecast\utils\utils.py
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
def prepare_levels_multiseries(
    X_train_series_names_in_: list,
    levels: Optional[Union[str, list]] = None
) -> Tuple[list, bool]:
    """
    Prepare list of levels to be predicted in multiseries Forecasters.

    Parameters
    ----------
    X_train_series_names_in_ : list
        Names of the series (levels) included in the matrix `X_train`.
    levels : str, list, default `None`
        Names of the series (levels) to be predicted.

    Returns
    -------
    levels : list
        Names of the series (levels) to be predicted.

    """

    input_levels_is_list = False
    if levels is None:
        levels = X_train_series_names_in_
    elif isinstance(levels, str):
        levels = [levels]
    else:
        input_levels_is_list = True

    return levels, input_levels_is_list

skforecast.utils.utils.preprocess_levels_self_last_window_multiseries

preprocess_levels_self_last_window_multiseries(
    levels, input_levels_is_list, last_window_
)

Preprocess levels and last_window (when using self.last_window_) arguments in multiseries Forecasters when predicting. Only levels whose last window ends at the same datetime index will be predicted together.

Parameters:

Name Type Description Default
levels list

Names of the series (levels) to be predicted.

required
input_levels_is_list bool

Indicates if input levels argument is a list.

required
last_window_ dict

Dictionary with the last window of each series (self.last_window_).

required

Returns:

Name Type Description
levels list

Names of the series (levels) to be predicted.

last_window pandas DataFrame

Series values used to create the predictors (lags) needed in the first iteration of the prediction (t + 1).

Source code in skforecast\utils\utils.py
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
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
def preprocess_levels_self_last_window_multiseries(
    levels: list,
    input_levels_is_list: bool,
    last_window_: dict
) -> Tuple[list, pd.DataFrame]:
    """
    Preprocess `levels` and `last_window` (when using self.last_window_) arguments 
    in multiseries Forecasters when predicting. Only levels whose last window 
    ends at the same datetime index will be predicted together.

    Parameters
    ----------
    levels : list
        Names of the series (levels) to be predicted.
    input_levels_is_list : bool
        Indicates if input levels argument is a list.
    last_window_ : dict
        Dictionary with the last window of each series (self.last_window_).

    Returns
    -------
    levels : list
        Names of the series (levels) to be predicted.
    last_window : pandas DataFrame
        Series values used to create the predictors (lags) needed in the 
        first iteration of the prediction (t + 1).

    """

    available_last_windows = set() if last_window_ is None else set(last_window_.keys())
    not_available_last_window = set(levels) - available_last_windows
    if not_available_last_window:
        levels = [level for level in levels 
                  if level not in not_available_last_window]
        if not levels:
            raise ValueError(
                (f"No series to predict. None of the series {not_available_last_window} "
                 f"are present in `last_window_` attribute. Provide `last_window` "
                 f"as argument in predict method.")
            )
        else:
            warnings.warn(
                (f"Levels {not_available_last_window} are excluded from "
                 f"prediction since they were not stored in `last_window_` "
                 f"attribute during training. If you don't want to retrain "
                 f"the Forecaster, provide `last_window` as argument."),
                 IgnoredArgumentWarning
            )

    last_index_levels = [
        v.index[-1] 
        for k, v in last_window_.items()
        if k in levels
    ]
    if len(set(last_index_levels)) > 1:
        max_index_levels = max(last_index_levels)
        selected_levels = [
            k
            for k, v in last_window_.items()
            if k in levels and v.index[-1] == max_index_levels
        ]

        series_excluded_from_last_window = set(levels) - set(selected_levels)
        levels = selected_levels

        if input_levels_is_list and series_excluded_from_last_window:
            warnings.warn(
                (f"Only series whose last window ends at the same index "
                 f"can be predicted together. Series that do not reach "
                 f"the maximum index, '{max_index_levels}', are excluded "
                 f"from prediction: {series_excluded_from_last_window}."),
                IgnoredArgumentWarning
            )

    last_window = pd.DataFrame(
        {k: v 
         for k, v in last_window_.items() 
         if k in levels}
    )

    return levels, last_window

skforecast.utils.utils.prepare_residuals_multiseries

prepare_residuals_multiseries(
    levels,
    use_in_sample_residuals,
    encoding=None,
    in_sample_residuals_=None,
    out_sample_residuals_=None,
)

Prepare residuals for bootstrapping prediction in multiseries Forecasters.

Parameters:

Name Type Description Default
levels list

Names of the series (levels) to be predicted.

required
use_in_sample_residuals bool

Indicates if forecaster.in_sample_residuals_ are used.

required
encoding str

Encoding used to identify the different series (ForecasterRecursiveMultiSeries).

`None`
in_sample_residuals_ dict

Residuals of the model when predicting training data. Only stored up to 1000 values in the form {level: residuals}. If transformer_series is not None, residuals are stored in the transformed scale.

`None`
out_sample_residuals_ dict

Residuals of the model when predicting non-training data. Only stored up to 1000 values in the form {level: residuals}. If transformer_series is not None, residuals are assumed to be in the transformed scale. Use set_out_sample_residuals() method to set values.

`None`

Returns:

Name Type Description
levels list

Names of the series (levels) to be predicted.

residuals dict

Residuals of the model for each level to use in bootstrapping prediction.

Source code in skforecast\utils\utils.py
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
2617
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
def prepare_residuals_multiseries(
    levels: list,
    use_in_sample_residuals: bool,
    encoding: Optional[str] = None,
    in_sample_residuals_: Optional[dict] = None,
    out_sample_residuals_: Optional[dict] = None
) -> Tuple[list, bool]:
    """
    Prepare residuals for bootstrapping prediction in multiseries Forecasters.

    Parameters
    ----------
    levels : list
        Names of the series (levels) to be predicted.
    use_in_sample_residuals : bool
        Indicates if `forecaster.in_sample_residuals_` are used.
    encoding : str, default `None`
        Encoding used to identify the different series (`ForecasterRecursiveMultiSeries`).
    in_sample_residuals_ : dict, default `None`
        Residuals of the model when predicting training data. Only stored up to
        1000 values in the form `{level: residuals}`. If `transformer_series` 
        is not `None`, residuals are stored in the transformed scale.
    out_sample_residuals_ : dict, default `None`
        Residuals of the model when predicting non-training data. Only stored
        up to 1000 values in the form `{level: residuals}`. If `transformer_series` 
        is not `None`, residuals are assumed to be in the transformed scale. Use 
        `set_out_sample_residuals()` method to set values.

    Returns
    -------
    levels : list
        Names of the series (levels) to be predicted.
    residuals : dict
        Residuals of the model for each level to use in bootstrapping prediction.

    """

    if use_in_sample_residuals:
        unknown_levels = set(levels) - set(in_sample_residuals_.keys())
        if unknown_levels and encoding is not None:
            warnings.warn(
                (f"`levels` {unknown_levels} are not present in `forecaster.in_sample_residuals_`, "
                 f"most likely because they were not present in the training data. "
                 f"A random sample of the residuals from other levels will be used. "
                 f"This can lead to inaccurate intervals for the unknown levels."),
                 UnknownLevelWarning
            )
        residuals = in_sample_residuals_.copy()
    else:
        if out_sample_residuals_ is None:
            raise ValueError(
                ("`forecaster.out_sample_residuals_` is `None`. Use "
                 "`use_in_sample_residuals=True` or the "
                 "`set_out_sample_residuals()` method before predicting.")
            )
        else:
            unknown_levels = set(levels) - set(out_sample_residuals_.keys())
            if unknown_levels and encoding is not None:
                warnings.warn(
                    (f"`levels` {unknown_levels} are not present in `forecaster.out_sample_residuals_`. "
                     f"A random sample of the residuals from other levels will be used. "
                     f"This can lead to inaccurate intervals for the unknown levels. "
                     f"Otherwise, Use the `set_out_sample_residuals()` method before "
                     f"predicting to set the residuals for these levels."),
                     UnknownLevelWarning
                )
            residuals = out_sample_residuals_.copy()

    check_residuals = (
        "forecaster.in_sample_residuals_" if use_in_sample_residuals
        else "forecaster.out_sample_residuals_"
    )
    for level in levels:
        if level in unknown_levels:
            residuals[level] = residuals['_unknown_level']
        if residuals[level] is None or len(residuals[level]) == 0:
            raise ValueError(
                (f"Not available residuals for level '{level}'. "
                 f"Check `{check_residuals}`.")
            )
        elif (any(element is None for element in residuals[level]) or
              np.any(np.isnan(residuals[level]))):
            raise ValueError(
                (f"forecaster residuals for level '{level}' contains `None` "
                 f"or `NaNs` values. Check `{check_residuals}`.")
            )

    return residuals

skforecast.utils.utils.set_skforecast_warnings

set_skforecast_warnings(
    suppress_warnings, action="default"
)

Set skforecast warnings action.

Parameters:

Name Type Description Default
suppress_warnings bool

If True, skforecast warnings will be suppressed. If False, skforecast warnings will be shown as default. See skforecast.exceptions.warn_skforecast_categories for more information.

required
action str

Action to be taken when a warning is raised. See the warnings module for more information.

`'default'`

Returns:

Type Description
None
Source code in skforecast\utils\utils.py
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
def set_skforecast_warnings(
    suppress_warnings: bool,
    action: str = 'default'
) -> None:
    """
    Set skforecast warnings action.

    Parameters
    ----------
    suppress_warnings : bool
        If `True`, skforecast warnings will be suppressed. If `False`, skforecast
        warnings will be shown as default. See 
        skforecast.exceptions.warn_skforecast_categories for more information.
    action : str, default `'default'`
        Action to be taken when a warning is raised. See the warnings module
        for more information.

    Returns
    -------
    None

    """

    if suppress_warnings:
        for category in warn_skforecast_categories:
            warnings.filterwarnings(action, category=category)