docstr: Temporal Cross-Validation with core.NeuralForecast.
  
  `core.NeuralForecast`'s cross-validation efficiently fits a list of NeuralForecast
  models through multiple windows, in either chained or rolled manner.
  
  Parameters
  ----------
  df : pandas or polars DataFrame, optional (default=None)
      DataFrame with columns [`unique_id`, `ds`, `y`] and exogenous variables.
      If None, a previously stored dataset is required.
  static_df : pandas or polars DataFrame, optional (default=None)
      DataFrame with columns [`unique_id`] and static exogenous.
  n_windows : int (default=1)
      Number of windows used for cross validation.
  step_size : int (default=1)
      Step size between each window.
  val_size : int, optional (default=None)
      Length of validation size. If passed, set `n_windows=None`.
  test_size : int, optional (default=None)
      Length of test size. If passed, set `n_windows=None`.
  sort_df : bool (default=True)
      Sort `df` before fitting.
  use_init_models : bool, option (default=False)
      Use initial model passed when object was instantiated.
  verbose : bool (default=False)
      Print processing steps.
  refit : bool or int (default=False)
      Retrain model for each cross validation window.
      If False, the models are trained at the beginning and then used to predict each window.
      If positive int, the models are retrained every `refit` windows.
  id_col : str (default='unique_id')
      Column that identifies each serie.
  time_col : str (default='ds')
      Column that identifies each timestep, its values can be timestamps or integers.
  target_col : str (default='y')
      Column that contains the target.
  data_kwargs : kwargs
      Extra arguments to be passed to the dataset within each model.
  
  Returns
  -------
  fcsts_df : pandas or polars DataFrame
      DataFrame with insample `models` columns for point predictions and probabilistic
      predictions for all fitted `models`.
