autogluon.timeseries 1.4.1b20251115__py3-none-any.whl → 1.4.1b20251218__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of autogluon.timeseries might be problematic. Click here for more details.

Files changed (82) hide show
  1. autogluon/timeseries/configs/hyperparameter_presets.py +7 -21
  2. autogluon/timeseries/configs/predictor_presets.py +23 -39
  3. autogluon/timeseries/dataset/ts_dataframe.py +32 -34
  4. autogluon/timeseries/learner.py +67 -33
  5. autogluon/timeseries/metrics/__init__.py +4 -4
  6. autogluon/timeseries/metrics/abstract.py +8 -8
  7. autogluon/timeseries/metrics/point.py +9 -9
  8. autogluon/timeseries/metrics/quantile.py +4 -4
  9. autogluon/timeseries/models/__init__.py +2 -1
  10. autogluon/timeseries/models/abstract/abstract_timeseries_model.py +52 -39
  11. autogluon/timeseries/models/abstract/model_trial.py +2 -1
  12. autogluon/timeseries/models/abstract/tunable.py +8 -8
  13. autogluon/timeseries/models/autogluon_tabular/mlforecast.py +30 -26
  14. autogluon/timeseries/models/autogluon_tabular/per_step.py +12 -10
  15. autogluon/timeseries/models/autogluon_tabular/transforms.py +2 -2
  16. autogluon/timeseries/models/chronos/__init__.py +2 -1
  17. autogluon/timeseries/models/chronos/chronos2.py +395 -0
  18. autogluon/timeseries/models/chronos/model.py +29 -24
  19. autogluon/timeseries/models/chronos/utils.py +5 -5
  20. autogluon/timeseries/models/ensemble/__init__.py +17 -10
  21. autogluon/timeseries/models/ensemble/abstract.py +13 -9
  22. autogluon/timeseries/models/ensemble/array_based/__init__.py +2 -2
  23. autogluon/timeseries/models/ensemble/array_based/abstract.py +24 -31
  24. autogluon/timeseries/models/ensemble/array_based/models.py +146 -11
  25. autogluon/timeseries/models/ensemble/array_based/regressor/__init__.py +2 -0
  26. autogluon/timeseries/models/ensemble/array_based/regressor/abstract.py +6 -5
  27. autogluon/timeseries/models/ensemble/array_based/regressor/linear_stacker.py +186 -0
  28. autogluon/timeseries/models/ensemble/array_based/regressor/per_quantile_tabular.py +44 -83
  29. autogluon/timeseries/models/ensemble/array_based/regressor/tabular.py +21 -55
  30. autogluon/timeseries/models/ensemble/ensemble_selection.py +167 -0
  31. autogluon/timeseries/models/ensemble/per_item_greedy.py +172 -0
  32. autogluon/timeseries/models/ensemble/weighted/abstract.py +7 -3
  33. autogluon/timeseries/models/ensemble/weighted/basic.py +26 -13
  34. autogluon/timeseries/models/ensemble/weighted/greedy.py +20 -145
  35. autogluon/timeseries/models/gluonts/abstract.py +30 -29
  36. autogluon/timeseries/models/gluonts/dataset.py +9 -9
  37. autogluon/timeseries/models/gluonts/models.py +0 -7
  38. autogluon/timeseries/models/local/__init__.py +0 -7
  39. autogluon/timeseries/models/local/abstract_local_model.py +13 -16
  40. autogluon/timeseries/models/local/naive.py +2 -2
  41. autogluon/timeseries/models/local/npts.py +7 -1
  42. autogluon/timeseries/models/local/statsforecast.py +12 -12
  43. autogluon/timeseries/models/multi_window/multi_window_model.py +38 -23
  44. autogluon/timeseries/models/registry.py +3 -4
  45. autogluon/timeseries/models/toto/_internal/backbone/attention.py +3 -4
  46. autogluon/timeseries/models/toto/_internal/backbone/backbone.py +6 -6
  47. autogluon/timeseries/models/toto/_internal/backbone/rope.py +4 -9
  48. autogluon/timeseries/models/toto/_internal/backbone/rotary_embedding_torch.py +342 -0
  49. autogluon/timeseries/models/toto/_internal/backbone/scaler.py +2 -3
  50. autogluon/timeseries/models/toto/_internal/backbone/transformer.py +10 -10
  51. autogluon/timeseries/models/toto/_internal/dataset.py +2 -2
  52. autogluon/timeseries/models/toto/_internal/forecaster.py +8 -8
  53. autogluon/timeseries/models/toto/dataloader.py +4 -4
  54. autogluon/timeseries/models/toto/hf_pretrained_model.py +97 -16
  55. autogluon/timeseries/models/toto/model.py +30 -17
  56. autogluon/timeseries/predictor.py +517 -129
  57. autogluon/timeseries/regressor.py +18 -23
  58. autogluon/timeseries/splitter.py +2 -2
  59. autogluon/timeseries/trainer/ensemble_composer.py +323 -129
  60. autogluon/timeseries/trainer/model_set_builder.py +9 -9
  61. autogluon/timeseries/trainer/prediction_cache.py +16 -16
  62. autogluon/timeseries/trainer/trainer.py +235 -144
  63. autogluon/timeseries/trainer/utils.py +3 -4
  64. autogluon/timeseries/transforms/covariate_scaler.py +7 -7
  65. autogluon/timeseries/transforms/target_scaler.py +8 -8
  66. autogluon/timeseries/utils/constants.py +10 -0
  67. autogluon/timeseries/utils/datetime/lags.py +1 -3
  68. autogluon/timeseries/utils/datetime/seasonality.py +1 -3
  69. autogluon/timeseries/utils/features.py +22 -9
  70. autogluon/timeseries/utils/forecast.py +1 -2
  71. autogluon/timeseries/utils/timer.py +173 -0
  72. autogluon/timeseries/version.py +1 -1
  73. {autogluon_timeseries-1.4.1b20251115.dist-info → autogluon_timeseries-1.4.1b20251218.dist-info}/METADATA +23 -21
  74. autogluon_timeseries-1.4.1b20251218.dist-info/RECORD +103 -0
  75. autogluon_timeseries-1.4.1b20251115.dist-info/RECORD +0 -96
  76. /autogluon.timeseries-1.4.1b20251115-py3.9-nspkg.pth → /autogluon.timeseries-1.4.1b20251218-py3.11-nspkg.pth +0 -0
  77. {autogluon_timeseries-1.4.1b20251115.dist-info → autogluon_timeseries-1.4.1b20251218.dist-info}/WHEEL +0 -0
  78. {autogluon_timeseries-1.4.1b20251115.dist-info → autogluon_timeseries-1.4.1b20251218.dist-info}/licenses/LICENSE +0 -0
  79. {autogluon_timeseries-1.4.1b20251115.dist-info → autogluon_timeseries-1.4.1b20251218.dist-info}/licenses/NOTICE +0 -0
  80. {autogluon_timeseries-1.4.1b20251115.dist-info → autogluon_timeseries-1.4.1b20251218.dist-info}/namespace_packages.txt +0 -0
  81. {autogluon_timeseries-1.4.1b20251115.dist-info → autogluon_timeseries-1.4.1b20251218.dist-info}/top_level.txt +0 -0
  82. {autogluon_timeseries-1.4.1b20251115.dist-info → autogluon_timeseries-1.4.1b20251218.dist-info}/zip-safe +0 -0
@@ -5,7 +5,7 @@ import os
5
5
  import pprint
6
6
  import time
7
7
  from pathlib import Path
8
- from typing import Any, Literal, Optional, Type, Union, cast
8
+ from typing import Any, Literal, Type, cast, overload
9
9
 
10
10
  import numpy as np
11
11
  import pandas as pd
@@ -66,7 +66,7 @@ class TimeSeriesPredictor:
66
66
 
