【问题标题】:sklearn: Turning off warningssklearn:关闭警告
【发布时间】:2015-05-19 03:10:38
【问题描述】:

当我使用 1 列 python pandas DataFrame(不是 Series 对象)拟合 sklearnLogisticRegression 时,我收到此警告:

/Library/Python/2.7/site-packages/sklearn/preprocessing/label.py:125:         
DataConversionWarning: A column-vector y was passed when a 1d array was 
expected. Please change the shape of y to (n_samples, ), for example using 
ravel().
y = column_or_1d(y, warn=True)

我知道我可以很容易地在我的代码中宣传这个警告,但是我怎样才能关闭这些警告呢?

【问题讨论】:

标签: python pandas warnings scikit-learn


【解决方案1】:

你可以用这个:

import warnings
from sklearn.exceptions import DataConversionWarning
warnings.filterwarnings(action='ignore', category=DataConversionWarning)

【讨论】:

  • 虽然这可能会回答这个问题,但最好解释一下答案的基本部分,以及 OPs 代码可能存在什么问题。
  • @pirho OP 可能已经知道问题的原因,并明确提到希望仅关闭警告而不是解决“问题”。
  • 值得一提的是必须import warnings
  • 如何禁用收敛警告,例如,对于使用 sklearn 的坐标下降算法的估计器?将上面的 DataConversionWarning 替换为 ConvergenceWarning 不起作用。
【解决方案2】:

实际上,警告会告诉你到底是什么问题:

您传递了一个二维数组,该数组恰好采用(X, 1) 的形式,但该方法需要一个一维数组并且必须采用(X, ) 的形式。

此外,警告会告诉您如何转换为所需的形式:y.ravel()。因此,与其取消警告,不如将其删除。

【讨论】:

    【解决方案3】:

    正如here所发布的,

    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        # Do stuff here
    

    感谢上面的 Andreas 发布链接。

    【讨论】:

    • 导入警告
    猜你喜欢
    • 1970-01-01
    • 2018-08-26
    • 2011-04-05
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-04
    • 2019-03-14
    相关资源
    最近更新 更多