繁体   English   中英

使用 warnings.filterwarnings() 将警告转换为异常

[英]using warnings.filterwarnings() to convert a warning into an exception

我想以编程方式捕获 statsmodels.api.OLS 引发其“最小特征值是......”警告

这将使我能够通过它们是否发出此警告来过滤大量 OLS 系统

理想情况下,我想只选择特定的警告,而不是针对任何/所有警告的全面过滤器

我的尝试(如下)尝试使用warnings.filterwarnings()进行全面过滤,但它不起作用

如何让 warnings.filterwarnings() 工作? 还是我应该查看其他一些模块?

import statsmodels.api as sm
import numpy as np
import pandas as pd
import warnings

np.random.seed(123)

nrows = 100

colA = np.random.uniform(0.0, 1.0, nrows)
colB = np.random.uniform(0.0 ,1.0, nrows)
colC = colA + colB  # multicolinear data to generate ill-conditioned system
y = colA + 2 * colB + np.random.uniform(0.0, 0.1, nrows)
X = pd.DataFrame({'colA': colA, 'colB': colB, 'colC': colC})

warnings.filterwarnings('error')  # achieves nothing

warnings.simplefilter('error')
# from https://stackoverflow.com/questions/59961735/cannot-supress-python-warnings-with-warnings-filterwarningsignore
# also achieves nothing

try:
    model = sm.OLS(y, sm.add_constant(X)).fit()
    print(model.summary())
except:
    print('warning successfully captured in try-except')

您可以使用model.eigenvals[-1]获得最小的特征值,只需检查它是否小于1e-10即可引发异常。 这是生成注释的来源

errstr = ("The smallest eigenvalue is %6.3g. This might indicate that there are\n"
          "strong multicollinearity problems or that the design matrix is singular.")
try:
    model = sm.OLS(y, sm.add_constant(X)).fit()
    assert model.eigenvals[-1] >= 1e-10, (errstr % model.eigenvals[-1])
    print(model.summary())
except AssertionError as e:
    print('warning successfully captured in try-except. Message below:')
    print(e)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM