hierarchicalforecast API完全参考:核心类与方法使用手册

hierarchicalforecast API完全参考:核心类与方法使用手册

【免费下载链接】hierarchicalforecastProbabilistic Hierarchical forecasting 👑 with statistical and econometric methods.项目地址: https://gitcode.com/gh_mirrors/hi/hierarchicalforecast

分层预测是现代时间序列分析中的关键技术,而HierarchicalForecast库提供了最先进的概率分层预测解决方案。本文将为您提供完整的API参考手册,帮助您掌握这个强大工具的核心功能。无论您是数据科学家、业务分析师还是时间序列预测工程师,这份手册都将成为您日常工作的得力助手。

🎯 核心概念与架构

HierarchicalForecast库采用模块化设计,主要包含以下核心模块:

  • 核心类HierarchicalReconciliation- 主协调类
  • 协调方法BottomUp,TopDown,MiddleOut,MinTrace,ERM
  • 概率方法Normality,Bootstrap,PERMBU,Conformal
  • 评估工具evaluate函数
  • 实用工具aggregate,SMatrix,HierarchicalPlot

📊 核心类详解

HierarchicalReconciliation 类

这是库的核心入口点,负责协调所有预测方法。位于 hierarchicalforecast/core.py 文件中的HierarchicalReconciliation类是整个框架的枢纽。

初始化方法:

from hierarchicalforecast.core import HierarchicalReconciliation # 创建协调器实例 reconcilers = [ BottomUp(), TopDown(method='forecast_proportions'), MiddleOut(middle_level='Country/Purpose/State', top_down_method='forecast_proportions'), MinTrace(method='mint_shrink') ] hrec = HierarchicalReconciliation(reconcilers=reconcilers)

主要方法:

  • reconcile()- 执行协调预测
  • bootstrap_reconcile()- 使用自助法进行概率协调

协调方法类

所有协调方法都继承自HReconciler基类,位于 hierarchicalforecast/methods.py。每个方法都有独特的适用场景:

1. BottomUp 方法
from hierarchicalforecast.methods import BottomUp # 自底向上方法 - 简单累加 bottom_up = BottomUp()
2. TopDown 方法
from hierarchicalforecast.methods import TopDown # 自顶向下方法 - 多种分配策略 top_down = TopDown(method='forecast_proportions') # 预测比例法 top_down = TopDown(method='average_proportions') # 平均比例法 top_down = TopDown(method='proportion_averages') # 比例平均法
3. MiddleOut 方法
from hierarchicalforecast.methods import MiddleOut # 中间向外方法 - 结合上下策略 middle_out = MiddleOut( middle_level='Country/Purpose/State', top_down_method='forecast_proportions' )
4. MinTrace 方法
from hierarchicalforecast.methods import MinTrace # 最小迹方法 - 最小化预测方差 min_trace = MinTrace(method='mint_shrink') # 收缩协方差估计 min_trace = MinTrace(method='mint_ols') # OLS估计 min_trace = MinTrace(method='mint_wls') # WLS估计 min_trace = MinTrace(method='mint_wls_var') # WLS方差估计
5. ERM 方法
from hierarchicalforecast.methods import ERM # 经验风险最小化方法 - L1正则化 erm = ERM(lambda_reg=0.5, nonnegative=False)

🔧 概率协调方法

HierarchicalForecast提供了多种概率预测方法,支持不确定性量化:

1. Normality 方法

基于正态性假设,使用MinTrace方差-协方差闭式矩阵:

# 在协调时指定间隔方法 Y_rec_df = hrec.reconcile( Y_hat_df=Y_hat_df, Y_df=Y_train_df, S_df=S_df, tags=tags, intervals_method='normality', level=[80, 95] )

2. Bootstrap 方法

使用Gamakumara的自助法生成分层协调预测分布:

