autogluon.timeseries 1.4.1b20251016__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 (90) 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 +97 -86
  4. autogluon/timeseries/learner.py +70 -35
  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 +5 -5
  9. autogluon/timeseries/metrics/utils.py +4 -4
  10. autogluon/timeseries/models/__init__.py +2 -1
  11. autogluon/timeseries/models/abstract/abstract_timeseries_model.py +52 -39
  12. autogluon/timeseries/models/abstract/model_trial.py +2 -1
  13. autogluon/timeseries/models/abstract/tunable.py +8 -8
  14. autogluon/timeseries/models/autogluon_tabular/mlforecast.py +58 -62
  15. autogluon/timeseries/models/autogluon_tabular/per_step.py +26 -15
  16. autogluon/timeseries/models/autogluon_tabular/transforms.py +11 -9
  17. autogluon/timeseries/models/chronos/__init__.py +2 -1
  18. autogluon/timeseries/models/chronos/chronos2.py +395 -0
  19. autogluon/timeseries/models/chronos/model.py +126 -88
  20. autogluon/timeseries/models/chronos/{pipeline/utils.py → utils.py} +69 -37
  21. autogluon/timeseries/models/ensemble/__init__.py +36 -2
  22. autogluon/timeseries/models/ensemble/abstract.py +14 -46
  23. autogluon/timeseries/models/ensemble/array_based/__init__.py +3 -0
  24. autogluon/timeseries/models/ensemble/array_based/abstract.py +240 -0
  25. autogluon/timeseries/models/ensemble/array_based/models.py +185 -0
  26. autogluon/timeseries/models/ensemble/array_based/regressor/__init__.py +12 -0
  27. autogluon/timeseries/models/ensemble/array_based/regressor/abstract.py +88 -0
  28. autogluon/timeseries/models/ensemble/array_based/regressor/linear_stacker.py +186 -0
  29. autogluon/timeseries/models/ensemble/array_based/regressor/per_quantile_tabular.py +94 -0
  30. autogluon/timeseries/models/ensemble/array_based/regressor/tabular.py +107 -0
  31. autogluon/timeseries/models/ensemble/{greedy.py → ensemble_selection.py} +41 -61
  32. autogluon/timeseries/models/ensemble/per_item_greedy.py +172 -0
  33. autogluon/timeseries/models/ensemble/weighted/__init__.py +8 -0
  34. autogluon/timeseries/models/ensemble/weighted/abstract.py +45 -0
  35. autogluon/timeseries/models/ensemble/{basic.py → weighted/basic.py} +25 -22
  36. autogluon/timeseries/models/ensemble/weighted/greedy.py +62 -0
  37. autogluon/timeseries/models/gluonts/abstract.py +32 -31
  38. autogluon/timeseries/models/gluonts/dataset.py +11 -11
  39. autogluon/timeseries/models/gluonts/models.py +0 -7
  40. autogluon/timeseries/models/local/__init__.py +0 -7
  41. autogluon/timeseries/models/local/abstract_local_model.py +15 -18
  42. autogluon/timeseries/models/local/naive.py +2 -2
  43. autogluon/timeseries/models/local/npts.py +7 -1
  44. autogluon/timeseries/models/local/statsforecast.py +12 -12
  45. autogluon/timeseries/models/multi_window/multi_window_model.py +39 -24
  46. autogluon/timeseries/models/registry.py +3 -4
  47. autogluon/timeseries/models/toto/_internal/backbone/attention.py +3 -4
  48. autogluon/timeseries/models/toto/_internal/backbone/backbone.py +6 -6
  49. autogluon/timeseries/models/toto/_internal/backbone/rope.py +4 -9
  50. autogluon/timeseries/models/toto/_internal/backbone/rotary_embedding_torch.py +342 -0
  51. autogluon/timeseries/models/toto/_internal/backbone/scaler.py +2 -3
  52. autogluon/timeseries/models/toto/_internal/backbone/transformer.py +10 -10
  53. autogluon/timeseries/models/toto/_internal/dataset.py +2 -2
  54. autogluon/timeseries/models/toto/_internal/forecaster.py +8 -8
  55. autogluon/timeseries/models/toto/dataloader.py +4 -4
  56. autogluon/timeseries/models/toto/hf_pretrained_model.py +97 -16
  57. autogluon/timeseries/models/toto/model.py +35 -20
  58. autogluon/timeseries/predictor.py +527 -155
  59. autogluon/timeseries/regressor.py +27 -30
  60. autogluon/timeseries/splitter.py +3 -27
  61. autogluon/timeseries/trainer/ensemble_composer.py +444 -0
  62. autogluon/timeseries/trainer/model_set_builder.py +9 -9
  63. autogluon/timeseries/trainer/prediction_cache.py +16 -16
  64. autogluon/timeseries/trainer/trainer.py +300 -278
  65. autogluon/timeseries/trainer/utils.py +17 -0
  66. autogluon/timeseries/transforms/covariate_scaler.py +8 -8
  67. autogluon/timeseries/transforms/target_scaler.py +15 -15
  68. autogluon/timeseries/utils/constants.py +10 -0
  69. autogluon/timeseries/utils/datetime/lags.py +1 -3
  70. autogluon/timeseries/utils/datetime/seasonality.py +1 -3
  71. autogluon/timeseries/utils/features.py +31 -14
  72. autogluon/timeseries/utils/forecast.py +6 -7
  73. autogluon/timeseries/utils/timer.py +173 -0
  74. autogluon/timeseries/version.py +1 -1
  75. autogluon.timeseries-1.4.1b20251218-py3.11-nspkg.pth +1 -0
  76. {autogluon.timeseries-1.4.1b20251016.dist-info → autogluon_timeseries-1.4.1b20251218.dist-info}/METADATA +39 -27
  77. autogluon_timeseries-1.4.1b20251218.dist-info/RECORD +103 -0
  78. {autogluon.timeseries-1.4.1b20251016.dist-info → autogluon_timeseries-1.4.1b20251218.dist-info}/WHEEL +1 -1
  79. autogluon/timeseries/evaluator.py +0 -6
  80. autogluon/timeseries/models/chronos/pipeline/__init__.py +0 -10
  81. autogluon/timeseries/models/chronos/pipeline/base.py +0 -160
  82. autogluon/timeseries/models/chronos/pipeline/chronos.py +0 -544
  83. autogluon/timeseries/models/chronos/pipeline/chronos_bolt.py +0 -580
  84. autogluon.timeseries-1.4.1b20251016-py3.9-nspkg.pth +0 -1
  85. autogluon.timeseries-1.4.1b20251016.dist-info/RECORD +0 -90
  86. {autogluon.timeseries-1.4.1b20251016.dist-info → autogluon_timeseries-1.4.1b20251218.dist-info/licenses}/LICENSE +0 -0
  87. {autogluon.timeseries-1.4.1b20251016.dist-info → autogluon_timeseries-1.4.1b20251218.dist-info/licenses}/NOTICE +0 -0
  88. {autogluon.timeseries-1.4.1b20251016.dist-info → autogluon_timeseries-1.4.1b20251218.dist-info}/namespace_packages.txt +0 -0
  89. {autogluon.timeseries-1.4.1b20251016.dist-info → autogluon_timeseries-1.4.1b20251218.dist-info}/top_level.txt +0 -0
  90. {autogluon.timeseries-1.4.1b20251016.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
@@ -22,10 +22,9 @@ from autogluon.core.utils.loaders import load_pkl, load_str
22
22
  from autogluon.core.utils.savers import save_pkl, save_str
23
23
  from autogluon.timeseries import __version__ as current_ag_version
24
24
  from autogluon.timeseries.configs import get_predictor_presets
25
- from autogluon.timeseries.dataset.ts_dataframe import ITEMID, TimeSeriesDataFrame
25
+ from autogluon.timeseries.dataset import TimeSeriesDataFrame
26
26
  from autogluon.timeseries.learner import TimeSeriesLearner
27
27
  from autogluon.timeseries.metrics import TimeSeriesScorer, check_get_evaluation_metric
28
- from autogluon.timeseries.splitter import ExpandingWindowSplitter
29
28
  from autogluon.timeseries.trainer import TimeSeriesTrainer
30
29
  from autogluon.timeseries.utils.forecast import make_future_data_frame
31
30
 
@@ -67,7 +66,7 @@ class TimeSeriesPredictor:
67
66
 
68
67
  If ``freq`` is provided when creating the predictor, all data passed to the predictor will be automatically
69
68
  resampled at this frequency.
70
- eval_metric : Union[str, TimeSeriesScorer], default = "WQL"
69
+ eval_metric : str | TimeSeriesScorer, default = "WQL"
71
70
  Metric by which predictions will be ultimately evaluated on future test data. AutoGluon tunes hyperparameters
72
71
  in order to improve this metric on validation data, and ranks models (on validation data) according to this
73
72
  metric.
@@ -125,7 +124,7 @@ class TimeSeriesPredictor:
125
124
  debug messages from AutoGluon and all logging in dependencies (GluonTS, PyTorch Lightning, AutoGluon-Tabular, etc.)
126
125
  log_to_file: bool, default = True
127
126
  Whether to save the logs into a file for later reference
128
- log_file_path: Union[str, Path], default = "auto"
127
+ log_file_path: str | Path, default = "auto"
129
128
  File path to save the logs.
130
129
  If auto, logs will be saved under ``predictor_path/logs/predictor_log.txt``.
131
130
  Will be ignored if ``log_to_file`` is set to False
@@ -146,20 +145,20 @@ class TimeSeriesPredictor:
146
145
 
147
146
  def __init__(
148
147
  self,
149
- target: Optional[str] = None,
150
- known_covariates_names: Optional[list[str]] = None,
148
+ target: str | None = None,
149
+ known_covariates_names: list[str] | None = None,
151
150
  prediction_length: int = 1,
152
- freq: Optional[str] = None,
153
- eval_metric: Union[str, TimeSeriesScorer, None] = None,
154
- eval_metric_seasonal_period: Optional[int] = None,
155
- horizon_weight: Optional[list[float]] = None,
156
- 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,
157
156
  verbosity: int = 2,
158
157
  log_to_file: bool = True,
159
- log_file_path: Union[str, Path] = "auto",
160
- quantile_levels: Optional[list[float]] = None,
158
+ log_file_path: str | Path = "auto",
159
+ quantile_levels: list[float] | None = None,
161
160
  cache_predictions: bool = True,
162
- label: Optional[str] = None,
161
+ label: str | None = None,
163
162
  **kwargs,
164
163
  ):
165
164
  self.verbosity = verbosity
@@ -221,20 +220,6 @@ class TimeSeriesPredictor:
221
220
  ensemble_model_type=kwargs.pop("ensemble_model_type", None),
222
221
  )
