[英]using warnings.filterwarnings() to convert a warning into an exception
I want to programatically capture when statsmodels.api.OLS raises its "The smallest eigenvalue is..." warning我想以编程方式捕获 statsmodels.api.OLS 引发其“最小特征值是......”警告
This would enable me to filter a large number of OLS systems by whether or not they raise this warning这将使我能够通过它们是否发出此警告来过滤大量 OLS 系统
Ideally, I would like to pick off just particular warnings instead of a blanket filter for any/all warnings理想情况下,我想只选择特定的警告,而不是针对任何/所有警告的全面过滤器
My attempt (below) attempts a blanket filter using warnings.filterwarnings(), it doesn't work我的尝试(如下)尝试使用warnings.filterwarnings()进行全面过滤,但它不起作用
How do I get warnings.filterwarnings() to work?如何让 warnings.filterwarnings() 工作? Or is there some other module I should be looking at instead?
还是我应该查看其他一些模块?
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')
You can get the smallest eigenvalue using model.eigenvals[-1]
, just check that it is less than 1e-10
to raise an exception.您可以使用
model.eigenvals[-1]
获得最小的特征值,只需检查它是否小于1e-10
即可引发异常。 Here's the source that generates the note这是生成注释的来源
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.