python - 拟合训练数据后获取值错误 'The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()'

标签 python multilabel-classification

我不断收到ValueError:“具有多个元素的数组的真值不明确。在拟合之前分为训练集和测试集的数据时,请使用 a.any() 或 a.all()'。如何解决此错误?

我已经通过使用 shape 属性并打印每个 X,y 列车和测试集的头部来检查数据是否正确分割。

data - 是一个 DataFrame,由一个“文本”列和六个标签列组成。
特征X - 矢量化文本
标签 y - 标签
data[['text']] - 是向量的 DataFrame
data [ ['1' ,'2' , '3' , '4' ,'5','6' ] ] - 标签的 DataFrame

更新
问题确实出在我的原始数据上,因为我的一些向量的形状确实扭曲了(例如(19,1))。方法 flatten() 似乎解决了该问题,因为它返回折叠成一维的数组的副本。

这是我分割数据的方法:

from sklearn.model_selection import train_test_split

X_test, X_train, y_test, y_train = train_test_split(data[['text']],data [ ['1'  ,'2' ,  '3' , '4' ,'5','6' ] ] , random_state=42, test_size=0.30, shuffle=True)

这是配件部分:

my_classifier = LabelPowerset(classifier = RandomForestClassifier(n_estimators=100),require_dense = [False, True])
my_classifier.fit(X_train, y_train)
print(X_test.shape)
print(X_train.shape)
print(y_test.shape)
print(y_train.shape)

输出:

(111699, 1)
(47872, 1)
(111699, 6)
(47872, 6)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-94-a59b7690b804> in <module>()
----> 1 my_classifier.fit(X_train, y_train)

~\Anaconda3\lib\site-packages\skmultilearn\problem_transform\lp.py in fit(self, X, y)
    136         """
    137         X = self._ensure_input_format(
--> 138             X, sparse_format='csr', enforce_sparse=True)
    139 
    140         self.classifier.fit(self._ensure_input_format(X),

~\Anaconda3\lib\site-packages\skmultilearn\base\base.py in _ensure_input_format(self, X, sparse_format, enforce_sparse)
     95                 return X
     96             else:
---> 97                 return matrix_creation_function_for_format(sparse_format)(X)
     98 
     99     def _ensure_output_format(self, matrix, sparse_format='csr', enforce_sparse=False):

~\Anaconda3\lib\site-packages\scipy\sparse\compressed.py in __init__(self, arg1, shape, dtype, copy)
     77                         self.format)
     78             from .coo import coo_matrix
---> 79             self._set_self(self.__class__(coo_matrix(arg1, dtype=dtype)))
     80 
     81         # Read matrix dimensions given, if any

~\Anaconda3\lib\site-packages\scipy\sparse\coo.py in __init__(self, arg1, shape, dtype, copy)
    183                     self._shape = check_shape(M.shape)
    184 
--> 185                 self.row, self.col = M.nonzero()
    186                 self.data = M[self.row, self.col]
    187                 self.has_canonical_format = True

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
X_train.head(5)

输出:

                                                  text
119105  [0.070629984, 0.09145695, 0.026743168, -0.0247...
131631  [0.15062076, 0.1616201, -0.24214625, -0.079838...
125326  [0.29536337, 0.148198, 0.19248627, 0.21796156,...
111256  [0.16876991, 0.035899613, -0.06388393, -0.2339...
83590   [0.14012083, 0.08112805, -0.079143375, -0.0808...
y_train.head(5)

输出:

        1   2   3   4   5   6
2783    0   0   0   0   0   0
109183  0   0   0   0   0   0
96229   0   0   0   0   0   0
128796  1   0   1   0   1   0
103592  0   0   0   0   0   0

整个向量在 X_train 中每行的样子:

[ 4.0938530e-02  2.0466107e-01  2.3541172e-01 -2.2121635e-01
 -1.6204901e-01 -2.3460600e-01  9.9785912e-01 -2.0803943e-01
 -9.1773011e-02  7.8154532e-03 -4.5910537e-02  1.6967587e-01
 -4.1978297e+00 -2.0136276e-01  1.3398567e-03  6.2967308e-02
  2.1797931e-01 -3.2942373e-01 -1.3567382e-01 -3.2139298e-01
 -1.1644501e-01  3.7298296e-02 -3.3780817e-02 -1.4053656e-01
 -2.2851831e-01]
y_train.all()

输出:

1     False
2     False
3     False
4     False
5     False
6     False
dtype: bool
y_train.any()

输出:

1     True
2     True
3     True
4     True
5     True
6     True
dtype: bool

最佳答案

这源于您的数据格式。看起来您的 X_train 只有两列:ID 列和 text 列,其中是一个数组。您需要拆分文本列以类似于 y_train 的格式。

要理解错误消息,请考虑以下内容:

bool(5)
# True
bool(0)
# False

现在,如果您尝试将数组(您的数据)转换为 bool,它将如何计算?

>>> a = np.array([3, 12, 5, 0, 2, 0])
>>> a.any()
True
>>> a.all()
False
>>> bool(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

正如错误告诉您的那样,它是不明确的。使用 a.any() 检查是否有任何元素为 True,使用 a.all() 检查所有元素是否为 true。

现在回到最初的问题:错误发生在预构建的 sklearn 函数中,这是一个提示,您放入其中的数据格式错误(与某些函数的先决条件)。 sklearn 模块端的错误应该很少见。

编辑:我实际上很确定数据格式是问题所在。如果您遵循堆栈跟踪,则在检查非零值 self.row, self.col = M.nonzero() 时,_ensure_input_format() 中会发生错误.

编辑2:针对提供的数据调整解决方案。

关于python - 拟合训练数据后获取值错误 'The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55952979/

相关文章:

python - 从截断的正态分布中抽样

r - 使用 e1071 (SVM) 进行文本分类

python - 使用 scikit learn 对文本进行多标签分类

machine-learning - 二元交叉熵惩罚 one-hot 向量的所有分量

python - Selenium WebDriver等待但仍然是 "Element is not clickable at point"

java - if item *in* array java

python - 转换 pandas 数据框以用于 MultiLabelBinarizer

python - 分类 : skewed data within a class

python - 匹配邮件中自然文本的算法

python - 在 Python 2.7 中执行 http 请求时使用 'while True'