223
222
 
224
- if "ignore_time_index" in kwargs:
225
- raise TypeError(
226
- "`ignore_time_index` argument to TimeSeriesPredictor.__init__() has been deprecated.\n"
227
- "If your data has irregular timestamps, please either 1) specify the desired regular frequency when "
228
- "creating the predictor as `TimeSeriesPredictor(freq=...)` or 2) manually convert timestamps to "
229
- "regular frequency with `data.convert_frequency(freq=...)`."
230
- )
231
- for k in ["learner_type", "learner_kwargs"]:
232
- if k in kwargs:
233
- val = kwargs.pop(k)
234
- logger.warning(
235
- f"Passing `{k}` to TimeSeriesPredictor has been deprecated and will be removed in v1.4. "
236
- f"The provided value {val} will be ignored."
237
- )
238
223
  if len(kwargs) > 0:
239
224
  for key in kwargs:
240
225
  raise TypeError(f"TimeSeriesPredictor.__init__() got an unexpected keyword argument '{key}'")
@@ -243,7 +228,16 @@ class TimeSeriesPredictor:
243
228
  def _trainer(self) -> TimeSeriesTrainer:
244
229
  return self._learner.load_trainer() # noqa
245
230
 
246
- 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:
247
241
  if log_to_file:
248
242
  if log_file_path == "auto":
