![](/img/trans.png)
[英]why I cannot suppress warning with regex using 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.