数组的 sklearn DeprecationWarning 真值

sklearn DeprecationWarning truth value of an array

运行 来自文档的 rasa_core 示例

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

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

.../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.

这是 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()

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

此警告是由 numpy 引起的,它弃用了 truth value check on empty array

此更改的理由是

It is impossible to take advantage of the fact that empty arrays are False, because an array can be False for other reasons.

检查以下示例:

>>> 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

解决方案

根据 scikit-learn 库中的 issue 10449,这已在库的 master 分支中修复。然而,它将在 2018 年 8 月左右可用,因此一种可能的替代方法是使用没有此问题的较小版本的 numpy 库,即 1.13.3,因为 scikit-library 默认情况下会引用最新版本的 numpy(即 1.14。 2 在撰写此答案时)

sudo pip install numpy==1.13.3

或者用 pip3 如下

sudo pip3 install numpy==1.13.3

忽略警告

如果我们想使用给出弃用警告的最新版本的库(在本例中为 numpy),并且只想使弃用警告静音,那么我们可以使用 filterwarnings method of python's Warnings 模块

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

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])

产生

/usr/local/lib/python2.7/dist-packages/sklearn/preprocessing/label.py:151: 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.

要处理它,请为 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])

如果有多个模块发出警告,而我们想要有选择地静默警告,则使用 module 属性。例如从 scikit 学习模块

静默弃用警告
warnings.filterwarnings(module='sklearn*', action='ignore', category=DeprecationWarning)

我也遇到了同样的问题。以下解决方案对我有用。 转到警告中提到的路径文件和行号,如果您使用 anaconda,则转到 Anaconda\envs\py2\Lib\site-packages\sklearn\preprocessing\label.py 行 number:151.

更改以下代码

if diff:
    raise ValueError("y contains new labels: %s" % str(diff))

以下

if diff.size>0:
    raise ValueError("y contains new labels: %s" % str(diff))