249
243
  log_file_path = os.path.join(self.path, "logs", self._predictor_log_file_name)
@@ -253,7 +247,7 @@ class TimeSeriesPredictor:
253
247
 
254
248
  def _to_data_frame(
255
249
  self,
256
- data: Union[TimeSeriesDataFrame, pd.DataFrame, Path, str],
250
+ data: TimeSeriesDataFrame | pd.DataFrame | Path | str,
257
251
  name: str = "data",
258
252
  ) -> TimeSeriesDataFrame:
259
253
  if isinstance(data, TimeSeriesDataFrame):
@@ -274,7 +268,7 @@ class TimeSeriesPredictor:
274
268
 
275
269
  def _check_and_prepare_data_frame(
276
270
  self,
277
- data: Union[TimeSeriesDataFrame, pd.DataFrame, Path, str],
271
+ data: TimeSeriesDataFrame | pd.DataFrame | Path | str,
278
272
  name: str = "data",
279
273
  ) -> TimeSeriesDataFrame:
280
274
  """Ensure that TimeSeriesDataFrame has a sorted index and a valid frequency.
@@ -283,7 +277,7 @@ class TimeSeriesPredictor:
283
277
 
284
278
  Parameters
285
279
  ----------
286
- data : Union[TimeSeriesDataFrame, pd.DataFrame, Path, str]
280
+ data : TimeSeriesDataFrame | pd.DataFrame | Path | str
287
281
  Data as a dataframe or path to file storing the data.
288
282
  name : str
289
283
  Name of the data that will be used in log messages (e.g., 'train_data', 'tuning_data', or 'data').
@@ -326,7 +320,7 @@ class TimeSeriesPredictor:
326
320
  return df
327
321
 
328
322
  def _check_and_prepare_data_frame_for_evaluation(
329
- self, data: TimeSeriesDataFrame, cutoff: Optional[int] = None, name: str = "data"
323
+ self, data: TimeSeriesDataFrame, cutoff: int | None = None, name: str = "data"
330
324
  ) -> TimeSeriesDataFrame:
331
325
  """
332
326
  Make sure that provided evaluation data includes both historical and future time series values.
@@ -366,36 +360,10 @@ class TimeSeriesPredictor:
366
360
  f"Median time series length is {median_length:.0f} (min={min_length}, max={max_length}). "
367
361
  )
368
362
 
369
- def _reduce_num_val_windows_if_necessary(
370
- self,
371
- train_data: TimeSeriesDataFrame,
372
- original_num_val_windows: int,
373
- val_step_size: int,
374
- ) -> int:
375
- """Adjust num_val_windows based on the length of time series in train_data.
376
-
377
- Chooses num_val_windows such that TS with median length is long enough to perform num_val_windows validations
378
- (at least 1, at most `original_num_val_windows`).
379
-
380
- In other words, find largest `num_val_windows` that satisfies
381
- median_length >= min_train_length + prediction_length + (num_val_windows - 1) * val_step_size
382
- """
383
- median_length = train_data.num_timesteps_per_item().median()
384
- num_val_windows_for_median_ts = int(
385
- (median_length - self._min_train_length - self.prediction_length) // val_step_size + 1
386
- )
387
- new_num_val_windows = min(original_num_val_windows, max(1, num_val_windows_for_median_ts))
388
- if new_num_val_windows < original_num_val_windows:
389
- logger.warning(
390
- f"Time series in train_data are too short for chosen num_val_windows={original_num_val_windows}. "
391
- f"Reducing num_val_windows to {new_num_val_windows}."
392
- )
393
- return new_num_val_windows
394
-
395
363
  def _filter_useless_train_data(
396
364
  self,
397
365
  train_data: TimeSeriesDataFrame,
398
- num_val_windows: int,
366
+ num_val_windows: tuple[int, ...],
399
367
  val_step_size: int,
400
368
  ) -> TimeSeriesDataFrame:
