当statsmodels.api.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')发布于 2022-01-11 03:20:46
您可以使用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)https://stackoverflow.com/questions/70661024
复制相似问题