sklearn DeprecationWarning数组的真值

roj*_*alo 16 python scikit-learn rasa-nlu

使用文档运行rasa_core示例

› python3 -m rasa_core.run -d models/dialogue -u models/nlu/default/current
Run Code Online (Sandbox Code Playgroud)

并在对话框中的每条消息后输出此错误:

.../sklearn/...: DeprecationWarning: The truth value of an empty array is ambiguous. Returning False, but in future this will result in an error. Use `array.size > 0` to check that an array is not empty.
Run Code Online (Sandbox Code Playgroud)

numpy的问题已修复但未在最新版本中发布:https://github.com/scikit-learn/scikit-learn/issues/10449

以下内容无法暂时使警告静音:

  1. 添加 -W ignore

python3 -W ignore -m rasa_core.run -d models/dialogue -u models/nlu/default/current

  1. warnings.simplefilter

python3

>>> warnings.simplefilter('ignore', DeprecationWarning)
>>> exit()
Run Code Online (Sandbox Code Playgroud)

python3 -m rasa_core.run -d models/dialogue -u models/nlu/default/current

Gau*_*hra 33

这个警告是由numpy引起的,它不赞成对空数组真值检查

这种变化的理由是

不可能利用空数组为False的事实,因为出于其他原因,数组可能为False.

检查以下示例:

>>> import numpy as np
>>> bool(np.array([]))
False
>>> # but this is not a good way to test for emptiness, because...
>>> bool(np.array([0]))
False
Run Code Online (Sandbox Code Playgroud)

根据关于scikit-learn库的问题10449,这已在图书馆的主分支中修复.然而,这将是在2018年8月左右可用,所以一个可能的替代是使用较小版本的numpy库,没有这个问题,即1.13.3,因为scikit-library默认会引用最新版本的numpy(1.14.2 at at写这个答案的时间)

sudo pip install numpy==1.13.3
Run Code Online (Sandbox Code Playgroud)

或者用pip3如下

sudo pip3 install numpy==1.13.3
Run Code Online (Sandbox Code Playgroud)

忽略警告

如果我们想要使用最新版本的库(在这种情况下是numpy),它给出了弃用警告并且只想使弃用警告静音,那么我们可以通过使用python的Warnings模块的filterwarnings方法来实现它.

以下示例将产生上述问题中提到的弃用警告:

from sklearn import preprocessing

if __name__ == '__main__':
    le = preprocessing.LabelEncoder()
    le.fit([1, 2, 2, 6])
    le.transform([1, 1, 2, 6])
    le.inverse_transform([0, 0, 1, 2])
Run Code Online (Sandbox Code Playgroud)

产生

/usr/local/lib/python2.7/dist-packages/sklearn/preprocessing/label.py:151:DeprecationWarning:空数组的真值是不明确的.返回False,但将来会导致错误.使用array.size > 0检查数组不为空.

为了解决这个问题,请为DeprecationWarning添加过滤警告

from sklearn import preprocessing
import warnings

if __name__ == '__main__':
    warnings.filterwarnings(action='ignore', category=DeprecationWarning)
    le = preprocessing.LabelEncoder()
    le.fit([1, 2, 2, 6])
    le.transform([1, 1, 2, 6])
    le.inverse_transform([0, 0, 1, 2])
Run Code Online (Sandbox Code Playgroud)

如果有多个模块发出警告,我们想要选择性地静默警告,那么使用模块属性.例如来自scikit学习模块的静默弃用警告

warnings.filterwarnings(module='sklearn*', action='ignore', category=DeprecationWarning)
Run Code Online (Sandbox Code Playgroud)

  • @rojobuffalo我已经编辑了答案以显示如何忽略警告。我们可以使用filterwarnings方法忽略任何类别的警告。 (2认同)