NeuralForecast

 NeuralForecast (models:List[Any], freq:Union[str,int],
                 local_scaler_type:Optional[str]=None)

core.StatsForecast 类允许您高效地拟合大量时间序列的多个 NeuralForecast 模型。它使用 pandas DataFrame df 进行操作,该 DataFrame 使用 unique_idds 列标识序列和日期时间戳。y 列表示目标时间序列变量。

类型默认值详情
models列表实例化的 neuralforecast.models
请参阅此处的集合
freq联合类型数据的频率。必须是有效的 pandas 或 polars offset 别名,或一个整数。
local_scaler_type可选None在拟合之前对每个序列的所有特征应用的缩放器,预测后会反转。
可以是 ‘standard’、‘robust’、‘robust-iqr’、‘minmax’ 或 ‘boxcox’
返回NeuralForecast返回实例化的 NeuralForecast 类。

NeuralForecast.fit

 NeuralForecast.fit (df:Union[pandas.core.frame.DataFrame,polars.dataframe
                     .frame.DataFrame,neuralforecast.compat.SparkDataFrame
                     ,Sequence[str],NoneType]=None, static_df:Union[pandas
                     .core.frame.DataFrame,polars.dataframe.frame.DataFram
                     e,neuralforecast.compat.SparkDataFrame,NoneType]=None
                     , val_size:Optional[int]=0,
                     use_init_models:bool=False, verbose:bool=False,
                     id_col:str='unique_id', time_col:str='ds',
                     target_col:str='y', distributed_config:Optional[neura
                     lforecast.common._base_model.DistributedConfig]=None,
                     prediction_intervals:Optional[neuralforecast.utils.Pr
                     edictionIntervals]=None)

*拟合 core.NeuralForecast。*

*将 models 拟合到 DataFrame df 中的大量时间序列。并存储拟合的模型以供后续检查。*

类型默认值详情
df联合类型None包含 [unique_id, ds, y] 列和外生变量的 DataFrame。
如果为 None,则需要之前存储的数据集。
static_df联合类型None包含 [unique_id] 列和静态外生变量的 DataFrame。
val_size可选0验证集大小。
use_init_models布尔值False使用实例化 NeuralForecast 对象时传入的初始模型。
verbose布尔值False打印处理步骤。
id_col字符串unique_id标识每个序列的列。
time_col字符串ds标识每个时间步的列,其值可以是时间戳或整数。
target_col字符串y包含目标的列。
distributed_config可选None用于 DDP 训练的配置。目前仅支持 spark。
prediction_intervals可选None校准预测区间(一致性预测)的配置。
返回NeuralForecast返回包含拟合的 modelsNeuralForecast 类。

NeuralForecast.predict

 NeuralForecast.predict (df:Union[pandas.core.frame.DataFrame,polars.dataf
                         rame.frame.DataFrame,neuralforecast.compat.SparkD
                         ataFrame,NoneType]=None, static_df:Union[pandas.c
                         ore.frame.DataFrame,polars.dataframe.frame.DataFr
                         ame,neuralforecast.compat.SparkDataFrame,NoneType
                         ]=None, futr_df:Union[pandas.core.frame.DataFrame
                         ,polars.dataframe.frame.DataFrame,neuralforecast.
                         compat.SparkDataFrame,NoneType]=None,
                         verbose:bool=False, engine=None,
                         level:Optional[List[Union[int,float]]]=None,
                         quantiles:Optional[List[float]]=None,
                         **data_kwargs)

*使用 core.NeuralForecast 进行预测。*

*使用存储的拟合 models 从 DataFrame df 中预测大量时间序列。*

类型默认值详情
df联合类型None包含 [unique_id, ds, y] 列和外生变量的 DataFrame。
如果传入 DataFrame,则用于生成预测。
static_df联合类型None包含 [unique_id] 列和静态外生变量的 DataFrame。
futr_df联合类型None包含 [unique_id, ds] 列和 df 的未来外生变量的 DataFrame。
verbose布尔值False打印处理步骤。
engineNoneTypeNone用于推理的分布式引擎。仅在 df 是 spark dataframe 或 fit 是在 spark dataframe 上调用时使用。
level可选None0 到 100 之间的置信水平。
quantiles可选Nonelevel 的替代方案,目标分位数进行预测。
data_kwargsVAR_KEYWORD传递给每个模型内数据集的额外参数。
返回pandas 或 polars DataFrame**包含样本内 models 列的 DataFrame,用于点预测和概率预测**
**所有拟合的 models 的预测。**