401
369
  """Remove time series from train_data that either contain all NaNs or are too short for chosen settings.
@@ -406,7 +374,8 @@ class TimeSeriesPredictor:
406
374
  In other words, this method removes from train_data all time series with only NaN values or length less than
407
375
  min_train_length + prediction_length + (num_val_windows - 1) * val_step_size
408
376
  """
409
- 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
410
379
  train_lengths = train_data.num_timesteps_per_item()
411
380
  too_short_items = train_lengths.index[train_lengths < min_length]
412
381
 
@@ -417,7 +386,9 @@ class TimeSeriesPredictor:
417
386
  )
418
387
  train_data = train_data.query("item_id not in @too_short_items")
419
388
 
420
- all_nan_items = train_data.item_ids[train_data[self.target].isna().groupby(ITEMID, sort=False).all()]
389
+ all_nan_items = train_data.item_ids[
390
+ train_data[self.target].isna().groupby(TimeSeriesDataFrame.ITEMID, sort=False).all()
391
+ ]
421
392
  if len(all_nan_items) > 0:
422
393
  logger.info(f"\tRemoving {len(all_nan_items)} time series consisting of only NaN values from train_data.")
423
394
  train_data = train_data.query("item_id not in @all_nan_items")
@@ -435,27 +406,28 @@ class TimeSeriesPredictor:
435
406
  @apply_presets(get_predictor_presets())
436
407
  def fit(
437
408
  self,
438
- train_data: Union[TimeSeriesDataFrame, pd.DataFrame, Path, str],
439
- tuning_data: Optional[Union[TimeSeriesDataFrame, pd.DataFrame, Path, str]] = None,
440
- time_limit: Optional[int] = None,
441
- presets: Optional[str] = None,
442
- hyperparameters: Optional[Union[str, dict[Union[str, Type], Any]]] = None,
443
- hyperparameter_tune_kwargs: Optional[Union[str, dict]] = None,
444
- excluded_model_types: Optional[list[str]] = None,
445
- num_val_windows: int = 1,
446
- val_step_size: Optional[int] = None,
447
- 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,
448
420
  refit_full: bool = False,
449
421
  enable_ensemble: bool = True,
450
422
  skip_model_selection: bool = False,
451
- random_seed: Optional[int] = 123,
452
- verbosity: Optional[int] = None,
423
+ random_seed: int | None = 123,
424
+ verbosity: int | None = None,
453
425
  ) -> "TimeSeriesPredictor":
454
426
  """Fit probabilistic forecasting models to the given time series dataset.
455
427
 
456
428
  Parameters
457
429
  ----------
458
- train_data : Union[TimeSeriesDataFrame, pd.DataFrame, Path, str]
430
+ train_data : TimeSeriesDataFrame | pd.DataFrame | Path | str
459
431
  Training data in the :class:`~autogluon.timeseries.TimeSeriesDataFrame` format.
460
432
 
461
433
  Time series with length ``<= (num_val_windows + 1) * prediction_length`` will be ignored during training.
@@ -481,7 +453,7 @@ class TimeSeriesPredictor:
481
453
 
482
454
  If provided data is a ``pandas.DataFrame``, AutoGluon will attempt to convert it to a ``TimeSeriesDataFrame``.
483
455
  If a ``str`` or a ``Path`` is provided, AutoGluon will attempt to load this file.
484
- tuning_data : Union[TimeSeriesDataFrame, pd.DataFrame, Path, str], optional
456
+ tuning_data : TimeSeriesDataFrame | pd.DataFrame | Path | str, optional
485
457
  Data reserved for model selection and hyperparameter tuning, rather than training individual models. Also
486
458
  used to compute the validation scores. Note that only the last ``prediction_length`` time steps of each
487
459
  time series are used for computing the validation score.
@@ -623,13 +595,39 @@ class TimeSeriesPredictor:
623
595
  presets="high_quality",
624
596
  excluded_model_types=["DeepAR"],
625
597
  )
626
- 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
627
622
  Number of backtests done on ``train_data`` for each trained model to estimate the validation performance.
628
- If ``num_val_windows > 1`` is provided, this value may be automatically reduced to ensure that the majority
629
- 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.
624
+
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).
630
627
 
631
- Increasing this parameter increases the training time roughly by a factor of ``num_val_windows // refit_every_n_windows``.
632
- See ``refit_every_n_windows`` and ``val_step_size`` for details.
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.
633
631
 
634
632
  For example, for ``prediction_length=2``, ``num_val_windows=3`` and ``val_step_size=1`` the folds are::
635
633
 
@@ -640,17 +638,41 @@ class TimeSeriesPredictor:
640
638
 
641
639
  where ``x`` are the train time steps and ``y`` are the validation time steps.
642
640
 
643
- 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
+
644
664
  val_step_size : int or None, default = None
645
665
  Step size between consecutive validation windows. If set to ``None``, defaults to ``prediction_length``
646
666
  provided when creating the predictor.
647
667
 
648
- This argument has no effect if ``tuning_data`` is provided.
649
- 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
650
670
  When performing cross validation, each model will be retrained every ``refit_every_n_windows`` validation
651
671
  windows, where the number of validation windows is specified by ``num_val_windows``. Note that in the
652
672
  default setting where ``num_val_windows=1``, this argument has no effect.
653
673
 
674
+ If set to ``"auto"``, the value will be determined automatically based on ``num_val_windows``.
675
+
654
676
  If set to ``None``, models will only be fit once for the first (oldest) validation window. By default,
655
677
  ``refit_every_n_windows=1``, i.e., all models will be refit for each validation window.
656
678
  refit_full : bool, default = False
@@ -673,8 +695,10 @@ class TimeSeriesPredictor:
673
695
 
674
696
  """
675
697
  time_start = time.time()
676
- if self._learner.is_fit:
677
- 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
+ )
678
702
 
679
703
  if verbosity is None:
680
704
  verbosity = self.verbosity
@@ -720,40 +744,57 @@ class TimeSeriesPredictor:
720
744
 
721
745
  if val_step_size is None:
722
746
  val_step_size = self.prediction_length
747
+ median_timeseries_length = int(train_data.num_timesteps_per_item().median())
748
+
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
+ )
723
759
 
724
- if num_val_windows > 0:
725
- num_val_windows = self._reduce_num_val_windows_if_necessary(
726
- train_data, original_num_val_windows=num_val_windows, val_step_size=val_step_size
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,
727
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
+ )
728
776
 
729
777
  if tuning_data is not None:
730
778
  tuning_data = self._check_and_prepare_data_frame(tuning_data, name="tuning_data")
731
779
  tuning_data = self._check_and_prepare_data_frame_for_evaluation(tuning_data, name="tuning_data")
732
780
  logger.info(f"Provided tuning_data has {self._get_dataset_stats(tuning_data)}")
733
- # TODO: Use num_val_windows to perform multi-window backtests on tuning_data
734
- if num_val_windows > 0:
735
- logger.warning(
736
- "\tSetting num_val_windows = 0 (disabling backtesting on train_data) because tuning_data is provided."
737
- )
738
- num_val_windows = 0
739
781
 
740
- if num_val_windows == 0 and tuning_data is None:
741
- 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
+ )
742
787
 
743
- 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:
744
789
  logger.warning(
745
- f"\trefit_every_n_windows provided as {refit_every_n_windows} but num_val_windows is set to {num_val_windows}."
746
- " 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."
747
792
  )
748
793
 
749
794
  if not skip_model_selection:
750
- train_data = self._filter_useless_train_data(
751
- train_data, num_val_windows=num_val_windows, val_step_size=val_step_size
752
- )
753
-
754
- val_splitter = ExpandingWindowSplitter(
755
- prediction_length=self.prediction_length, num_val_windows=num_val_windows, val_step_size=val_step_size
756
- )
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)
757
798
 
758
799
  time_left = None if time_limit is None else time_limit - (time.time() - time_start)
759
800
  self._learner.fit(
@@ -762,9 +803,11 @@ class TimeSeriesPredictor:
762
803
  val_data=tuning_data,
763
804
  hyperparameter_tune_kwargs=hyperparameter_tune_kwargs,
764
805
  excluded_model_types=excluded_model_types,
806
+ ensemble_hyperparameters=ensemble_hyperparameters,
765
807
  time_limit=time_left,
766
808
  verbosity=verbosity,
767
- val_splitter=val_splitter,
809
+ num_val_windows=num_val_windows,
810
+ val_step_size=val_step_size,
768
811
  refit_every_n_windows=refit_every_n_windows,
769
812
  skip_model_selection=skip_model_selection,
770
813
  enable_ensemble=enable_ensemble,
@@ -779,23 +822,152 @@ class TimeSeriesPredictor:
779
822
  self.save()
780
823
  return self
781
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
+
782
953
  def model_names(self) -> list[str]:
783
954
  """Returns the list of model names trained by this predictor object."""
955
+ self._assert_is_fit("model_names")
784
956
  return self._trainer.get_model_names()
785
957
 
786
958
  def predict(
787
959
  self,
788
- data: Union[TimeSeriesDataFrame, pd.DataFrame, Path, str],
789
- known_covariates: Optional[Union[TimeSeriesDataFrame, pd.DataFrame, Path, str]] = None,
790
- 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,
791
963
  use_cache: bool = True,
792
- random_seed: Optional[int] = 123,
964
+ random_seed: int | None = 123,
793
965
  ) -> TimeSeriesDataFrame:
794
966
  """Return quantile and mean forecasts for the given dataset, starting from the end of each time series.
795
967
 
796
968
  Parameters
797
969
  ----------
798
- data : Union[TimeSeriesDataFrame, pd.DataFrame, Path, str]
970
+ data : TimeSeriesDataFrame | pd.DataFrame | Path | str
799
971
  Historical time series data for which the forecast needs to be made.
800
972
 
801
973
  The names and dtypes of columns and static features in ``data`` must match the ``train_data`` used to train
@@ -803,7 +975,7 @@ class TimeSeriesPredictor:
803
975
 
804
976
  If provided data is a ``pandas.DataFrame``, AutoGluon will attempt to convert it to a ``TimeSeriesDataFrame``.
805
977
  If a ``str`` or a ``Path`` is provided, AutoGluon will attempt to load this file.
806
- known_covariates : Union[TimeSeriesDataFrame, pd.DataFrame, Path, str], optional
978
+ known_covariates : TimeSeriesDataFrame | pd.DataFrame | Path | str, optional
807
979
  If ``known_covariates_names`` were specified when creating the predictor, it is necessary to provide the
808
980
  values of the known covariates for each time series during the forecast horizon. Specifically:
809
981
 
@@ -853,6 +1025,7 @@ class TimeSeriesPredictor:
853
1025
  B 2020-03-04 17.1
854
1026
  2020-03-05 8.3
855
1027
  """
1028
+ self._assert_is_fit("predict")
856
1029
  # Save original item_id order to return predictions in the same order as input data
857
1030
  data = self._to_data_frame(data)
858
1031
  original_item_id_order = data.item_ids
@@ -866,14 +1039,209 @@ class TimeSeriesPredictor:
866
1039
  use_cache=use_cache,
867
1040
  random_seed=random_seed,
868
1041
  )
