[英]catching warnings from numpy and scipy with try except
I'm fitting an ExponentialSmoothing model from statsmodels with version 0.10.1 (statsmodels.tsa.holtwinters.ExponentialSmoothing) - I have to do this repeatedly on groups in a pandas groupby object, but the point is I'm looping through datasets to fit每组数据上一个新的 model。
在循环的某些迭代(但不是全部)中,statsmodels 会引发 ConvergenceWarning 或 RuntimeWarning,我想捕获这些警告并将它们记录在预测旁边的结果 dataframe 中。
我尝试使用警告上下文管理器,这样我就可以像异常一样发出警告,并添加了 try/except 块
这种方法的问题在于,如果其中一个警告被捕获,则 model 实际上不适合,因为 try 块被跳过,最糟糕的是,我最终预测使用 model 适合之前的迭代。
import pandas as pd
from statsmodels.tsa.holtwinters import ExponentialSmoothing, HoltWintersResults
from statsmodels.tools.sm_exceptions import ConvergenceWarning
import numpy as np
from loguru import logger
concat_region_keys = []
forecast_result_dfs = []
region_df_groups = deseasonalized_search_counts \
.sort_index() \
.groupby('region_id') \
['region_deseasonalized_observations']
with warnings.catch_warnings():
warnings.simplefilter("error")
for i, (region_id, df_region_group) in enumerate(region7_df_groups):
concat_region_keys.append(region_id)
region_guard_rail = df_region_group.iloc[-1] # most recent observation
err_msg = np.nan
try:
holt_winters_result_object = ExponentialSmoothing(endog=df_region_group).fit()
except ConvergenceWarning as ce:
logger.warning(f"{i} region {region_id}: ConvergenceWarning {ce}")
err_msg = f"ConvergenceWarning: {ce}"
except RuntimeWarning as re:
logger.warning(f"{i} region {region_id}: RuntimeWarning {re}")
err_msg = f"RuntimeWarning: {re}"
forecast_result = holt_winters_result_object \
.forecast(periods_ahead) \
.assign(
fit_call_warning=err_msg,
)
forecast_result_dfs.append(forecast_result)
对于循环的每次迭代,使用 try/except 或其他一些 python 构造的正确方法是什么?
一个问题是这个
“在循环的某些迭代中,但不是全部,statsmodels 会引发 ConvergenceWarning 或 RuntimeWarning,我想捕获这些警告并将它们记录在预测旁边的结果 dataframe 中。”
您无法捕获引发错误的预测,错误是 function 的 output。 您可以将预测保存到发生错误的那一点。 你需要决定在你的 model 抛出这样的错误之后你想做什么。 您可以像@ALollz 所说的那样继续使用,或者您可以转到下一个您想要适应的组,但这是您需要做出的决定。 无论是放弃在装配时出现错误的系列还是决定继续前进,这是一种设计选择,我们无法为您决定。
检查这个网站https://www.programcreek.com/python/example/369/warnings.filterwarnings
使用with
语句
with warnings.catch_warnings():
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.