67
67
  If ``freq`` is provided when creating the predictor, all data passed to the predictor will be automatically
68
68
  resampled at this frequency.
69
- eval_metric : Union[str, TimeSeriesScorer], default = "WQL"
69
+ eval_metric : str | TimeSeriesScorer, default = "WQL"
70
70
  Metric by which predictions will be ultimately evaluated on future test data. AutoGluon tunes hyperparameters
71
71
  in order to improve this metric on validation data, and ranks models (on validation data) according to this
72
72
  metric.
@@ -124,7 +124,7 @@ class TimeSeriesPredictor:
124
124
  debug messages from AutoGluon and all logging in dependencies (GluonTS, PyTorch Lightning, AutoGluon-Tabular, etc.)
125
125
  log_to_file: bool, default = True
126
126
  Whether to save the logs into a file for later reference
127
- log_file_path: Union[str, Path], default = "auto"
127
+ log_file_path: str | Path, default = "auto"
128
128
  File path to save the logs.
129
129
  If auto, logs will be saved under ``predictor_path/logs/predictor_log.txt``.
130
130
  Will be ignored if ``log_to_file`` is set to False
@@ -145,20 +145,20 @@ class TimeSeriesPredictor:
145
145
 
146
146
  def __init__(
147
147
  self,
148
- target: Optional[str] = None,
149
- known_covariates_names: Optional[list[str]] = None,
148
+ target: str | None = None,
149
+ known_covariates_names: list[str] | None = None,
150
150
  prediction_length: int = 1,
151
- freq: Optional[str] = None,
152
- eval_metric: Union[str, TimeSeriesScorer, None] = None,
153
- eval_metric_seasonal_period: Optional[int] = None,
154
- horizon_weight: Optional[list[float]] = None,
155
- path: Optional[Union[str, Path]] = None,
151
+ freq: str | None = None,
152
+ eval_metric: str | TimeSeriesScorer | None = None,
153
+ eval_metric_seasonal_period: int | None = None,
154
+ horizon_weight: list[float] | None = None,
155
+ path: str | Path | None = None,
156
156
  verbosity: int = 2,
157
157
  log_to_file: bool = True,
158
- log_file_path: Union[str, Path] = "auto",
159
- quantile_levels: Optional[list[float]] = None,
158
+ log_file_path: str | Path = "auto",
159
+ quantile_levels: list[float] | None = None,
160
160
  cache_predictions: bool = True,
161
- label: Optional[str] = None,
161
+ label: str | None = None,
162
162
  **kwargs,
163
163
  ):
164
164
  self.verbosity = verbosity
@@ -228,7 +228,16 @@ class TimeSeriesPredictor:
228
228
  def _trainer(self) -> TimeSeriesTrainer:
229
229
  return self._learner.load_trainer() # noqa
230
230
 
231
- def _setup_log_to_file(self, log_to_file: bool, log_file_path: Union[str, Path]) -> None:
231
+ @property
232
+ def is_fit(self) -> bool:
233
+ return self._learner.is_fit
234
+
235
+ def _assert_is_fit(self, method_name: str) -> None:
236
+ """Check if predictor is fit and raise AssertionError with informative message if not."""
237
+ if not self.is_fit:
238
+ raise AssertionError(f"Predictor is not fit. Call `.fit` before calling `.{method_name}`. ")
239
+
240
+ def _setup_log_to_file(self, log_to_file: bool, log_file_path: str | Path) -> None:
232
241
  if log_to_file:
233
242
  if log_file_path == "auto":
234
243
  log_file_path = os.path.join(self.path, "logs", self._predictor_log_file_name)
@@ -238,7 +247,7 @@ class TimeSeriesPredictor:
238
247
 
239
248
  def _to_data_frame(
240
249
  self,
241
- data: Union[TimeSeriesDataFrame, pd.DataFrame, Path, str],
250
+ data: TimeSeriesDataFrame | pd.DataFrame | Path | str,
242
251
  name: str = "data",
243
252
  ) -> TimeSeriesDataFrame:
244
253
  if isinstance(data, TimeSeriesDataFrame):
@@ -259,7 +268,7 @@ class TimeSeriesPredictor:
259
268
 
260
269
  def _check_and_prepare_data_frame(
261
270
  self,
262
- data: Union[TimeSeriesDataFrame, pd.DataFrame, Path, str],
271
+ data: TimeSeriesDataFrame | pd.DataFrame | Path | str,
263
272
  name: str = "data",
264
273
  ) -> TimeSeriesDataFrame:
265
274
  """Ensure that TimeSeriesDataFrame has a sorted index and a valid frequency.
@@ -268,7 +277,7 @@ class TimeSeriesPredictor:
268
277
 
269
278
  Parameters
270
279
  ----------
271
- data : Union[TimeSeriesDataFrame, pd.DataFrame, Path, str]
280
+ data : TimeSeriesDataFrame | pd.DataFrame | Path | str
272
281
  Data as a dataframe or path to file storing the data.
273
282
  name : str
274
283
  Name of the data that will be used in log messages (e.g., 'train_data', 'tuning_data', or 'data').
@@ -311,7 +320,7 @@ class TimeSeriesPredictor:
311
320
  return df
312
321
 
313
322
  def _check_and_prepare_data_frame_for_evaluation(
314
- self, data: TimeSeriesDataFrame, cutoff: Optional[int] = None, name: str = "data"
323
+ self, data: TimeSeriesDataFrame, cutoff: int | None = None, name: str = "data"
315
324
  ) -> TimeSeriesDataFrame:
316
325
  """
317
326
  Make sure that provided evaluation data includes both historical and future time series values.
@@ -351,36 +360,10 @@ class TimeSeriesPredictor:
351
360
  f"Median time series length is {median_length:.0f} (min={min_length}, max={max_length}). "
352
361
  )
353
362
 
354
- def _reduce_num_val_windows_if_necessary(
355
- self,
356
- train_data: TimeSeriesDataFrame,
357
- original_num_val_windows: int,
358
- val_step_size: int,
359
- ) -> int:
360
- """Adjust num_val_windows based on the length of time series in train_data.
361
-
362
- Chooses num_val_windows such that TS with median length is long enough to perform num_val_windows validations
363
- (at least 1, at most `original_num_val_windows`).
364
-
365
- In other words, find largest `num_val_windows` that satisfies
366
- median_length >= min_train_length + prediction_length + (num_val_windows - 1) * val_step_size
367
- """
368
- median_length = train_data.num_timesteps_per_item().median()
369
- num_val_windows_for_median_ts = int(
370
- (median_length - self._min_train_length - self.prediction_length) // val_step_size + 1
371
- )
372
- new_num_val_windows = min(original_num_val_windows, max(1, num_val_windows_for_median_ts))
373
- if new_num_val_windows < original_num_val_windows:
374
- logger.warning(
375
- f"Time series in train_data are too short for chosen num_val_windows={original_num_val_windows}. "
376
- f"Reducing num_val_windows to {new_num_val_windows}."
377
- )
378
- return new_num_val_windows
379
-
380
363
  def _filter_useless_train_data(
381
364
  self,
382
365
  train_data: TimeSeriesDataFrame,
383
- num_val_windows: int,
366
+ num_val_windows: tuple[int, ...],
384
367
  val_step_size: int,
385
368
  ) -> TimeSeriesDataFrame:
386
369
  """Remove time series from train_data that either contain all NaNs or are too short for chosen settings.
@@ -391,7 +374,8 @@ class TimeSeriesPredictor:
391
374
  In other words, this method removes from train_data all time series with only NaN values or length less than
392
375
  min_train_length + prediction_length + (num_val_windows - 1) * val_step_size
393
376
  """