869
- return cast(TimeSeriesDataFrame, predictions.reindex(original_item_id_order, level=ITEMID))
1042
+ return cast(TimeSeriesDataFrame, predictions.reindex(original_item_id_order, level=TimeSeriesDataFrame.ITEMID))
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
+ )
870
1238
 
871
1239
  def evaluate(
872
1240
  self,
873
- data: Union[TimeSeriesDataFrame, pd.DataFrame, Path, str],
874
- model: Optional[str] = None,
875
- metrics: Optional[Union[str, TimeSeriesScorer, list[Union[str, TimeSeriesScorer]]]] = None,
876
- 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,
877
1245
  display: bool = False,
878
1246
  use_cache: bool = True,
879
1247
  ) -> dict[str, float]:
@@ -890,7 +1258,7 @@ class TimeSeriesPredictor:
890
1258
 
891
1259
  Parameters
892
1260
  ----------
893
- data : Union[TimeSeriesDataFrame, pd.DataFrame, Path, str]
1261
+ data : TimeSeriesDataFrame | pd.DataFrame | Path | str
894
1262
  The data to evaluate the best model on. If a ``cutoff`` is not provided, the last ``prediction_length``
895
1263
  time steps of each time series in ``data`` will be held out for prediction and forecast accuracy will
896
1264
  be calculated on these time steps. When a ``cutoff`` is provided, the ``-cutoff``-th to the
@@ -907,7 +1275,7 @@ class TimeSeriesPredictor:
907
1275
  model : str, optional
908
1276
  Name of the model that you would like to evaluate. By default, the best model during training
909
1277
  (with highest validation score) will be used.
910
- metrics : str, TimeSeriesScorer or list[Union[str, TimeSeriesScorer]], optional
1278
+ metrics : str, TimeSeriesScorer or list[str | TimeSeriesScorer], optional
911
1279
  Metric or a list of metrics to compute scores with. Defaults to ``self.eval_metric``. Supports both
912
1280
  metric names as strings and custom metrics based on TimeSeriesScorer.
913
1281
  cutoff : int, optional
@@ -928,7 +1296,7 @@ class TimeSeriesPredictor:
928
1296
  will have their signs flipped to obey this convention. For example, negative MAPE values will be reported.
929
1297
  To get the ``eval_metric`` score, do ``output[predictor.eval_metric.name]``.
930
1298
  """
931
-
1299
+ self._assert_is_fit("evaluate")
932
1300
  data = self._check_and_prepare_data_frame(data)
933
1301
  data = self._check_and_prepare_data_frame_for_evaluation(data, cutoff=cutoff)
934
1302
 
@@ -940,15 +1308,15 @@ class TimeSeriesPredictor:
940
1308
 
941
1309
  def feature_importance(
942
1310
  self,
943
- data: Optional[Union[TimeSeriesDataFrame, pd.DataFrame, Path, str]] = None,
944
- model: Optional[str] = None,
945
- metric: Optional[Union[str, TimeSeriesScorer]] = None,
946
- features: Optional[list[str]] = None,
947
- 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,
948
1316
  method: Literal["naive", "permutation"] = "permutation",
949
1317
  subsample_size: int = 50,
950
- num_iterations: Optional[int] = None,
951
- random_seed: Optional[int] = 123,
1318
+ num_iterations: int | None = None,
1319
+ random_seed: int | None = 123,
952
1320
  relative_scores: bool = False,
953
1321
  include_confidence_band: bool = True,
954
1322
  confidence_level: float = 0.99,
@@ -1045,6 +1413,7 @@ class TimeSeriesPredictor:
1045
1413
  'importance': The estimated feature importance score.
1046
1414
  'stddev': The standard deviation of the feature importance score. If NaN, then not enough ``num_iterations`` were used.
1047
1415
  """
