首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用warnings.filterwarnings()将警告转换为异常

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

Stack Overflow用户
提问于 2022-01-11 02:36:28
回答 1查看 123关注 0票数 0

当statsmodels.api.OLS提出它的“最小特征值是.”时,我想以编程方式捕获它。警告

这将使我能够过滤大量的苏丹生命线行动系统,无论它们是否提出这一警告。

理想情况下,我只想取出特定的警告,而不是任何/所有警告的毯子过滤器。

我的尝试(下面)使用warnings.filterwarnings()尝试毯子过滤器,它不起作用

如何让warnings.filterwarnings()工作?或者我应该看的是其他模块吗?

代码语言:javascript
复制
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')
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-11 03:20:46

您可以使用model.eigenvals[-1]得到最小的特征值,只需检查引发异常的值是否小于1e-10。下面是生成便条的来源

代码语言:javascript
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70661024

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档