【问题标题】:Python - Replacing warnings with a simple messagePython - 用简单的消息替换警告
【发布时间】:2016-07-10 03:07:21
【问题描述】:

我已经从sklearn 构建了一些现成的分类器,并且在一些预期的情况下,我知道分类器肯定会表现不佳并且无法正确预测任何事情。 sklearn.svm 包运行时没有错误,但会引发以下警告。

~/anaconda/lib/python3.5/site-packages/sklearn/metrics/classification.py:1074: UndefinedMetricWarning: F-score is ill-defined and being set to 0.0 due to no predicted samples.
  'precision', 'predicted', average, warn_for)

我希望禁止显示此警告,而是替换为发送至stdout 的消息,例如"poor classifier performance"

一般有什么方法可以抑制warnings

【问题讨论】:

    标签: python warnings suppress


    【解决方案1】:

    使用-Wignore 可以轻松抑制所有警告(请参阅warning flag docs

    warnings 模块可以对过滤器进行一些微调(忽略您的警告类型)。

    捕获只是您的警告(假设模块中没有一些 API 来调整它)并使用warnings.catch_warnings context manager 和改编自"Testing Warnings" 的代码来做一些特殊的事情:

    import warnings
    
    class MyWarning(Warning):
        pass
    
    def something():
        warnings.warn("magic warning", MyWarning)
    
    with warnings.catch_warnings(record=True) as w:
        # Trigger a warning.
        something()
        # Verify some things
        if ((len(w) == 1) 
                and issubclass(w[0].category, MyWarning) 
                and "magic" in str(w[-1].message)):
            print('something magical')
    

    【讨论】:

    • 那行得通。我决定捕获 sn-p 可以生成的所有警告,并使用通用消息进行报告。 with warnings.catch_warnings(record=True) as w: self.clfObj.fit(self.train_x,self.train_y) self.preds = list(self.clfObj.predict(self.test_x)) self.predProbabs = self.clfObj.predict_proba(self.test_x)[:,1] self.evalClassifierPerf() if len(w) >= 1: print("Poor Classifer detected")
    猜你喜欢
    • 2018-02-08
    • 1970-01-01
    • 2017-10-27
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 2021-01-19
    • 1970-01-01
    相关资源
    最近更新 更多