1416
+ self._assert_is_fit("feature_importance")
1048
1417
  if data is not None:
1049
1418
  data = self._check_and_prepare_data_frame(data)
1050
1419
  data = self._check_and_prepare_data_frame_for_evaluation(data)
@@ -1063,7 +1432,7 @@ class TimeSeriesPredictor:
1063
1432
  include_confidence_band=include_confidence_band,
1064
1433
  confidence_level=confidence_level,
1065
1434
  )
1066
- return fi_df
1435
+ return fi_df.sort_values("importance", ascending=False)
1067
1436
 
1068
1437
  @classmethod
1069
1438
  def _load_version_file(cls, path: str) -> str:
@@ -1091,7 +1460,7 @@ class TimeSeriesPredictor:
1091
1460
  return version
1092
1461
 
1093
1462
  @classmethod
1094
- 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":
1095
1464
  """Load an existing ``TimeSeriesPredictor`` from given ``path``.
1096
1465
 
1097
1466
  .. warning::
@@ -1175,15 +1544,14 @@ class TimeSeriesPredictor:
1175
1544
  @property
1176
1545
  def model_best(self) -> str:
1177
1546
  """Returns the name of the best model from trainer."""
1547
+ self._assert_is_fit("model_best")
1178
1548
  if self._trainer.model_best is not None:
1179
1549
  models = self._trainer.get_model_names()
1180
1550
  if self._trainer.model_best in models:
1181
1551
  return self._trainer.model_best
1182
1552
  return self._trainer.get_model_best()
1183
1553
 
1184
- def persist(
1185
- self, models: Union[Literal["all", "best"], list[str]] = "best", with_ancestors: bool = True
1186
- ) -> list[str]:
1554
+ def persist(self, models: Literal["all", "best"] | list[str] = "best", with_ancestors: bool = True) -> list[str]:
1187
1555
  """Persist models in memory for reduced inference latency. This is particularly important if the models are being used for online
1188
1556
  inference where low latency is critical. If models are not persisted in memory, they are loaded from disk every time they are
1189
1557
  asked to make predictions. This is especially cumbersome for large deep learning based models which have to be loaded into
@@ -1206,6 +1574,7 @@ class TimeSeriesPredictor:
1206
1574
  list_of_models : list[str]
1207
1575
  List of persisted model names.
1208
1576
  """
1577
+ self._assert_is_fit("persist")
1209
1578
  return self._learner.persist_trainer(models=models, with_ancestors=with_ancestors)
1210
1579
 
1211
1580
  def unpersist(self) -> list[str]:
@@ -1224,10 +1593,10 @@ class TimeSeriesPredictor:
1224
1593
 
1225
1594
  def leaderboard(
1226
1595
  self,
1227
- data: Optional[Union[TimeSeriesDataFrame, pd.DataFrame, Path, str]] = None,
1228
- cutoff: Optional[int] = None,
1596
+ data: TimeSeriesDataFrame | pd.DataFrame | Path | str | None = None,
1597
+ cutoff: int | None = None,
1229
1598
  extra_info: bool = False,
1230
- extra_metrics: Optional[list[Union[str, TimeSeriesScorer]]] = None,
1599
+ extra_metrics: list[str | TimeSeriesScorer] | None = None,
1231
1600
  display: bool = False,
1232
1601
  use_cache: bool = True,
1233
1602
  **kwargs,
@@ -1252,7 +1621,7 @@ class TimeSeriesPredictor:
1252
1621
 
1253
1622
  Parameters
1254
1623
  ----------
1255
- data : Union[TimeSeriesDataFrame, pd.DataFrame, Path, str], optional
1624
+ data : TimeSeriesDataFrame | pd.DataFrame | Path | str, optional
1256
1625
  dataset used for additional evaluation. Must include both historical and future data (i.e., length of all
1257
1626
  time series in ``data`` must be at least ``prediction_length + 1``, if ``cutoff`` is not provided,
1258
1627
  ``-cutoff + 1`` otherwise).
@@ -1271,7 +1640,7 @@ class TimeSeriesPredictor:
1271
1640
  If True, the leaderboard will contain an additional column ``hyperparameters`` with the hyperparameters used
1272
1641
  by each model during training. An empty dictionary ``{}`` means that the model was trained with default
1273
1642
  hyperparameters.
1274
- extra_metrics : list[Union[str, TimeSeriesScorer]], optional
1643
+ extra_metrics : list[str | TimeSeriesScorer], optional
1275
1644
  A list of metrics to calculate scores for and include in the output DataFrame.
1276
1645
 
1277
1646
  Only valid when ``data`` is specified. The scores refer to the scores on ``data`` (same data as used to
@@ -1293,6 +1662,7 @@ class TimeSeriesPredictor:
1293
1662
  The leaderboard containing information on all models and in order of best model to worst in terms of
1294
1663
  test performance.
1295
1664
  """
1665
+ self._assert_is_fit("leaderboard")
1296
1666
  if "silent" in kwargs:
1297
1667
  # keep `silent` logic for backwards compatibility
1298
1668
  assert isinstance(kwargs["silent"], bool)