394
- min_length = self._min_train_length + self.prediction_length + (num_val_windows - 1) * val_step_size
377
+ total_num_val_windows = sum(num_val_windows)
378
+ min_length = self._min_train_length + self.prediction_length + (total_num_val_windows - 1) * val_step_size
395
379
  train_lengths = train_data.num_timesteps_per_item()
396
380
  too_short_items = train_lengths.index[train_lengths < min_length]
397
381
 
@@ -422,27 +406,28 @@ class TimeSeriesPredictor:
422
406
  @apply_presets(get_predictor_presets())
423
407
  def fit(
424
408
  self,
425
- train_data: Union[TimeSeriesDataFrame, pd.DataFrame, Path, str],
426
- tuning_data: Optional[Union[TimeSeriesDataFrame, pd.DataFrame, Path, str]] = None,
427
- time_limit: Optional[int] = None,
428
- presets: Optional[str] = None,
429
- hyperparameters: Optional[Union[str, dict[Union[str, Type], Any]]] = None,
430
- hyperparameter_tune_kwargs: Optional[Union[str, dict]] = None,
431
- excluded_model_types: Optional[list[str]] = None,
432
- num_val_windows: int = 1,
433
- val_step_size: Optional[int] = None,
434
- refit_every_n_windows: Optional[int] = 1,
409
+ train_data: TimeSeriesDataFrame | pd.DataFrame | Path | str,
410
+ tuning_data: TimeSeriesDataFrame | pd.DataFrame | Path | str | None = None,
411
+ time_limit: int | None = None,
412
+ presets: str | None = None,
413
+ hyperparameters: str | dict[str | Type, Any] | None = None,
414
+ hyperparameter_tune_kwargs: str | dict | None = None,
415
+ excluded_model_types: list[str] | None = None,
416
+ ensemble_hyperparameters: dict[str, Any] | list[dict[str, Any]] | None = None,
417
+ num_val_windows: int | tuple[int, ...] | Literal["auto"] = 1,
418
+ val_step_size: int | None = None,
419
+ refit_every_n_windows: int | None | Literal["auto"] = 1,
435
420
  refit_full: bool = False,
436
421
  enable_ensemble: bool = True,
437
422
  skip_model_selection: bool = False,
438
- random_seed: Optional[int] = 123,
439
- verbosity: Optional[int] = None,
423
+ random_seed: int | None = 123,
424
+ verbosity: int | None = None,
440
425
  ) -> "TimeSeriesPredictor":
441
426
  """Fit probabilistic forecasting models to the given time series dataset.
442
427
 
443
428
  Parameters
444
429
  ----------
445
- train_data : Union[TimeSeriesDataFrame, pd.DataFrame, Path, str]
430
+ train_data : TimeSeriesDataFrame | pd.DataFrame | Path | str
446
431
  Training data in the :class:`~autogluon.timeseries.TimeSeriesDataFrame` format.
447
432
 
448
433
  Time series with length ``<= (num_val_windows + 1) * prediction_length`` will be ignored during training.
@@ -468,7 +453,7 @@ class TimeSeriesPredictor:
468
453
 
469
454
  If provided data is a ``pandas.DataFrame``, AutoGluon will attempt to convert it to a ``TimeSeriesDataFrame``.
470
455
  If a ``str`` or a ``Path`` is provided, AutoGluon will attempt to load this file.
471
- tuning_data : Union[TimeSeriesDataFrame, pd.DataFrame, Path, str], optional
456
+ tuning_data : TimeSeriesDataFrame | pd.DataFrame | Path | str, optional
472
457
  Data reserved for model selection and hyperparameter tuning, rather than training individual models. Also
473
458
  used to compute the validation scores. Note that only the last ``prediction_length`` time steps of each
474
459
  time series are used for computing the validation score.
@@ -610,13 +595,39 @@ class TimeSeriesPredictor:
610
595
  presets="high_quality",
611
596
  excluded_model_types=["DeepAR"],
612
597
  )
613
- num_val_windows : int, default = 1
598
+ ensemble_hyperparameters : dict or list of dict, optional
599
+ Hyperparameters for ensemble models. Can be a single dict for one ensemble layer, or a list of dicts
600
+ for multiple ensemble layers (multi-layer stacking).
601
+
602
+ For single-layer ensembling (default)::
603
+
604
+ predictor.fit(
605
+ ...,
606
+ ensemble_hyperparameters={"WeightedEnsemble": {"ensemble_size": 10}},
607
+ )
608
+
609
+ For multi-layer ensembling, provide a list where each element configures one ensemble layer::
610
+
611
+ predictor.fit(
612
+ ...,
613
+ num_val_windows=(2, 3),
614
+ ensemble_hyperparameters=[
615
+ {"WeightedEnsemble": {"ensemble_size": 5}, "SimpleAverageEnsemble": {}}, # Layer 1
616
+ {"PerformanceWeightedEnsemble": {}}, # Layer 2
617
+ ],
618
+ )
619
+
620
+ When using multi-layer ensembling, ``num_val_windows`` must be a tuple of integers, and ``len(ensemble_hyperparameters)`` must match ``len(num_val_windows)``.
621
+ num_val_windows : int | tuple[int, ...] | "auto", default = 1
614
622
  Number of backtests done on ``train_data`` for each trained model to estimate the validation performance.
615
- If ``num_val_windows > 1`` is provided, this value may be automatically reduced to ensure that the majority
616
- of time series in ``train_data`` are long enough for the chosen number of backtests.
623
+ This parameter is also used to control multi-layer ensembling.
617
624
 
618
- Increasing this parameter increases the training time roughly by a factor of ``num_val_windows // refit_every_n_windows``.
619
- See ``refit_every_n_windows`` and ``val_step_size`` for details.
625
+ If set to ``"auto"``, the value will be determined automatically based on dataset properties (number of
626
+ time series and median time series length).
627
+
628
+ Increasing this parameter increases the training time roughly by a factor of
629
+ ``num_val_windows // refit_every_n_windows``. See ``refit_every_n_windows`` and ``val_step_size`` for
630
+ details.
620
631
 
621
632
  For example, for ``prediction_length=2``, ``num_val_windows=3`` and ``val_step_size=1`` the folds are::
622
633
 
@@ -627,17 +638,41 @@ class TimeSeriesPredictor:
627
638
 
628
639
  where ``x`` are the train time steps and ``y`` are the validation time steps.
629
640
 
630
- This argument has no effect if ``tuning_data`` is provided.
641
+ This parameter can also be used to control how many of the backtesting windows are reserved for training
642
+ multiple layers of ensemble models. By default, AutoGluon-TimeSeries uses only a single layer of ensembles
643
+ trained on the backtest windows specified by the ``num_val_windows`` parameter. However, the
644
+ ``ensemble_hyperparameters`` argument can be used to specify multiple layers of ensembles. In this case,
645
+ a tuple of integers can be provided in ``num_val_windows`` to control how many of the backtesting windows
646
+ will be used to train which ensemble layers.
647
+
648
+ For example, if ``len(ensemble_hyperparameters) == 2``, a 2-tuple ``num_val_windows=(2, 3)`` is analogous
649
+ to ``num_val_windows=5``, except the first layer of ensemble models will be trained on the first two
650
+ backtest windows, and the second layer will be trained on the latter three. Validation scores of all models
651
+ will be computed on the last three windows.
652
+
653
+ If ``len(ensemble_hyperparameters) == 1``, then ``num_val_windows=(5,)`` has the same effect as
654
+ ``num_val_windows=5``.
655
+
656
+ If ``tuning_data`` is provided and ``len(ensemble_hyperparameters) == 1``, then this parameter is ignored.
657
+ Validation and ensemble training will be performed on ``tuning_data``.
658
+
659
+ If ``tuning_data`` is provided and ``len(ensemble_hyperparameters) > 1``, then this method expects that
660
+ ``len(num_val_windows) > 1``. In this case, the last element of ``num_val_windows`` will be ignored. The
661
+ last layer of ensemble training will be performed on ``tuning_data``. Validation scores will likewise be
662
+ computed on ``tuning_data``.
663
+
631
664
  val_step_size : int or None, default = None
632
665
  Step size between consecutive validation windows. If set to ``None``, defaults to ``prediction_length``
633
666
  provided when creating the predictor.
634
667
 
635
- This argument has no effect if ``tuning_data`` is provided.
636
- refit_every_n_windows: int or None, default = 1
668
+ If ``tuning_data`` is provided and ``len(ensemble_hyperparameters) == 1``, then this parameter is ignored.
669
+ refit_every_n_windows: int | None | "auto", default = 1
637
670
  When performing cross validation, each model will be retrained every ``refit_every_n_windows`` validation
638
671
  windows, where the number of validation windows is specified by ``num_val_windows``. Note that in the
639
672
  default setting where ``num_val_windows=1``, this argument has no effect.
640
673
 
674
+ If set to ``"auto"``, the value will be determined automatically based on ``num_val_windows``.
675
+
641
676
  If set to ``None``, models will only be fit once for the first (oldest) validation window. By default,
642
677
  ``refit_every_n_windows=1``, i.e., all models will be refit for each validation window.
643
678
  refit_full : bool, default = False
@@ -660,8 +695,10 @@ class TimeSeriesPredictor:
660
695
 
661
696
  """