NeuralForecast.cross_validation

 NeuralForecast.cross_validation (df:Union[pandas.core.frame.DataFrame,pol
                                  ars.dataframe.frame.DataFrame,NoneType]=
                                  None, static_df:Union[pandas.core.frame.
                                  DataFrame,polars.dataframe.frame.DataFra
                                  me,NoneType]=None, n_windows:int=1,
                                  step_size:int=1,
                                  val_size:Optional[int]=0,
                                  test_size:Optional[int]=None,
                                  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', p
                                  rediction_intervals:Optional[neuralforec
                                  ast.utils.PredictionIntervals]=None, lev
                                  el:Optional[List[Union[int,float]]]=None
                                  , quantiles:Optional[List[float]]=None,
                                  **data_kwargs)

*使用 core.NeuralForecast 进行时间序列交叉验证。*

core.NeuralForecast 的交叉验证通过多个窗口高效地拟合 NeuralForecast 模型列表,可以采用链式或滚动方式进行。*

类型默认值详情
df联合类型None包含 [unique_id, ds, y] 列和外生变量的 DataFrame。
如果为 None,则需要之前存储的数据集。
static_df联合类型None包含 [unique_id] 列和静态外生变量的 DataFrame。
n_windows整数1用于交叉验证的窗口数量。
step_size整数1每个窗口之间的步长。
val_size可选0验证集长度。如果传入,将 n_windows 设置为 None。
test_size可选None测试集长度。如果传入,将 n_windows 设置为 None。
use_init_models布尔值False使用对象实例化时传入的初始模型。
verbose布尔值False打印处理步骤。
refit联合类型False为每个交叉验证窗口重新训练模型。
如果为 False,则模型在开始时训练一次,然后用于预测每个窗口。
如果为正整数,则模型每 refit 个窗口重新训练。
id_col字符串unique_id标识每个序列的列。
time_col字符串ds标识每个时间步的列,其值可以是时间戳或整数。
target_col字符串y包含目标的列。
prediction_intervals可选None校准预测区间(一致性预测)的配置。
level可选None0 到 100 之间的置信水平。
quantiles可选Nonelevel 的替代方案,目标分位数进行预测。
data_kwargsVAR_KEYWORD传递给每个模型内数据集的额外参数。
返回联合类型**包含样本内 models 列的 DataFrame,用于点预测和概率预测**
**所有拟合的 models 的预测。**

NeuralForecast.predict_insample

 NeuralForecast.predict_insample (step_size:int=1)

*使用 core.NeuralForecast 进行样本内预测。*

core.NeuralForecastpredict_insample 使用存储的拟合 models 从存储的 dataframe 中预测时间序列的历史值。*

类型默认值详情
step_size整数1每个窗口之间的步长。
返回pandas.DataFrame**包含所有拟合的 models 的样本内预测的 DataFrame。**

NeuralForecast.save

 NeuralForecast.save (path:str, model_index:Optional[List]=None,
                      save_dataset:bool=True, overwrite:bool=False)

*保存 NeuralForecast 核心类。*

core.NeuralForecast 的方法,用于保存模型、数据集和配置的当前状态。请注意,默认情况下 models 不保存训练检查点以节省磁盘空间,要保存检查点,请更改单个模型的 **trainer_kwargs 以包含 enable_checkpointing=True。*

类型默认值详情
path字符串保存当前状态的目录。
model_index可选None指定从 self.models 列表中保存哪些模型的列表。
save_dataset布尔值True是否保存数据集。
overwrite布尔值False是否覆盖文件。
/opt/hostedtoolcache/Python/3.10.16/x64/lib/python3.10/site-packages/fastcore/docscrape.py:230: UserWarning: potentially wrong underline length... 
Parameters 
----------- in 
Load NeuralForecast
...
  else: warn(msg)

NeuralForecast.load

 NeuralForecast.load (path, verbose=False, **kwargs)

*加载 NeuralForecast*

core.NeuralForecast 的方法,用于从路径加载检查点。*

类型默认值详情
path字符串包含存储工件的目录。
verbose布尔值False
kwargsVAR_KEYWORD要传递给函数的额外关键字参数
load_from_checkpoint.
返回NeuralForecast实例化的 NeuralForecast 类。
# Test predict_insample step_size

