ARTICLE DETAIL

资讯详情

深耕网站视觉设计与运营推广的一线实战洞察。

sktime 异常与警告体系解析:NotEvaluatedError、NotFittedError 与 FitFailedWarning 的源码级使用指南

sktime 异常与警告体系解析:NotEvaluatedError、NotFittedError 与 FitFailedWarning 的源码级使用指南 sktime 异常与警告体系解析NotEvaluatedError、NotFittedError 与 FitFailedWarning 的源码级使用指南【免费下载链接】sktimeA unified framework for machine learning with time series项目地址: https://gitcode.com/GitHub_Trending/sk/sktimesktime 的异常与警告体系集中在sktime/exceptions.py模块中它为整个时间序列机器学习框架提供了三个关键成员NotEvaluatedError、NotFittedError与FitFailedWarning。本文以该模块为主线结合基准评估、模型选择、交叉验证等核心子系统的源码调用系统讲解这三个成员的设计意图、类层次结构、触发场景与正确使用方法帮助读者在开发自定义估计器estimator或编排评估实验时写出语义准确、易于调试的异常与警告处理代码。一、模块概览sktime 自定义异常与警告的入口在sktime中异常与警告并非散落在各处临时抛出而是统一收敛在sktime/exceptions.py这个出口模块中。该模块的文档字符串只有一句话——Custom exceptions and warnings但其定位非常明确作为框架统一的异常与警告出口供全仓库所有子模块基准测试、模型选择、模型评估、深度学习封装等引用。模块顶层通过__all__显式声明对外公开的 API__all__ [NotEvaluatedError, NotFittedError, FitFailedWarning]__all__的声明意味着from sktime.exceptions import *只会导入这三个名字这也是docs/source/api_reference/exceptions.rst中 autosummary 所列三项与之一一对应的原因。该文档页通过 Sphinx 的automodule与autosummary机制为sktime.exceptions中的每个类自动生成独立的 API 参考页toctree: auto_generated/并指定class.rst模板渲染类文档。值得注意的是模块作者标记为__author__ [mloning]说明这三个异常/警告类从框架早期便确立是 sktime 异常体系的基础构件。二、异常与警告的三个核心成员2.1 NotEvaluatedError评估器尚未评估时的语义化报错class NotEvaluatedError(ValueError, AttributeError): NotEvaluatedError. Exception class to raise if evaluator is used before having evaluated any metric. NotEvaluatedError同时继承ValueError与AttributeError两个内建异常。这种多重继承的设计使得调用方既可以用except ValueError从参数/状态非法的角度捕获也可以用except AttributeError从对象状态尚未就绪的角度捕获兼顾了两类常见的使用直觉。它的触发场景由文档字符串定义得非常清晰当评估器evaluator在被使用前尚未评估过任何指标时抛出。其典型实现位于sktime/benchmarking/evaluation.py中的_check_is_evaluated方法def _check_is_evaluated(self): Check if evaluator has evaluated any metrics. if len(self._metric_names) 0: raise NotEvaluatedError( This evaluator has not evaluated any metric yet. Please call evaluate with the appropriate arguments before using this method. )从这段源码可以推断出其使用契约任何依赖已评估指标的实例方法如获取排名、绘制临界差图等都必须先调用_check_is_evaluated()做前置校验一旦发现_metric_names为空即从未调用过evaluate便以NotEvaluatedError中断并给出可操作的提示信息——告知用户请先以合适的参数调用 evaluate 方法。2.2 NotFittedError未拟合估计器被使用时的统一报错from skbase._exceptions import NotFittedErrorsktime.exceptions.NotFittedError并非在 sktime 内定义而是直接复用了skbase库中同名异常sktime 的估计器基类体系建立在skbase之上因此异常体系也随之复用再经sktime.exceptions作为框架统一出口重新导出。这样做的好处是全仓库各子模块只需from sktime.exceptions import NotFittedError而无需关心其底层来自skbase。NotFittedError的语义在 scikit-learn 生态中已是约定俗成当对尚未fit的估计器调用predict、transform、forecast等需要已学习参数的方法时抛出。在 sktime 中它被广泛使用例如时序分类器sktime/classification/sklearn/_continuous_interval_tree.py在predict/predict_proba等阶段检查内部estimator_是否已拟合未拟合则抛出NotFittedError。网格搜索sktime/forecasting/model_selection/_base.py当所有参数组合在交叉验证中拟合全部失败、导致最优索引无效时抛出if self.best_index_ -1: raise NotFittedError( fAll fits of forecaster failed, set error_scoreraise to see the exceptions. Failed forecaster: {self.forecaster} )贝叶斯优化的ForecastingOptunaSearchCV与ForecastingSKoptSearchCVsktime/forecasting/model_selection/_optuna.py、sktime/forecasting/model_selection/_skopt.py、面板数据的_tune.pysktime/base/_panel/_tune.py也都沿用同一模式。此外框架级测试套件sktime/tests/test_all_estimators.py与sktime/forecasting/tests/test_all_forecasters.py会以NotFittedError作为未拟合时调用预测方法应报错的断言基准这意味着所有进入框架测试的估计器都必须遵循未 fit 即用则抛 NotFittedError的约定。2.3 FitFailedWarning拟合失败但不中断实验的告警class FitFailedWarning(RuntimeWarning): Warning class used if there is an error while fitting the estimator. This Warning is used in meta estimators GridSearchCV and RandomizedSearchCV and the cross-validation helper function cross_val_score to warn when there is an error while fitting the estimator. FitFailedWarning(Estimator fit failed. The score on this train-test partition for these parameters will be set to 0.000000). References ---------- .. [1] Based on scikit-learns FitFailedWarning FitFailedWarning继承自RuntimeWarning用于估计器拟合过程中出现错误的场景。其设计初衷文档字符串已明确在元估计器如GridSearchCV、RandomizedSearchCV和交叉验证辅助函数cross_val_score中当某个训练-测试划分上的拟合失败时不中断整个实验而是降级处理——将该划分的得分置为占位值如 0.0 或 NaN并通过告警告知用户。该设计明确标注参考References自 scikit-learn 的FitFailedWarning。其实际抛出方式可以看预测器评估函数sktime/forecasting/model_evaluation/_functions.py中evaluate的核心逻辑except Exception as e: if error_score raise: raise e else: # assign default value when fitting failed ... warnings.warn( f In evaluate, fitting of forecaster {type(forecaster).__name__} failed, you can set error_scoreraise in evaluate to see the exception message. Fit failed for the {i}-th data split, on training data y_train with cutoff {cutoff}, and len(y_train){len(y_train)}. The score will be set to {error_score}. Failed forecaster with parameters: {forecaster}. , FitFailedWarning, stacklevel2, )分类器评估函数sktime/classification/model_evaluation/_functions.py采用完全相同的模式。由此可以总结出FitFailedWarning的两个关键使用要点与error_score参数联动当error_scoreraise时原始异常被重新抛出便于调试当error_score为数值或np.nan默认值时失败结果被吞掉、以占位得分写入结果表同时触发FitFailedWarning。告警信息高度可操作消息中包含失败估计器类型名、失败发生的第 i 个数据划分、训练数据长度、cutoff、占位得分以及完整的估计器参数方便事后定位是哪个参数组合导致失败。同样的告警还贯穿模型选择全链路例如ForecastingGridSearchCVsktime/forecasting/model_selection/_gridsearch.py、随机搜索sktime/forecasting/model_selection/_randomsearch.py、_hyperactive.py以及分类/回归侧的_tune.py其文档字符串均声明若拟合失败将触发 FitFailedWarning。三、三个成员的关系与设计哲学从sktime/exceptions.py的源码可以提炼出三个成员在设计上的分工与关联成员基类语义定位典型抛出方NotEvaluatedErrorValueError, AttributeError评估器在使用前尚未评估任何指标sktime/benchmarking/evaluation.pyNotFittedError来自skbase未拟合估计器被调用预测/变换等方法各类估计器、网格/随机/贝叶斯搜索FitFailedWarningRuntimeWarning拟合失败但不中断实验得分降级evaluate系列、各类搜索 CV 元估计器其设计哲学可以归纳为三点区分异常与警告编程错误未评估就用、未拟合就用用Exception直接中断属于必须修复的状态错误而单次拟合失败在批量搜索场景中是可容忍的降级事件用Warning提示而不中断保证GridSearchCV这类需要遍历全部参数组合的流程能跑完。统一的导入出口NotFittedError本身来自skbase但通过sktime.exceptions重新导出后整个仓库只依赖这一个内部入口避免各模块各自引入外部依赖。信息驱动调试无论是NotEvaluatedError的请先调用 evaluate、NotFittedError的设置 error_scoreraise 查看异常还是FitFailedWarning中的失败划分与参数详情都在抛出时尽可能给出下一步行动指引。四、在自定义估计器与实验脚本中使用这套体系4.1 在自定义估计器中抛出 NotFittedError开发自定义估计器时应遵循 scikit-learn/skbase 的约定在predict等依赖拟合状态的方法入口处校验self.is_fitted或内部估计器属性未拟合即抛出NotFittedErrorfrom sktime.exceptions import NotFittedError class MyForecaster: def fit(self, y, XNone, fhNone): # ... 学习模型参数 self._is_fitted True return self def predict(self, fh, XNone): if not self._is_fitted: raise NotFittedError( This forecaster has not been fitted yet. Please call fit with appropriate arguments before using predict. ) # ... 返回预测这样你的估计器便能通过sktime/tests/test_all_estimators.py中未拟合即用应报错的框架级契约检查。4.2 在评估实验中正确处理拟合失败使用evaluate进行时间序列交叉验证时可借助error_score与FitFailedWarning控制失败行为import warnings from sktime.exceptions import FitFailedWarning from sktime.forecasting.model_evaluation import evaluate # 默认行为拟合失败置为 NaN 并发出 FitFailedWarning with warnings.catch_warnings(): warnings.simplefilter(always, FitFailedWarning) results evaluate(forecaster, cvmy_cv, yy, XX, scoringscoring) # 需要精确调试时任何拟合失败都会原样抛出异常 results evaluate(forecaster, cvmy_cv, yy, XX, scoringscoring, error_scoreraise)其中error_score的语义为raise时直接抛出底层异常否则以给定数值默认np.nan作为失败划分的得分并触发FitFailedWarning。4.3 捕获异常时的类型选择由于NotEvaluatedError同时继承ValueError与AttributeError捕获时可根据语义需要选择from sktime.benchmarking.evaluation import Evaluator from sktime.exceptions import NotEvaluatedError evaluator Evaluator(...) # 尚未调用 evaluate try: evaluator.plot() # 内部会触发 _check_is_evaluated except NotEvaluatedError as e: print(请先评估指标, e) # 也等价于 except ValueError 或 except AttributeError五、API 参考与进一步阅读三个成员的定义与__all__导出sktime/exceptions.pyAPI 参考文档页本主题对应的官方文档docs/source/api_reference/exceptions.rstNotEvaluatedError的抛出实现sktime/benchmarking/evaluation.pyFitFailedWarning的典型抛出逻辑sktime/forecasting/model_evaluation/_functions.py、sktime/classification/model_evaluation/_functions.pyNotFittedError的典型抛出逻辑sktime/forecasting/model_selection/_base.py、sktime/classification/sklearn/_continuous_interval_tree.py框架级未拟合即用应抛错契约测试sktime/tests/test_all_estimators.py、sktime/forecasting/tests/test_all_forecasters.py理解并善用这套异常与警告体系是参与 sktime 估计器开发与实验编排的基本功它既保证了错误被显式暴露的代码健壮性也保证了批量搜索实验不被单点失败打断的工程可用性。【免费下载链接】sktimeA unified framework for machine learning with time series项目地址: https://gitcode.com/GitHub_Trending/sk/sktime创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表