Y_rec_df = hrec.reconcile( Y_hat_df=Y_hat_df, Y_df=Y_train_df, S_df=S_df, tags=tags, intervals_method='bootstrap', level=[80, 95], num_samples=1000 )

3. PERMBU 方法

通过估计秩置换copula重新注入多变量依赖关系:

Y_rec_df = hrec.reconcile( Y_hat_df=Y_hat_df, Y_df=Y_train_df, S_df=S_df, tags=tags, intervals_method='permbu', level=[80, 95], num_samples=1000 )

4. Conformal 方法

基于共形预测的无分布预测区间:

Y_rec_df = hrec.reconcile( Y_hat_df=Y_hat_df, Y_df=Y_train_df, S_df=S_df, tags=tags, intervals_method='conformal', level=[80, 95] )

📈 评估与验证

evaluate() 函数

位于 hierarchicalforecast/evaluation.py 的评估函数支持多层级评估:

from hierarchicalforecast.evaluation import evaluate from utilsforecast.losses import mse, mae, rmse # 评估协调预测 evaluation = evaluate( df=df, tags=tags, metrics=[mse, mae, rmse], models=['AutoARIMA', 'Naive', 'BottomUp', 'TopDown'], benchmark='Naive', agg_fn='mean' )

支持的评估指标:

  • mse- 均方误差
  • mae- 平均绝对误差
  • rmse- 均方根误差
  • mase- 平均绝对标度误差
  • rmae- 相对平均绝对误差
  • mape- 平均绝对百分比误差

🛠️ 实用工具函数

1. aggregate() 函数

从底层序列构建聚合序列:

from hierarchicalforecast.utils import aggregate # 创建聚合序列 Y_df, S_df, tags = aggregate( df=bottom_df, spec=spec_dict, agg_fn='sum' )

2. SMatrix 类

处理求和矩阵的核心工具:

from hierarchicalforecast.utils import SMatrix # 创建求和矩阵 S = SMatrix(spec=spec_dict)

3. HierarchicalPlot 类

可视化分层结构和预测结果:

from hierarchicalforecast.utils import HierarchicalPlot # 创建可视化对象 plotter = HierarchicalPlot(Y_df, S_df, tags) plotter.plot_forecasts(Y_hat_df, models=['AutoARIMA', 'BottomUp'])

🚀 完整工作流程示例

步骤1:准备数据

import pandas as pd import numpy as np from datasetsforecast.hierarchical import HierarchicalData # 加载分层数据集 Y_df, S_df, tags = HierarchicalData.load('./data', 'TourismSmall') Y_df['ds'] = pd.to_datetime(Y_df['ds']) S_df = S_df.reset_index(names="unique_id") # 分割训练测试集 Y_test_df = Y_df.groupby('unique_id').tail(4) Y_train_df = Y_df.drop(Y_test_df.index)

步骤2:生成基础预测

from statsforecast.core import StatsForecast from statsforecast.models import AutoARIMA, Naive # 计算基础预测 fcst = StatsForecast( models=[AutoARIMA(season_length=4), Naive()], freq='QE', n_jobs=-1 ) Y_hat_df = fcst.forecast(df=Y_train_df, h=4)

步骤3:协调预测

from hierarchicalforecast.core import HierarchicalReconciliation from hierarchicalforecast.methods import BottomUp, TopDown, MinTrace # 配置协调器 reconcilers = [ BottomUp(), TopDown(method='forecast_proportions'), MinTrace(method='mint_shrink') ] hrec = HierarchicalReconciliation(reconcilers=reconcilers) # 执行协调 Y_rec_df = hrec.reconcile( Y_hat_df=Y_hat_df, Y_df=Y_train_df, S_df=S_df, tags=tags, intervals_method='normality', level=[80, 95] )

步骤4:评估结果