docstr_tok: ["Temporal","Cross-Validation","with","core.NeuralForecast",".","`","core.NeuralForecast","`","'s","cross-validation","efficiently","fits","a","list","of","NeuralForecast","models","through","multiple","windows",",","in","either","chained","or","rolled","manner",".","Parameters","--","--","--","--","--","df",":","pandas","or","polars","DataFrame",",","optional","(","default=None",")","DataFrame","with","columns","[","`","unique_id","`",",","`","ds","`",",","`","y","`","]","and","exogenous","variables",".","If","None",",","a","previously","stored","dataset","is","required",".","static_df",":","pandas","or","polars","DataFrame",",","optional","(","default=None",")","DataFrame","with","columns","[","`","unique_id","`","]","and","static","exogenous",".","n_windows",":","int","(","default=1",")","Number","of","windows","used","for","cross","validation",".","step_size",":","int","(","default=1",")","Step","size","between","each","window",".","val_size",":","int",",","optional","(","default=None",")","Length","of","validation","size",".","If","passed",",","set","`","n_windows=None","`",".","test_size",":","int",",","optional","(","default=None",")","Length","of","test","size",".","If","passed",",","set","`","n_windows=None","`",".","sort_df",":","bool","(","default=True",")","Sort","`","df","`","before","fitting",".","use_init_models",":","bool",",","option","(","default=False",")","Use","initial","model","passed","when","object","was","instantiated",".","verbose",":","bool","(","default=False",")","Print","processing","steps",".","refit",":","bool","or","int","(","default=False",")","Retrain","model","for","each","cross","validation","window",".","If","False",",","the","models","are","trained","at","the","beginning","and","then","used","to","predict","each","window",".","If","positive","int",",","the","models","are","retrained","every","`","refit","`","windows",".","id_col",":","str","(","default='unique_id","'",")","Column","that","identifies","each","serie",".","time_col",":","str","(","default='ds","'",")","Column","that","identifies","each","timestep",",","its","values","can","be","timestamps","or","integers",".","target_col",":","str","(","default=","'","y","'",")","Column","that","contains","the","target",".","data_kwargs",":","kwargs","Extra","arguments","to","be","passed","to","the","dataset","within","each","model",".","Returns","--","--","--","-","fcsts_df",":","pandas","or","polars","DataFrame","DataFrame","with","insample","`","models","`","columns","for","point","predictions","and","probabilistic","predictions","for","all","fitted","`","models","`","."]
code: def cross_validation(
      self,
      df: Optional[DataFrame] = None,
      static_df: Optional[DataFrame] = None,
      n_windows: int = 1,
      step_size: int = 1,
      val_size: Optional[int] = 0,
      test_size: Optional[int] = None,
      sort_df: bool = True,
      use_init_models: bool = False,
      verbose: bool = False,
      refit: Union[bool, int] = False,
      id_col: str = "unique_id",
      time_col: str = "ds",
      target_col: str = "y",
      **data_kwargs,
  ) -> DataFrame:
      """Temporal Cross-Validation with core.NeuralForecast.
  
      `core.NeuralForecast`'s cross-validation efficiently fits a list of NeuralForecast
      models through multiple windows, in either chained or rolled manner.
  
      Parameters
      ----------
      df : pandas or polars DataFrame, optional (default=None)
          DataFrame with columns [`unique_id`, `ds`, `y`] and exogenous variables.
          If None, a previously stored dataset is required.
      static_df : pandas or polars DataFrame, optional (default=None)
          DataFrame with columns [`unique_id`] and static exogenous.
      n_windows : int (default=1)
          Number of windows used for cross validation.
      step_size : int (default=1)
          Step size between each window.
      val_size : int, optional (default=None)
          Length of validation size. If passed, set `n_windows=None`.
      test_size : int, optional (default=None)
          Length of test size. If passed, set `n_windows=None`.
      sort_df : bool (default=True)
          Sort `df` before fitting.
      use_init_models : bool, option (default=False)
          Use initial model passed when object was instantiated.
      verbose : bool (default=False)
          Print processing steps.
      refit : bool or int (default=False)
          Retrain model for each cross validation window.
          If False, the models are trained at the beginning and then used to predict each window.
          If positive int, the models are retrained every `refit` windows.
      id_col : str (default='unique_id')
          Column that identifies each serie.
      time_col : str (default='ds')
          Column that identifies each timestep, its values can be timestamps or integers.
      target_col : str (default='y')
          Column that contains the target.
      data_kwargs : kwargs
          Extra arguments to be passed to the dataset within each model.
  
      Returns
      -------
      fcsts_df : pandas or polars DataFrame
          DataFrame with insample `models` columns for point predictions and probabilistic
          predictions for all fitted `models`.
      """
      h = self.h
      if n_windows is None and test_size is None:
          raise Exception("you must define `n_windows` or `test_size`.")
      if test_size is None:
          test_size = h + step_size * (n_windows - 1)
      elif n_windows is None:
          if (test_size - h) % step_size:
              raise Exception(
                  "`test_size - h` should be module `step_size`"
              )
          n_windows = int((test_size - h) / step_size) + 1
      else:
          raise Exception(
              "you must define `n_windows` or `test_size` but not both"
          )
      # Recover initial model if use_init_models.
      if use_init_models:
          self._reset_models()
      if not refit:
          return self._no_refit_cross_validation(
              df=df,
              static_df=static_df,
              n_windows=n_windows,
              step_size=step_size,
              val_size=val_size,
              test_size=test_size,
              sort_df=sort_df,
              verbose=verbose,
              id_col=id_col,
              time_col=time_col,
              target_col=target_col,
              **data_kwargs,
          )
      if df is None:
          raise ValueError("Must specify `df` with `refit!=False`.")
      validate_freq(df[time_col], self.freq)
      splits = ufp.backtest_splits(
          df,
          n_windows=n_windows,
          h=self.h,
          id_col=id_col,
          time_col=time_col,
          freq=self.freq,
          step_size=step_size,
          input_size=None,
      )
      results = []
      for i_window, (cutoffs, train, test) in enumerate(splits):
          should_fit = i_window == 0 or (
              refit > 0 and i_window % refit == 0
          )
          if should_fit:
              self.fit(
                  df=train,
                  static_df=static_df,
                  val_size=val_size,
                  sort_df=sort_df,
                  use_init_models=False,
                  verbose=verbose,
              )
              predict_df: Optional[DataFrame] = None
          else:
              predict_df = train
          needed_futr_exog = self._get_needed_futr_exog()
          if needed_futr_exog:
              futr_df: Optional[DataFrame] = test
          else:
              futr_df = None
          preds = self.predict(
              df=predict_df,
              static_df=static_df,
              futr_df=futr_df,
              sort_df=sort_df,
              verbose=verbose,
              **data_kwargs,
          )
          preds = ufp.join(preds, cutoffs, on=id_col, how="left")
          fold_result = ufp.join(
              preds,
              test[[id_col, time_col, target_col]],
              on=[id_col, time_col],
          )
          results.append(fold_result)
      out = ufp.vertical_concat(results, match_categories=False)
      out = ufp.drop_index_if_pandas(out)
      # match order of cv with no refit
      first_out_cols = [id_col, time_col, "cutoff"]
      remaining_cols = [
          c
          for c in out.columns
          if c not in first_out_cols + [target_col]
      ]
      cols_order = first_out_cols + remaining_cols + [target_col]
      out = ufp.sort(out[cols_order], by=[id_col, "cutoff", time_col])
      if isinstance(out, pd.DataFrame) and _id_as_idx():
          _warn_id_as_idx()
          out = out.set_index(id_col)
      return out
  
imports: import os
  import pickle
  import warnings
  from copy import deepcopy
  from itertools import chain
  from typing import Any, Dict, List, Optional, Union
  import numpy
  import pandas
  import torch
  import utilsforecast.processing
  from utilsforecast.compat import DataFrame, Series, pl_DataFrame, pl_Series
  from utilsforecast.grouped_array import GroupedArray
  from utilsforecast.target_transforms import BaseTargetTransform, LocalBoxCox, LocalMinMaxScaler, LocalRobustScaler, LocalStandardScaler
  from utilsforecast.validation import validate_freq
  from .tsdataset import TimeSeriesDataset
  from neuralforecast.models import GRU, LSTM, RNN, TCN, DeepAR, DilatedRNN, MLP, NHITS, NBEATS, NBEATSx, TFT, VanillaTransformer, Informer, Autoformer, FEDformer, StemGNN, PatchTST, TimesNet
label_desc: Use image node_id 13 for calling the NeuralForecast obj's underlying member method code with example usage: obj.cross_validation(df, static_df, n_windows, step_size, val_size, test_size, sort_df, use_init_models, verbose, refit, id_col, time_col, target_col) and returns: out, self