h = 12
train_end = AirPassengersPanel_train['ds'].max()
sizes = AirPassengersPanel_train['unique_id'].value_counts().to_numpy()
for step_size, test_size in [(7, 0), (9, 0), (7, 5), (9, 5)]:
    models = [NHITS(h=h, input_size=12, max_steps=1)]
    nf = NeuralForecast(models=models, freq='M')
    nf.fit(AirPassengersPanel_train)
    # Note: only apply set_test_size() upon nf.fit(), otherwise it would have set the test_size = 0
    nf.models[0].set_test_size(test_size)
    
    forecasts = nf.predict_insample(step_size=step_size)
    last_cutoff = train_end - test_size * pd.offsets.MonthEnd() - h * pd.offsets.MonthEnd()
    n_expected_cutoffs = (sizes[0] - test_size - nf.h + step_size) // step_size

    # compare cutoff values
    expected_cutoffs = np.flip(np.array([last_cutoff - step_size * i * pd.offsets.MonthEnd() for i in range(n_expected_cutoffs)]))
    actual_cutoffs = np.array([pd.Timestamp(x) for x in forecasts[forecasts['unique_id']==nf.uids[1]]['cutoff'].unique()])
    np.testing.assert_array_equal(expected_cutoffs, actual_cutoffs, err_msg=f"{step_size=},{expected_cutoffs=},{actual_cutoffs=}")
    
    # check forecast-points count per series
    cutoffs_by_series = forecasts.groupby(['unique_id', 'cutoff']).size().unstack('unique_id')
    pd.testing.assert_series_equal(cutoffs_by_series['Airline1'], cutoffs_by_series['Airline2'], check_names=False)
def config_optuna(trial):
    return {"input_size": trial.suggest_categorical('input_size', [12, 24]),
        "hist_exog_list": trial.suggest_categorical('hist_exog_list', [['trend'], ['y_[lag12]'], ['trend', 'y_[lag12]']]),
        "futr_exog_list": ['trend'],
        "max_steps": 10,
        "val_check_steps": 5}

config_ray = {'input_size': tune.choice([12, 24]), 
          'hist_exog_list': tune.choice([['trend'], ['y_[lag12]'], ['trend', 'y_[lag12]']]),
          'futr_exog_list': ['trend'],
          'max_steps': 10,
          'val_check_steps': 5}
# Test predict_insample step_size

h = 12
train_end = AirPassengers_pl['time'].max()
sizes = AirPassengers_pl['uid'].value_counts().to_numpy()

for step_size, test_size in [(7, 0), (9, 0), (7, 5), (9, 5)]:
    models = [NHITS(h=h, input_size=12, max_steps=1)]
    nf = NeuralForecast(models=models, freq='1mo')
    nf.fit(
        AirPassengers_pl,
        id_col='uid',
        time_col='time',
        target_col='target',    
    )
    # Note: only apply set_test_size() upon nf.fit(), otherwise it would have set the test_size = 0
    nf.models[0].set_test_size(test_size)    
    
    forecasts = nf.predict_insample(step_size=step_size)
    n_expected_cutoffs = (sizes[0][1] - test_size - nf.h + step_size) // step_size

    # compare cutoff values
    last_cutoff = train_end - test_size * pd.offsets.MonthEnd() - h * pd.offsets.MonthEnd()
    expected_cutoffs = np.flip(np.array([last_cutoff - step_size * i * pd.offsets.MonthEnd() for i in range(n_expected_cutoffs)]))
    pl_cutoffs = forecasts.filter(polars.col('uid') ==nf.uids[1]).select('cutoff').unique(maintain_order=True)
    actual_cutoffs = np.sort(np.array([pd.Timestamp(x['cutoff']) for x in pl_cutoffs.rows(named=True)]))
    np.testing.assert_array_equal(expected_cutoffs, actual_cutoffs, err_msg=f"{step_size=},{expected_cutoffs=},{actual_cutoffs=}")

    # check forecast-points count per series
    cutoffs_by_series = forecasts.group_by(['uid', 'cutoff']).count()
    assert_frame_equal(cutoffs_by_series.filter(polars.col('uid') == "Airline1").select(['cutoff', 'count']), cutoffs_by_series.filter(polars.col('uid') == "Airline2").select(['cutoff', 'count'] ), check_row_order=False)