from hierarchicalforecast.evaluation import evaluate from utilsforecast.losses import mse, mae # 合并测试数据 df = Y_rec_df.merge(Y_test_df, on=['unique_id', 'ds']) # 评估性能 evaluation = evaluate( df=df, tags=tags, metrics=[mse, mae], models=['AutoARIMA', 'Naive', 'BottomUp', 'TopDown', 'MinTrace'], benchmark='Naive' )

🔍 高级功能与技巧

1. 时间分层协调

# 时间分层协调 Y_rec_df = hrec.reconcile( Y_hat_df=Y_hat_df, S_df=S_df, tags=tags, temporal=True, id_time_col='temporal_id' )

2. 自定义线程控制

from hierarchicalforecast.utils import set_num_threads, get_num_threads # 设置OpenMP线程数 set_num_threads(4) current_threads = get_num_threads() print(f"当前线程数: {current_threads}")

3. 稀疏矩阵优化

对于大规模分层结构,使用稀疏方法提高性能:

from hierarchicalforecast.methods import BottomUpSparse, TopDownSparse, MinTraceSparse # 使用稀疏版本 reconcilers = [ BottomUpSparse(), TopDownSparse(method='forecast_proportions'), MinTraceSparse(method='mint_shrink') ]

📊 性能优化建议

  1. 数据预处理:确保时间序列数据格式正确,缺失值已处理
  2. 方法选择:根据数据规模和结构选择合适的方法
  3. 内存管理:对于大型数据集,使用稀疏矩阵方法
  4. 并行计算:利用多线程加速计算
  5. 缓存机制:重复使用已拟合的协调器

🎯 最佳实践

1. 方法选择指南

  • 小规模数据:所有方法都适用
  • 中等规模:推荐MinTraceERM
  • 大规模数据:使用稀疏版本或BottomUp
  • 需要概率区间:使用BootstrapPERMBU

2. 参数调优

# MinTrace方法参数调优 min_trace = MinTrace( method='mint_shrink', # 协方差估计方法 nonnegative=False, # 是否强制非负 covariance_estimator='lw' # 协方差估计器 ) # ERM方法参数调优 erm = ERM( lambda_reg=0.5, # L1正则化强度 nonnegative=True, # 非负约束 solver='clarabel' # 优化求解器 )

3. 错误处理

try: Y_rec_df = hrec.reconcile( Y_hat_df=Y_hat_df, Y_df=Y_train_df, S_df=S_df, tags=tags ) except ValueError as e: print(f"输入数据错误: {e}") except NotImplementedError as e: print(f"方法不支持: {e}") except Exception as e: print(f"其他错误: {e}")

📚 学习资源与扩展

官方文档

  • 核心API文档:docs/core.html.md
  • 方法文档:docs/methods.html.md
  • 概率方法文档:docs/probabilistic_methods.html.md
  • 评估文档:docs/evaluation.html.md
  • 工具文档:docs/utils.html.md

示例笔记本

项目包含丰富的示例笔记本,位于nbs/examples/目录:

  • introduction.ipynb- 入门教程
  • tourismlarge-evaluation.ipynb- 大规模旅游数据评估
  • probabilistic-reconciliation-comparison.ipynb- 概率方法比较
  • reconciliationdiagnostics.ipynb- 协调诊断

🎉 总结

HierarchicalForecast提供了完整的分层预测解决方案,从基础协调方法到高级概率预测。通过本API参考手册,您应该能够:

  1. 理解核心类的功能和使用方法
  2. 选择合适的协调策略
  3. 实现概率预测和不确定性量化
  4. 评估和比较不同方法的性能
  5. 优化大规模数据集的预测流程

无论您是处理销售预测、库存管理还是资源规划,HierarchicalForecast都能为您提供可靠、一致且可解释的分层预测结果。开始使用这个强大的工具,提升您的预测准确性和业务决策质量!

【免费下载链接】hierarchicalforecastProbabilistic Hierarchical forecasting 👑 with statistical and econometric methods.项目地址: https://gitcode.com/gh_mirrors/hi/hierarchicalforecast

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考