@@ -1317,12 +1687,12 @@ class TimeSeriesPredictor:
1317
1687
  print(leaderboard)
1318
1688
  return leaderboard
1319
1689
 
1320
- 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:
1321
1691
  """Generate a dataframe with the ``item_id`` and ``timestamp`` values corresponding to the forecast horizon.
1322
1692
 
1323
1693
  Parameters
1324
1694
  ----------
1325
- data : Union[TimeSeriesDataFrame, pd.DataFrame, Path, str]
1695
+ data : TimeSeriesDataFrame | pd.DataFrame | Path | str
1326
1696
  Historical time series data.
1327
1697
 
1328
1698
  Returns
@@ -1370,6 +1740,7 @@ class TimeSeriesPredictor:
1370
1740
  Dict containing various detailed information. We do not recommend directly printing this dict as it may
1371
1741
  be very large.
1372
1742
  """
1743
+ self._assert_is_fit("fit_summary")
1373
1744
  # TODO: HPO-specific information currently not reported in fit_summary
1374
1745
  # TODO: Revisit after ray tune integration
1375
1746
 
@@ -1430,6 +1801,7 @@ class TimeSeriesPredictor:
1430
1801
  ``predictor.predict(data)`` is called will be the refit_full version instead of the original version of the
1431
1802
  model. Has no effect if ``model`` is not the best model.
1432
1803
  """
1804
+ self._assert_is_fit("refit_full")
1433
1805
  logger.warning(
1434
1806
  "\tWARNING: refit_full functionality for TimeSeriesPredictor is experimental "
1435
1807
  "and is not yet supported by all models."
@@ -1482,7 +1854,7 @@ class TimeSeriesPredictor:
1482
1854
  trainer = self._trainer
1483
1855
  train_data = trainer.load_train_data()
1484
1856
  val_data = trainer.load_val_data()
1485
- base_model_names = trainer.get_model_names(level=0)
1857
+ base_model_names = trainer.get_model_names(layer=0)
1486
1858
  pred_proba_dict_val: dict[str, list[TimeSeriesDataFrame]] = {
1487
1859
  model_name: trainer._get_model_oof_predictions(model_name)
1488
1860
  for model_name in base_model_names
@@ -1498,7 +1870,7 @@ class TimeSeriesPredictor:
1498
1870
  )
1499
1871
 
1500
1872
  y_val: list[TimeSeriesDataFrame] = [
1501
- select_target(df) for df in trainer._get_ensemble_oof_data(train_data=train_data, val_data=val_data)
1873
+ select_target(df) for df in trainer._get_validation_windows(train_data=train_data, val_data=val_data)
1502
1874
  ]
1503
1875
  y_test: TimeSeriesDataFrame = select_target(test_data)
1504
1876
 
@@ -1518,27 +1890,27 @@ class TimeSeriesPredictor:
1518
1890
 
1519
1891
  def plot(
1520
1892
  self,
1521
- data: Union[TimeSeriesDataFrame, pd.DataFrame, Path, str],
1522
- predictions: Optional[TimeSeriesDataFrame] = None,
1523
- quantile_levels: Optional[list[float]] = None,
1524
- 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,
1525
1897
  max_num_item_ids: int = 8,
1526
- max_history_length: Optional[int] = None,
1527
- point_forecast_column: Optional[str] = None,
1528
- 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,
1529
1901
  ):
1530
1902
  """Plot historical time series values and the forecasts.
1531
1903
 
1532
1904
  Parameters
1533
1905
  ----------
1534
- data : Union[TimeSeriesDataFrame, pd.DataFrame, Path, str]
1906
+ data : TimeSeriesDataFrame | pd.DataFrame | Path | str
1535
1907
  Observed time series data.
1536
1908
  predictions : TimeSeriesDataFrame, optional
1537
1909
  Predictions generated by calling :meth:`~autogluon.timeseries.TimeSeriesPredictor.predict`.
1538
1910
  quantile_levels : list[float], optional
1539
1911
  Quantile levels for which to plot the prediction intervals. Defaults to lowest & highest quantile levels
1540
1912
  available in ``predictions``.
1541
- item_ids : list[Union[str, int]], optional
1913
+ item_ids : list[str | int], optional
1542
1914
  If provided, plots will only be generated for time series with these item IDs. By default (if set to
1543
1915
  ``None``), item IDs are selected randomly. In either case, plots are generated for at most
1544
1916
  ``max_num_item_ids`` time series.
@@ -1621,7 +1993,7 @@ class TimeSeriesPredictor:
1621
1993
  for q in quantile_levels:
1622
1994
  ax.fill_between(forecast.index, point_forecast, forecast[str(q)], color="C1", alpha=0.2)
1623
1995
  if len(axes) > len(item_ids):
1624
- axes[len(item_ids)].set_axis_off()
1625
- handles, labels = axes[0].get_legend_handles_labels()
1996
+ axes[len(item_ids)].set_axis_off() # type: ignore
1997
+ handles, labels = axes[0].get_legend_handles_labels() # type: ignore
1626
1998
  fig.legend(handles, labels, bbox_to_anchor=(0.5, 0.0), ncols=len(handles))
1627
1999
  return fig