HierarchicalForecast 包包含用于整理和可视化分层序列数据集的实用函数。该模块的 aggregate 函数允许您从代表结构级别的分类变量创建层次结构,同时返回聚合约束矩阵 S\mathbf{S}

此外,HierarchicalForecast 通过其外部预测适配器确保其协调方法与其他流行的机器学习库兼容,这些适配器将外部库的输出基础预测转换为兼容的数据框格式。

聚合函数


来源

aggregate

 aggregate
            (df:Union[ForwardRef('DataFrame[Any]'),ForwardRef('LazyFrame[A
            ny]')], spec:list[list[str]],
            exog_vars:Optional[dict[str,Union[str,list[str]]]]=None,
            sparse_s:bool=False, id_col:str='unique_id',
            time_col:str='ds', id_time_col:Optional[str]=None,
            target_cols:collections.abc.Sequence[str]=('y',))

Utils 聚合函数。根据 spec 列表中定义的级别聚合 DataFrame df 中包含的底层序列。

类型默认值详细信息
dfUnion包含列 [time_col, *target_cols]、要聚合的列以及可选的 exog_vars 的 Dataframe。
speclist级别列表。列表的每个元素应包含 df 中要聚合的列列表。
exog_vars可选None
sparse_sboolFalse返回稀疏 Pandas 数据框形式的 S_df
id_colstrunique_id聚合后标识每个序列的列。
time_colstrds标识每个时间步的列,其值可以是时间戳或整数。
id_time_col可选None时间聚合后标识每个时间步的列。如果提供,aggregate 将按时间进行操作。
target_colsSequence(‘y’,)包含要聚合的目标的列列表。
返回tuple分层结构的序列。

来源

aggregate_temporal

 aggregate_temporal
                     (df:Union[ForwardRef('DataFrame[Any]'),ForwardRef('La
                     zyFrame[Any]')], spec:dict[str,int], exog_vars:Option
                     al[dict[str,Union[str,list[str]]]]=None,
                     sparse_s:bool=False, id_col:str='unique_id',
                     time_col:str='ds', id_time_col:str='temporal_id',
                     target_cols:collections.abc.Sequence[str]=('y',),
                     aggregation_type:str='local')

用于时间聚合的 Utils 聚合函数。根据 spec 列表中定义的时间级别聚合 DataFrame df 中包含的底层时间步。

类型默认值详细信息
dfUnion包含列 [time_col, target_cols] 和要聚合的列的 Dataframe。
specdict时间级别字典。每个键应是一个字符串,其值表示聚合中包含的底层时间步数量。
exog_vars可选None
sparse_sboolFalse返回稀疏 Pandas 数据框形式的 S_df
id_colstrunique_id聚合后标识每个序列的列。
time_colstrds标识每个时间步的列,其值可以是时间戳或整数。
id_time_colstrtemporal_id聚合后标识每个时间步的列。
target_colsSequence(‘y’,)包含要聚合的目标的列列表。
aggregation_typestrlocal如果为“local”,则对每个时间序列的时间戳独立执行聚合。如果为“global”,则对所有时间序列的唯一时间戳执行聚合。
返回tuple按时间分层结构的序列。

来源

make_future_dataframe

 make_future_dataframe
                        (df:Union[ForwardRef('DataFrame[Any]'),ForwardRef(
                        'LazyFrame[Any]')], freq:Union[str,int], h:int,
                        id_col:str='unique_id', time_col:str='ds')

创建用于预测的未来数据框。

类型默认值详细信息
dfUnion包含外生回归变量的 ID、时间和值的数据框。
freqUnion数据的频率。必须是有效的 pandas 或 polars offset alias,或一个整数。
hint预测范围。
id_colstrunique_id标识每个序列的列。
time_colstrds标识每个时间步的列,其值可以是时间戳或整数。
返回FrameT包含未来值的 DataFrame

来源

get_cross_temporal_tags

 get_cross_temporal_tags
                          (df:Union[ForwardRef('DataFrame[Any]'),ForwardRe
                          f('LazyFrame[Any]')],
                          tags_cs:dict[str,numpy.ndarray],
                          tags_te:dict[str,numpy.ndarray], sep:str='//',
                          id_col:str='unique_id',
                          id_time_col:str='temporal_id',
                          cross_temporal_id_col:str='cross_temporal_id')

获取交叉时间标签。

类型默认值详细信息
dfUnion包含时间 ID 的 DataFrame。
tags_csdict交叉截面层次结构的标签
tags_tedict时间层次结构的标签
sepstr//交叉时间标签的分隔符。
id_colstrunique_id标识每个序列的列。
id_time_colstrtemporal_id标识每个(聚合的)时间步的列。
cross_temporal_id_colstrcross_temporal_id标识每个交叉时间聚合的列。
返回tuple包含交叉时间 ID 的 DataFrame。

分层可视化


来源

HierarchicalPlot

 HierarchicalPlot
                   (S:Union[ForwardRef('DataFrame[Any]'),ForwardRef('LazyF
                   rame[Any]')], tags:dict[str,numpy.ndarray],
                   S_id_col:str='unique_id')

*分层图

此类包含一系列适合中小型分层序列的 matplotlib 可视化方法。

参数
S:大小为 (base, bottom) 的求和矩阵 DataFrame,参见 aggregate 函数
tags:np.ndarray,包含分层聚合索引,其中每个键是一个级别,其值包含与该级别关联的标签。
S_id_col:str='unique_id',标识每个聚合的列。
*


来源

plot_summing_matrix

 plot_summing_matrix ()

*求和约束图

此方法仅绘制分层聚合约束矩阵 S\mathbf{S}。*


来源

plot_series

 plot_series (series:str,
              Y_df:Union[ForwardRef('DataFrame[Any]'),ForwardRef('LazyFram
              e[Any]')], models:Optional[list[str]]=None,
              level:Optional[list[int]]=None, id_col:str='unique_id',
              time_col:str='ds', target_col:str='y')

*单序列图

参数
series:str,用于标识要绘制的任何级别序列 'unique_id' 的字符串。
Y_df:DataFrame,分层结构的序列(y[a,b]\mathbf{y}_{[a,b]})。它包含列 ['unique_id', 'ds', 'y'],可能包含 'models'
models:list[str],标识过滤模型列的字符串列表。
level:float list 0-100,Y_df 中可用的预测区间的置信水平。
id_col:str='unique_id',标识每个序列的列。
time_col:str='ds',标识每个时间步的列,其值可以是时间戳或整数。
target_col:str='y',包含目标的列。

返回
带有过滤模型和预测区间水平的单序列图。

*


来源

plot_hierarchically_linked_series

 plot_hierarchically_linked_series (bottom_series:str,
                                    Y_df:Union[ForwardRef('DataFrame[Any]'
                                    ),ForwardRef('LazyFrame[Any]')],
                                    models:Optional[list[str]]=None,
                                    level:Optional[list[int]]=None,
                                    id_col:str='unique_id',
                                    time_col:str='ds', target_col:str='y')

*分层链接序列图

参数
bottom_series:str,用于标识要绘制的底层序列 'unique_id' 的字符串。
Y_df:DataFrame,分层结构的序列(y[a,b]\mathbf{y}_{[a,b]})。它包含列 [‘unique_id’, ‘ds’, ‘y’] 和 models。
models:list[str],标识过滤模型列的字符串列表。
level:float list 0-100,Y_df 中可用的预测区间的置信水平。
id_col:str='unique_id',标识每个序列的列。
time_col:str='ds',标识每个时间步的列,其值可以是时间戳或整数。
target_col:str='y',包含目标的列。

返回
bottom_series 相关的分层链接序列图集合,带有过滤的模型和预测区间水平。

*


来源

plot_hierarchical_predictions_gap

 plot_hierarchical_predictions_gap
                                    (Y_df:Union[ForwardRef('DataFrame[Any]
                                    '),ForwardRef('LazyFrame[Any]')],
                                    models:Optional[list[str]]=None,
                                    xlabel:Optional[str]=None,
                                    ylabel:Optional[str]=None,
                                    id_col:str='unique_id',
                                    time_col:str='ds', target_col:str='y')

*分层预测差距图

参数
Y_df:DataFrame,分层结构的序列(y[a,b]\mathbf{y}_{[a,b]})。它包含列 [‘unique_id’, ‘ds’, ‘y’] 和 models。
models:list[str],标识过滤模型列的字符串列表。
xlabel:str,用于图表 x 轴标签的字符串。
ylabel:str,用于图表 y 轴标签的字符串。
id_col:str='unique_id',标识每个序列的列。
time_col:str='ds',标识每个时间步的列,其值可以是时间戳或整数。
target_col:str='y',包含目标的列。

返回
在分层结构的不同级别上聚合预测值的图表。聚合根据标签级别进行,参见 aggregate 函数

*

from statsforecast.core import StatsForecast
from statsforecast.models import AutoETS
from datasetsforecast.hierarchical import HierarchicalData

Y_df, S, tags = HierarchicalData.load('./data', 'Labour')
Y_df['ds'] = pd.to_datetime(Y_df['ds'])
S = S.reset_index(names="unique_id")

Y_test_df  = Y_df.groupby('unique_id').tail(24)
Y_train_df = Y_df.drop(Y_test_df.index)

fcst = StatsForecast( 
    models=[AutoETS(season_length=12, model='AAZ')],
    freq='MS', 
    n_jobs=-1
)
Y_hat_df = fcst.forecast(df=Y_train_df, h=24).reset_index()

# Plot prediction difference of different aggregation
# Levels Country, Country/Region, Country/Gender/Region ...
hplots = HierarchicalPlot(S=S, tags=tags)

hplots.plot_hierarchical_predictions_gap(
    Y_df=Y_hat_df, models='AutoETS',
    xlabel='Month', ylabel='Predictions',
)
# polars
from statsforecast.core import StatsForecast
from statsforecast.models import AutoETS
from datasetsforecast.hierarchical import HierarchicalData

Y_df, S, tags = HierarchicalData.load('./data', 'Labour')
Y_df['ds'] = pd.to_datetime(Y_df['ds'])
S = S.reset_index(names="unique_id")

Y_test_df  = Y_df.groupby('unique_id').tail(24)
Y_train_df = Y_df.drop(Y_test_df.index)
Y_test_df_pl  = pl.from_pandas(Y_test_df)
Y_train_df_pl = pl.from_pandas(Y_train_df)

fcst = StatsForecast(
    models=[AutoETS(season_length=12, model='AAZ')],
    freq='1m', 
    n_jobs=-1
)
Y_hat_df = fcst.forecast(df=Y_train_df_pl, h=24)

# Plot prediction difference of different aggregation
# Levels Country, Country/Region, Country/Gender/Region ...
hplots = HierarchicalPlot(S=S, tags=tags)

hplots.plot_hierarchical_predictions_gap(
    Y_df=Y_hat_df, models='AutoETS',
    xlabel='Month', ylabel='Predictions',
)

外部预测适配器


来源

samples_to_quantiles_df

 samples_to_quantiles_df (samples:numpy.ndarray,
                          unique_ids:collections.abc.Sequence[str],
                          dates:list[str],
                          quantiles:Optional[list[float]]=None,
                          level:Optional[list[int]]=None,
                          model_name:str='model', id_col:str='unique_id',
                          time_col:str='ds', backend:str='pandas')

*将随机样本转换为 HierarchicalForecast 输入。辅助函数,用于创建兼容的 HierarchicalForecast 输入 Y_hat_df 数据框。

参数
samples:numpy 数组。形状为 [n_series, n_samples, horizon] 的预测分布样本。
unique_ids:字符串列表。每个时间序列的唯一标识符。
dates:datetime 列表。预测日期列表。
quantiles:[0., 1.] 之间的浮点列表。作为 level 的替代,从 y 分布中估计的分位数。
level:[0, 100] 之间的整数列表。预测区间的概率水平。
model_name:字符串。预测模型的名称。
id_col:str='unique_id',标识每个序列的列。
time_col:str='ds',标识每个时间步的列,其值可以是时间戳或整数。
backend:str='pandas',用于输出数据框的后端,可以是 'pandas' 或 'polars'。

返回
quantiles:[0., 1.] 之间的浮点列表。从 y 分布中估计的分位数。
Y_hat_df:DataFrame。包含按 unique_id 索引的,带有 ds 和 models 列的用于协调的基础分位数预测。*