662
697
  time_start = time.time()
663
- if self._learner.is_fit:
664
- raise AssertionError("Predictor is already fit! To fit additional models create a new `Predictor`.")
698
+ if self.is_fit:
699
+ raise AssertionError(
700
+ "Predictor is already fit! To fit additional models create a new `TimeSeriesPredictor`."
701
+ )
665
702
 
666
703
  if verbosity is None:
667
704
  verbosity = self.verbosity
@@ -707,36 +744,57 @@ class TimeSeriesPredictor:
707
744
 
708
745
  if val_step_size is None:
709
746
  val_step_size = self.prediction_length
747
+ median_timeseries_length = int(train_data.num_timesteps_per_item().median())
710
748
 
711
- if num_val_windows > 0:
712
- num_val_windows = self._reduce_num_val_windows_if_necessary(
713
- train_data, original_num_val_windows=num_val_windows, val_step_size=val_step_size
749
+ # Early validation: check length mismatch when num_val_windows is explicitly provided
750
+ if num_val_windows != "auto" and ensemble_hyperparameters is not None:
751
+ num_layers = len(ensemble_hyperparameters) if isinstance(ensemble_hyperparameters, list) else 1
752
+ num_windows_tuple = num_val_windows if isinstance(num_val_windows, tuple) else (num_val_windows,)
753
+ if len(num_windows_tuple) != num_layers:
754
+ raise ValueError(
755
+ f"Length mismatch: num_val_windows has {len(num_windows_tuple)} element(s) but "
756
+ f"ensemble_hyperparameters has {num_layers} layer(s). These must match when num_val_windows "
757
+ f"is explicitly provided. Use num_val_windows='auto' to automatically determine the number of windows."
758
+ )
759
+
760
+ if num_val_windows == "auto":
761
+ num_val_windows = self._recommend_num_val_windows_auto(
762
+ median_timeseries_length=median_timeseries_length,
763
+ val_step_size=val_step_size,
764
+ num_items=train_data.num_items,
765
+ ensemble_hyperparameters=ensemble_hyperparameters,
714
766
  )
767
+ logger.info(f"Automatically setting num_val_windows={num_val_windows} based on dataset properties")
768
+
769
+ num_val_windows, ensemble_hyperparameters = self._validate_and_normalize_validation_and_ensemble_inputs(
770
+ num_val_windows=num_val_windows,
771
+ ensemble_hyperparameters=ensemble_hyperparameters,
772
+ val_step_size=val_step_size,
773
+ median_timeseries_length=median_timeseries_length,
774
+ tuning_data_provided=tuning_data is not None,
775
+ )
715
776
 
716
777
  if tuning_data is not None:
717
778
  tuning_data = self._check_and_prepare_data_frame(tuning_data, name="tuning_data")
718
779
  tuning_data = self._check_and_prepare_data_frame_for_evaluation(tuning_data, name="tuning_data")
719
780
  logger.info(f"Provided tuning_data has {self._get_dataset_stats(tuning_data)}")
720
- # TODO: Use num_val_windows to perform multi-window backtests on tuning_data
721
- if num_val_windows > 0:
722
- logger.warning(
723
- "\tSetting num_val_windows = 0 (disabling backtesting on train_data) because tuning_data is provided."
724
- )
725
- num_val_windows = 0
726
781
 
727
- if num_val_windows == 0 and tuning_data is None:
728
- raise ValueError("Please set num_val_windows >= 1 or provide custom tuning_data")
782
+ if refit_every_n_windows == "auto":
783
+ refit_every_n_windows = self._recommend_refit_every_n_windows_auto(num_val_windows)
784
+ logger.info(
785
+ f"Automatically setting refit_every_n_windows={refit_every_n_windows} based on num_val_windows"
786
+ )
729
787
 
730
- if num_val_windows <= 1 and refit_every_n_windows is not None and refit_every_n_windows > 1:
788
+ if sum(num_val_windows) <= 1 and refit_every_n_windows is not None and refit_every_n_windows > 1:
731
789
  logger.warning(
732
- f"\trefit_every_n_windows provided as {refit_every_n_windows} but num_val_windows is set to {num_val_windows}."
733
- " Refit_every_n_windows will have no effect."
790
+ f"\trefit_every_n_windows provided as {refit_every_n_windows} but num_val_windows is set to "
791
+ f"{num_val_windows}. refit_every_n_windows will have no effect."
734
792
  )
735
793
 
736
794
  if not skip_model_selection:
737
- train_data = self._filter_useless_train_data(
738
- train_data, num_val_windows=num_val_windows, val_step_size=val_step_size
739
- )
795
+ # When tuning_data is provided, ignore the last element of num_val_windows for filtering purposes
796
+ filter_num_val_windows = num_val_windows[:-1] if tuning_data is not None else num_val_windows
797
+ train_data = self._filter_useless_train_data(train_data, filter_num_val_windows, val_step_size)
740
798
 
741
799
  time_left = None if time_limit is None else time_limit - (time.time() - time_start)
742
800
  self._learner.fit(
@@ -745,6 +803,7 @@ class TimeSeriesPredictor:
745
803
  val_data=tuning_data,
746
804
  hyperparameter_tune_kwargs=hyperparameter_tune_kwargs,
747
805
  excluded_model_types=excluded_model_types,
806
+ ensemble_hyperparameters=ensemble_hyperparameters,
748
807
  time_limit=time_left,
749
808
  verbosity=verbosity,
750
809
  num_val_windows=num_val_windows,
@@ -763,23 +822,152 @@ class TimeSeriesPredictor:
763
822
  self.save()
764
823
  return self
765
824
 
825
+ def _recommend_num_val_windows_auto(
826
+ self,
827
+ num_items: int,
828
+ median_timeseries_length: int,
829
+ val_step_size: int,
830
+ ensemble_hyperparameters: dict[str, Any] | list[dict[str, Any]] | None = None,
831
+ ) -> tuple[int, ...]:
832
+ if num_items < 20:
833
+ recommended_windows = 5
834
+ elif num_items < 100:
835
+ recommended_windows = 3
836
+ else:
837
+ recommended_windows = 2
838
+
839
+ min_train_length = max(2 * self.prediction_length + 1, 10)
840
+ max_windows = int((median_timeseries_length - min_train_length - self.prediction_length) // val_step_size + 1)
841
+ total_windows = min(recommended_windows, max(1, max_windows))
842
+
843
+ num_layers = len(ensemble_hyperparameters) if isinstance(ensemble_hyperparameters, list) else 1
844
+ if total_windows >= num_layers:
845
+ # Distribute windows: most to first layer, 1 to each remaining layer
846
+ return (total_windows - num_layers + 1,) + (1,) * (num_layers - 1)
847
+ else:
848
+ # Insufficient windows: return tuple matching num_layers, will be reduced downstream
849
+ return (1,) * num_layers
850
+
851
+ def _recommend_refit_every_n_windows_auto(self, num_val_windows: tuple[int, ...]) -> int:
852
+ # Simple mapping for total_windows -> refit_ever_n_windows: 1 -> 1, 2 -> 1, 3 -> 2, 4 -> 2, 5 -> 2
853
+ total_windows = sum(num_val_windows)
854
+ return int(round(total_windows**0.5))
855
+
856
+ def _validate_and_normalize_validation_and_ensemble_inputs(
857
+ self,
858
+ num_val_windows: int | tuple[int, ...],
859
+ ensemble_hyperparameters: dict[str, Any] | list[dict[str, Any]] | None,
860
+ val_step_size: int,
861
+ median_timeseries_length: float,
862
+ tuning_data_provided: bool,
863
+ ) -> tuple[tuple[int, ...], list[dict[str, Any]] | None]:
864
+ """Validate and normalize num_val_windows and ensemble_hyperparameters for multi-layer ensembling."""
865
+ if ensemble_hyperparameters is not None and isinstance(ensemble_hyperparameters, dict):
866
+ ensemble_hyperparameters = [ensemble_hyperparameters]
867
+
868
+ num_val_windows = self._normalize_num_val_windows_input(num_val_windows, tuning_data_provided)
869
+ num_val_windows = self._reduce_num_val_windows_if_necessary(
870
+ num_val_windows, val_step_size, median_timeseries_length, tuning_data_provided
871
+ )
872
+
873
+ if ensemble_hyperparameters is not None and len(num_val_windows) < len(ensemble_hyperparameters):
874
+ logger.warning(
875
+ f"Time series too short: reducing ensemble layers from {len(ensemble_hyperparameters)} to "
876
+ f"{len(num_val_windows)}. Only the first {len(num_val_windows)} ensemble layer(s) will be trained."
877
+ )
878
+ ensemble_hyperparameters = ensemble_hyperparameters[: len(num_val_windows)]
879
+
880
+ return num_val_windows, ensemble_hyperparameters
881
+
882
+ def _normalize_num_val_windows_input(
883
+ self,
884
+ num_val_windows: int | tuple[int, ...],
885
+ tuning_data_provided: bool,
886
+ ) -> tuple[int, ...]:
887
+ if isinstance(num_val_windows, int):
888
+ num_val_windows = (num_val_windows,)
889
+ if not isinstance(num_val_windows, tuple):
890
+ raise TypeError(f"num_val_windows must be int or tuple[int, ...], got {type(num_val_windows)}")
891
+ if len(num_val_windows) == 0:
892
+ raise ValueError("num_val_windows tuple cannot be empty")
893
+ if tuning_data_provided:
894
+ num_val_windows = num_val_windows[:-1] + (1,)
895
+ logger.warning(
896
+ f"\tTuning data is provided. Setting num_val_windows = {num_val_windows}. Validation scores will"
897
+ " be computed on a single window of tuning_data."
898
+ )
899
+ if not all(isinstance(n, int) and n > 0 for n in num_val_windows):
900
+ raise ValueError("All elements of num_val_windows must be positive integers.")
901
+ return num_val_windows
902
+
903
+ def _reduce_num_val_windows_if_necessary(
904
+ self,
905
+ num_val_windows: tuple[int, ...],
906
+ val_step_size: int,
907
+ median_time_series_length: float,
908
+ tuning_data_provided: bool,
909
+ ) -> tuple[int, ...]:
910
+ """Adjust num_val_windows based on the length of time series in train_data.
911
+
912
+ Chooses num_val_windows such that TS with median length is long enough to perform num_val_windows validations
913
+ (at least 1, at most `original_num_val_windows`).
914
+
915
+ In other words, find largest `num_val_windows` that satisfies
916
+ median_length >= min_train_length + prediction_length + (num_val_windows - 1) * val_step_size
917
+
918
+ If tuning_data is provided, the last element of `num_val_windows` is ignored when computing the number of
919
+ requested validation windows.
920
+ """
921
+ num_val_windows_for_median_ts = int(
922
+ (median_time_series_length - self._min_train_length - self.prediction_length) // val_step_size + 1
923
+ )
924
+ max_allowed = max(1, num_val_windows_for_median_ts)
925
+ total_requested = sum(num_val_windows) if not tuning_data_provided else sum(num_val_windows[:-1])
926
+
927
+ if max_allowed >= total_requested:
928
+ return num_val_windows
929
+
930
+ logger.warning(
931
+ f"Time series in train_data are too short for chosen num_val_windows={num_val_windows}. "
932
+ f"Reducing num_val_windows to {max_allowed} total windows."
933
+ )
934
+
935
+ result = list(num_val_windows)
936
+
937
+ # Starting from the last group of windows, reduce number of windows in each group by 1,
938
+ # until sum(num_val_windows) <= max_allowed is satisfied.
939
+ for i in range(len(result) - 1, -1, -1):
940
+ while result[i] > 1 and sum(result) > max_allowed:
941
+ result[i] -= 1
942
+ if sum(result) <= max_allowed:
943
+ break
944
+
945
+ # It is possible that the above for loop reduced the number of windows in each group to 1
946
+ # (i.e. result = [1] * len(num_val_windows)), but still sum(result) > max_allowed. In this
947
+ # case we set result = [1] * max_allowed
948
+ if sum(result) > max_allowed:
949
+ result = [1] * max_allowed
950
+
951
+ return tuple(result)
952
+
766
953
  def model_names(self) -> list[str]:
767
954
  """Returns the list of model names trained by this predictor object."""
955
+ self._assert_is_fit("model_names")
768
956
  return self._trainer.get_model_names()
769
957
 
770
958
  def predict(
771
959
  self,
772
- data: Union[TimeSeriesDataFrame, pd.DataFrame, Path, str],
773
- known_covariates: Optional[Union[TimeSeriesDataFrame, pd.DataFrame, Path, str]] = None,
774
- model: Optional[str] = None,
960
+ data: TimeSeriesDataFrame | pd.DataFrame | Path | str,
961
+ known_covariates: TimeSeriesDataFrame | pd.DataFrame | Path | str | None = None,
962
+ model: str | None = None,
775
963
  use_cache: bool = True,
776
- random_seed: Optional[int] = 123,
964
+ random_seed: int | None = 123,
777
965
  ) -> TimeSeriesDataFrame:
778
966
  """Return quantile and mean forecasts for the given dataset, starting from the end of each time series.
779
967
 
780
968
  Parameters
781
969
  ----------
782
- data : Union[TimeSeriesDataFrame, pd.DataFrame, Path, str]
970
+ data : TimeSeriesDataFrame | pd.DataFrame | Path | str
783
971
  Historical time series data for which the forecast needs to be made.
784
972
 
785
973
  The names and dtypes of columns and static features in ``data`` must match the ``train_data`` used to train
@@ -787,7 +975,7 @@ class TimeSeriesPredictor:
787
975
 
788
976
  If provided data is a ``pandas.DataFrame``, AutoGluon will attempt to convert it to a ``TimeSeriesDataFrame``.
789
977
  If a ``str`` or a ``Path`` is provided, AutoGluon will attempt to load this file.
790
- known_covariates : Union[TimeSeriesDataFrame, pd.DataFrame, Path, str], optional
978
+ known_covariates : TimeSeriesDataFrame | pd.DataFrame | Path | str, optional
791
979
  If ``known_covariates_names`` were specified when creating the predictor, it is necessary to provide the
792
980
  values of the known covariates for each time series during the forecast horizon. Specifically:
793
981
 
@@ -837,6 +1025,7 @@ class TimeSeriesPredictor:
837
1025
  B 2020-03-04 17.1
838
1026
  2020-03-05 8.3
839
1027
  """
1028
+ self._assert_is_fit("predict")
840
1029
  # Save original item_id order to return predictions in the same order as input data
841
1030
  data = self._to_data_frame(data)
842
1031
  original_item_id_order = data.item_ids
@@ -852,12 +1041,207 @@ class TimeSeriesPredictor:
852
1041
  )
853
1042
  return cast(TimeSeriesDataFrame, predictions.reindex(original_item_id_order, level=TimeSeriesDataFrame.ITEMID))
854
1043
 
1044
+ @overload
1045
+ def backtest_predictions(
1046
+ self,
1047
+ data: TimeSeriesDataFrame | None = None,
1048
+ *,
1049
+ model: str | None = None,
1050
+ num_val_windows: int | None = None,
1051
+ val_step_size: int | None = None,
1052
+ use_cache: bool = True,
1053
+ ) -> list[TimeSeriesDataFrame]: ...
1054
+
1055
+ @overload
1056
+ def backtest_predictions(
1057
+ self,
1058
+ data: TimeSeriesDataFrame | None = None,
1059
+ *,
1060
+ model: list[str],
1061
+ num_val_windows: int | None = None,
1062
+ val_step_size: int | None = None,
1063
+ use_cache: bool = True,
1064
+ ) -> dict[str, list[TimeSeriesDataFrame]]: ...
1065
+
1066
+ def backtest_predictions(
1067
+ self,
1068
+ data: TimeSeriesDataFrame | None = None,
1069
+ *,
1070
+ model: str | list[str] | None = None,
1071
+ num_val_windows: int | None = None,
1072
+ val_step_size: int | None = None,
1073
+ use_cache: bool = True,
1074
+ ) -> list[TimeSeriesDataFrame] | dict[str, list[TimeSeriesDataFrame]]:
1075
+ """Return predictions for multiple validation windows.
1076
+
1077
+ When ``data=None``, returns the predictions that were saved during training. Otherwise, generates new
1078
+ predictions by splitting ``data`` into multiple windows using an expanding window strategy.
1079
+
1080
+ The corresponding target values for each window can be obtained using
1081
+ :meth:`~autogluon.timeseries.TimeSeriesPredictor.backtest_targets`.
1082
+
1083
+ Parameters
1084
+ ----------
1085
+ data : TimeSeriesDataFrame, optional
1086
+ Time series data to generate predictions for. If ``None``, returns the predictions that were saved
1087
+ during training on ``train_data``.
1088
+
1089
+ If provided, all time series in ``data`` must have length at least
1090
+ ``prediction_length + (num_val_windows - 1) * val_step_size + 1``.
1091
+
1092
+ The names and dtypes of columns and static features in ``data`` must match the ``train_data`` used to train
1093
+ the predictor.
1094
+ model : str, list[str], or None, default = None
1095
+ Name of the model(s) to generate predictions with. By default, the best model during training
1096
+ (with highest validation score) will be used.
1097
+
1098
+ - If ``str``: Returns predictions for a single model as a list.
1099
+ - If ``list[str]``: Returns predictions for multiple models as a dict mapping model names to lists.
1100
+ - If ``None``: Uses the best model.
1101
+ num_val_windows : int, optional
1102
+ Number of validation windows to generate. If ``None``, uses the ``num_val_windows`` value from training
1103
+ configuration when ``data=None``, otherwise defaults to 1.
1104
+
1105
+ For example, with ``prediction_length=2``, ``num_val_windows=3``, and ``val_step_size=1``, the validation
1106
+ windows are::
1107
+
1108
+ |-------------------|
1109
+ | x x x x x y y - - |
1110
+ | x x x x x x y y - |
1111
+ | x x x x x x x y y |
1112
+
1113
+ where ``x`` denotes training time steps and ``y`` denotes validation time steps for each window.
1114
+ val_step_size : int, optional
1115
+ Number of time steps between the start of consecutive validation windows. If ``None``, defaults to
1116
+ ``prediction_length``.
1117
+ use_cache : bool, default = True
1118
+ If True, will attempt to use cached predictions. If False, cached predictions will be ignored.
1119
+ This argument is ignored if ``cache_predictions`` was set to False when creating the ``TimeSeriesPredictor``.
1120
+
1121
+ Returns
1122
+ -------
1123
+ list[TimeSeriesDataFrame] or dict[str, list[TimeSeriesDataFrame]]
1124
+ Predictions for each validation window.
1125
+
1126
+ - If ``model`` is a ``str`` or ``None``: Returns a list of length ``num_val_windows``, where each element
1127
+ contains the predictions for one validation window.
1128
+ - If ``model`` is a ``list[str]``: Returns a dict mapping each model name to a list of predictions for
1129
+ each validation window.
1130
+
1131
+ Examples
1132
+ --------
1133
+ Make predictions on new data with the best model
1134
+
1135
+ >>> predictor.backtest_predictions(test_data, num_val_windows=2)
1136
+
1137
+ Load validation predictions for all models that were saved during training
1138
+
1139
+ >>> predictor.backtest_predictions(model=predictor.model_names())
1140
+
1141
+ See Also
1142
+ --------
1143
+ backtest_targets
1144
+ Return target values aligned with predictions.
1145
+ evaluate
1146
+ Evaluate forecast accuracy on a hold-out set.
1147
+ predict
1148
+ Generate forecasts for future time steps.
1149
+ """
1150
+ self._assert_is_fit("backtest_predictions")
1151
+ if data is not None:
1152
+ data = self._check_and_prepare_data_frame(data)
1153
+
1154
+ if model is None:
1155
+ model_names = [self.model_best]
1156
+ elif isinstance(model, str):
1157
+ model_names = [model]
1158
+ else:
1159
+ model_names = model
1160
+
1161
+ result = self._learner.backtest_predictions(
1162
+ data=data,
1163
+ model_names=model_names,
1164
+ num_val_windows=num_val_windows,
1165
+ val_step_size=val_step_size,
1166
+ use_cache=use_cache,
1167
+ )
1168
+
1169
+ if isinstance(model, list):
1170
+ return result
1171
+ else:
1172
+ return result[model_names[0]]
1173
+
1174
+ def backtest_targets(
1175
+ self,
1176
+ data: TimeSeriesDataFrame | None = None,
1177
+ *,
1178
+ num_val_windows: int | None = None,
1179
+ val_step_size: int | None = None,
1180
+ ) -> list[TimeSeriesDataFrame]:
1181
+ """Return target values for each validation window.
1182
+
1183
+ Returns the actual target values corresponding to each validation window used in
1184
+ :meth:`~autogluon.timeseries.TimeSeriesPredictor.backtest_predictions`. The returned targets are aligned
1185
+ with the predictions, making it easy to compute custom evaluation metrics or analyze forecast errors.
1186
+
1187
+ Parameters
1188
+ ----------
1189
+ data : TimeSeriesDataFrame, optional
1190
+ Time series data to extract targets from. If ``None``, returns the targets from the validation windows
1191
+ used during training.
1192
+
1193
+ If provided, all time series in ``data`` must have length at least
1194
+ ``prediction_length + (num_val_windows - 1) * val_step_size + 1``.
1195
+
1196
+ The names and dtypes of columns and static features in ``data`` must match the ``train_data`` used to train
1197
+ the predictor.
1198
+ num_val_windows : int, optional
1199
+ Number of validation windows to extract targets for. If ``None``, uses the ``num_val_windows`` value from
1200
+ training configuration when ``data=None``, otherwise defaults to 1.
1201
+
1202
+ This should match the ``num_val_windows`` argument passed to
1203
+ :meth:`~autogluon.timeseries.TimeSeriesPredictor.backtest_predictions`.
1204
+ val_step_size : int, optional
1205
+ Number of time steps between the start of consecutive validation windows. If ``None``, defaults to
1206
+ ``prediction_length``.
1207
+
1208
+ This should match the ``val_step_size`` argument passed to
1209
+ :meth:`~autogluon.timeseries.TimeSeriesPredictor.backtest_predictions`.
1210
+
1211
+ Returns
1212
+ -------
1213
+ list[TimeSeriesDataFrame]
1214
+ Target values for each validation window. Returns a list of length ``num_val_windows``,
1215
+ where each element contains the full time series data for one validation window.
1216
+ Each dataframe includes both historical context and the last ``prediction_length`` time steps
1217
+ that represent the target values to compare against predictions.
1218
+
1219
+ The returned targets are aligned with the output of
1220
+ :meth:`~autogluon.timeseries.TimeSeriesPredictor.backtest_predictions`, so ``targets[i]`` corresponds
1221
+ to ``predictions[i]`` for the i-th validation window.
1222
+
1223
+ See Also
1224
+ --------
1225
+ backtest_predictions
1226
+ Return predictions for multiple validation windows.
1227
+ evaluate
1228
+ Evaluate forecast accuracy on a hold-out set.
1229
+ """
1230
+ self._assert_is_fit("backtest_targets")
1231
+ if data is not None:
1232
+ data = self._check_and_prepare_data_frame(data)
1233
+ return self._learner.backtest_targets(
1234
+ data=data,
1235
+ num_val_windows=num_val_windows,
1236
+ val_step_size=val_step_size,
1237
+ )
1238
+
855
1239
  def evaluate(
856
1240
  self,
857
- data: Union[TimeSeriesDataFrame, pd.DataFrame, Path, str],
858
- model: Optional[str] = None,
859
- metrics: Optional[Union[str, TimeSeriesScorer, list[Union[str, TimeSeriesScorer]]]] = None,
860
- cutoff: Optional[int] = None,
1241
+ data: TimeSeriesDataFrame | pd.DataFrame | Path | str,
1242
+ model: str | None = None,
1243
+ metrics: str | TimeSeriesScorer | list[str | TimeSeriesScorer] | None = None,
1244
+ cutoff: int | None = None,
861
1245
  display: bool = False,
862
1246
  use_cache: bool = True,
863
1247
  ) -> dict[str, float]:
@@ -874,7 +1258,7 @@ class TimeSeriesPredictor:
874
1258
 
875
1259
  Parameters
876
1260
  ----------
877
- data : Union[TimeSeriesDataFrame, pd.DataFrame, Path, str]
1261
+ data : TimeSeriesDataFrame | pd.DataFrame | Path | str
878
1262
  The data to evaluate the best model on. If a ``cutoff`` is not provided, the last ``prediction_length``
879
1263
  time steps of each time series in ``data`` will be held out for prediction and forecast accuracy will
880
1264
  be calculated on these time steps. When a ``cutoff`` is provided, the ``-cutoff``-th to the
@@ -891,7 +1275,7 @@ class TimeSeriesPredictor:
891
1275
  model : str, optional
892
1276
  Name of the model that you would like to evaluate. By default, the best model during training
893
1277
  (with highest validation score) will be used.
894
- metrics : str, TimeSeriesScorer or list[Union[str, TimeSeriesScorer]], optional
1278
+ metrics : str, TimeSeriesScorer or list[str | TimeSeriesScorer], optional
895
1279
  Metric or a list of metrics to compute scores with. Defaults to ``self.eval_metric``. Supports both
896
1280
  metric names as strings and custom metrics based on TimeSeriesScorer.
897
1281
  cutoff : int, optional
@@ -912,7 +1296,7 @@ class TimeSeriesPredictor:
912
1296
  will have their signs flipped to obey this convention. For example, negative MAPE values will be reported.
913
1297
  To get the ``eval_metric`` score, do ``output[predictor.eval_metric.name]``.
914
1298
  """
915
-
1299
+ self._assert_is_fit("evaluate")
916
1300
  data = self._check_and_prepare_data_frame(data)
917
1301
  data = self._check_and_prepare_data_frame_for_evaluation(data, cutoff=cutoff)
918
1302
 
@@ -924,15 +1308,15 @@ class TimeSeriesPredictor:
924
1308
 
925
1309
  def feature_importance(
926
1310
  self,
927
- data: Optional[Union[TimeSeriesDataFrame, pd.DataFrame, Path, str]] = None,
928
- model: Optional[str] = None,
929
- metric: Optional[Union[str, TimeSeriesScorer]] = None,
930
- features: Optional[list[str]] = None,
931
- time_limit: Optional[float] = None,
1311
+ data: TimeSeriesDataFrame | pd.DataFrame | Path | str | None = None,
1312
+ model: str | None = None,
1313
+ metric: str | TimeSeriesScorer | None = None,
1314
+ features: list[str] | None = None,
1315
+ time_limit: float | None = None,
932
1316
  method: Literal["naive", "permutation"] = "permutation",
933
1317
  subsample_size: int = 50,
934
- num_iterations: Optional[int] = None,
935
- random_seed: Optional[int] = 123,
1318
+ num_iterations: int | None = None,
1319
+ random_seed: int | None = 123,
936
1320
  relative_scores: bool = False,
937
1321
  include_confidence_band: bool = True,
938
1322
  confidence_level: float = 0.99,
@@ -1029,6 +1413,7 @@ class TimeSeriesPredictor:
1029
1413
  'importance': The estimated feature importance score.
1030
1414
  'stddev': The standard deviation of the feature importance score. If NaN, then not enough ``num_iterations`` were used.
1031
1415
  """
1416
+ self._assert_is_fit("feature_importance")
1032
1417
  if data is not None:
1033
1418
  data = self._check_and_prepare_data_frame(data)
1034
1419
  data = self._check_and_prepare_data_frame_for_evaluation(data)
@@ -1047,7 +1432,7 @@ class TimeSeriesPredictor:
1047
1432
  include_confidence_band=include_confidence_band,
1048
1433
  confidence_level=confidence_level,
1049
1434
  )
1050
- return fi_df
1435
+ return fi_df.sort_values("importance", ascending=False)
1051
1436
 
1052
1437
  @classmethod
1053
1438
  def _load_version_file(cls, path: str) -> str:
@@ -1075,7 +1460,7 @@ class TimeSeriesPredictor:
1075
1460
  return version
1076
1461
 
1077
1462
  @classmethod
1078
- def load(cls, path: Union[str, Path], require_version_match: bool = True) -> "TimeSeriesPredictor":
1463
+ def load(cls, path: str | Path, require_version_match: bool = True) -> "TimeSeriesPredictor":
1079
1464
  """Load an existing ``TimeSeriesPredictor`` from given ``path``.
1080
1465
 
1081
1466
  .. warning::
@@ -1159,15 +1544,14 @@ class TimeSeriesPredictor:
1159
1544
  @property
1160
1545
  def model_best(self) -> str:
1161
1546
  """Returns the name of the best model from trainer."""
1547
+ self._assert_is_fit("model_best")
1162
1548
  if self._trainer.model_best is not None:
1163
1549
  models = self._trainer.get_model_names()
1164
1550
  if self._trainer.model_best in models:
1165
1551
  return self._trainer.model_best
1166
1552
  return self._trainer.get_model_best()
1167
1553
 
1168
- def persist(
1169
- self, models: Union[Literal["all", "best"], list[str]] = "best", with_ancestors: bool = True
1170
- ) -> list[str]:
1554
+ def persist(self, models: Literal["all", "best"] | list[str] = "best", with_ancestors: bool = True) -> list[str]:
1171
1555
  """Persist models in memory for reduced inference latency. This is particularly important if the models are being used for online
1172
1556
  inference where low latency is critical. If models are not persisted in memory, they are loaded from disk every time they are
1173
1557
  asked to make predictions. This is especially cumbersome for large deep learning based models which have to be loaded into
@@ -1190,6 +1574,7 @@ class TimeSeriesPredictor:
1190
1574
  list_of_models : list[str]
1191
1575
  List of persisted model names.
1192
1576
  """
1577
+ self._assert_is_fit("persist")
1193
1578
  return self._learner.persist_trainer(models=models, with_ancestors=with_ancestors)
1194
1579
 
1195
1580
  def unpersist(self) -> list[str]:
@@ -1208,10 +1593,10 @@ class TimeSeriesPredictor:
1208
1593
 
1209
1594
  def leaderboard(
1210
1595
  self,
1211
- data: Optional[Union[TimeSeriesDataFrame, pd.DataFrame, Path, str]] = None,
1212
- cutoff: Optional[int] = None,
1596
+ data: TimeSeriesDataFrame | pd.DataFrame | Path | str | None = None,
1597
+ cutoff: int | None = None,
1213
1598
  extra_info: bool = False,
1214
- extra_metrics: Optional[list[Union[str, TimeSeriesScorer]]] = None,
1599
+ extra_metrics: list[str | TimeSeriesScorer] | None = None,
1215
1600
  display: bool = False,
1216
1601
  use_cache: bool = True,
1217
1602
  **kwargs,
@@ -1236,7 +1621,7 @@ class TimeSeriesPredictor:
1236
1621
 
1237
1622
  Parameters
1238
1623
  ----------
1239
- data : Union[TimeSeriesDataFrame, pd.DataFrame, Path, str], optional
1624
+ data : TimeSeriesDataFrame | pd.DataFrame | Path | str, optional
1240
1625
  dataset used for additional evaluation. Must include both historical and future data (i.e., length of all
1241
1626
  time series in ``data`` must be at least ``prediction_length + 1``, if ``cutoff`` is not provided,
1242
1627
  ``-cutoff + 1`` otherwise).
@@ -1255,7 +1640,7 @@ class TimeSeriesPredictor:
1255
1640
  If True, the leaderboard will contain an additional column ``hyperparameters`` with the hyperparameters used
1256
1641
  by each model during training. An empty dictionary ``{}`` means that the model was trained with default
1257
1642
  hyperparameters.
1258
- extra_metrics : list[Union[str, TimeSeriesScorer]], optional
1643
+ extra_metrics : list[str | TimeSeriesScorer], optional
1259
1644
  A list of metrics to calculate scores for and include in the output DataFrame.
1260
1645
 
1261
1646
  Only valid when ``data`` is specified. The scores refer to the scores on ``data`` (same data as used to
@@ -1277,6 +1662,7 @@ class TimeSeriesPredictor:
1277
1662
  The leaderboard containing information on all models and in order of best model to worst in terms of
1278
1663
  test performance.
1279
1664
  """
1665
+ self._assert_is_fit("leaderboard")
1280
1666
  if "silent" in kwargs:
1281
1667
  # keep `silent` logic for backwards compatibility
1282
1668
  assert isinstance(kwargs["silent"], bool)
@@ -1301,12 +1687,12 @@ class TimeSeriesPredictor:
1301
1687
  print(leaderboard)
1302
1688
  return leaderboard
1303
1689
 
1304
- def make_future_data_frame(self, data: Union[TimeSeriesDataFrame, pd.DataFrame, Path, str]) -> pd.DataFrame:
1690
+ def make_future_data_frame(self, data: TimeSeriesDataFrame | pd.DataFrame | Path | str) -> pd.DataFrame:
1305
1691
  """Generate a dataframe with the ``item_id`` and ``timestamp`` values corresponding to the forecast horizon.
1306
1692
 
1307
1693
  Parameters
1308
1694
  ----------
1309
- data : Union[TimeSeriesDataFrame, pd.DataFrame, Path, str]
1695
+ data : TimeSeriesDataFrame | pd.DataFrame | Path | str
1310
1696
  Historical time series data.
1311
1697
 
1312
1698
  Returns
@@ -1354,6 +1740,7 @@ class TimeSeriesPredictor:
1354
1740
  Dict containing various detailed information. We do not recommend directly printing this dict as it may
1355
1741
  be very large.
1356
1742
  """
1743
+ self._assert_is_fit("fit_summary")
1357
1744
  # TODO: HPO-specific information currently not reported in fit_summary
1358
1745
  # TODO: Revisit after ray tune integration
1359
1746
 
@@ -1414,6 +1801,7 @@ class TimeSeriesPredictor:
1414
1801
  ``predictor.predict(data)`` is called will be the refit_full version instead of the original version of the
1415
1802
  model. Has no effect if ``model`` is not the best model.
1416
1803
  """
1804
+ self._assert_is_fit("refit_full")
1417
1805
  logger.warning(
1418
1806
  "\tWARNING: refit_full functionality for TimeSeriesPredictor is experimental "
1419
1807
  "and is not yet supported by all models."
@@ -1466,7 +1854,7 @@ class TimeSeriesPredictor:
1466
1854
  trainer = self._trainer
1467
1855
  train_data = trainer.load_train_data()
1468
1856
  val_data = trainer.load_val_data()
1469
- base_model_names = trainer.get_model_names(level=0)
1857
+ base_model_names = trainer.get_model_names(layer=0)
1470
1858
  pred_proba_dict_val: dict[str, list[TimeSeriesDataFrame]] = {
1471
1859
  model_name: trainer._get_model_oof_predictions(model_name)
1472
1860
  for model_name in base_model_names
@@ -1502,27 +1890,27 @@ class TimeSeriesPredictor:
1502
1890
 
1503
1891
  def plot(
1504
1892
  self,
1505
- data: Union[TimeSeriesDataFrame, pd.DataFrame, Path, str],
1506
- predictions: Optional[TimeSeriesDataFrame] = None,
1507
- quantile_levels: Optional[list[float]] = None,
1508
- item_ids: Optional[list[Union[str, int]]] = None,
1893
+ data: TimeSeriesDataFrame | pd.DataFrame | Path | str,
1894
+ predictions: TimeSeriesDataFrame | None = None,
1895
+ quantile_levels: list[float] | None = None,
1896
+ item_ids: list[str | int] | None = None,
1509
1897
  max_num_item_ids: int = 8,
1510
- max_history_length: Optional[int] = None,
1511
- point_forecast_column: Optional[str] = None,
1512
- matplotlib_rc_params: Optional[dict] = None,
1898
+ max_history_length: int | None = None,
1899
+ point_forecast_column: str | None = None,
1900
+ matplotlib_rc_params: dict | None = None,
1513
1901
  ):
1514
1902
  """Plot historical time series values and the forecasts.
1515
1903
 
1516
1904
  Parameters
1517
1905
  ----------
1518
- data : Union[TimeSeriesDataFrame, pd.DataFrame, Path, str]
1906
+ data : TimeSeriesDataFrame | pd.DataFrame | Path | str
1519
1907
  Observed time series data.
1520
1908
  predictions : TimeSeriesDataFrame, optional
1521
1909
  Predictions generated by calling :meth:`~autogluon.timeseries.TimeSeriesPredictor.predict`.
1522
1910
  quantile_levels : list[float], optional
1523
1911
  Quantile levels for which to plot the prediction intervals. Defaults to lowest & highest quantile levels
1524
1912
  available in ``predictions``.
1525
- item_ids : list[Union[str, int]], optional
1913
+ item_ids : list[str | int], optional
1526
1914
  If provided, plots will only be generated for time series with these item IDs. By default (if set to
1527
1915
  ``None``), item IDs are selected randomly. In either case, plots are generated for at most
1528
1916
  ``max_num_item_ids`` time series.