不一致的形状错误y_test上的MultiLabelBinarizer,sklearn多标签分类

时间:2017-06-21 08:51:28

标签: numpy scikit-learn text-classification multilabel-classification

import numpy as np
import pandas as pd
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.svm import LinearSVC
from sklearn.linear_model import SGDClassifier
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.multiclass import OneVsRestClassifier
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
from sklearn.svm import SVC

data = r'C:\Users\...\Downloads\news_v1.xlsx'

df = pd.read_excel(data)
df = pd.DataFrame(df.groupby(["id", "doc"]).label.apply(list)).reset_index()

X = np.array(df.doc)
y = np.array(df.label)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)

mlb = preprocessing.MultiLabelBinarizer()
Y_train = mlb.fit_transform(y_train)

classifier = Pipeline([
('vectorizer', CountVectorizer()),
('tfidf', TfidfTransformer()),
('clf', OneVsRestClassifier(LinearSVC()))])

classifier.fit(X_train, Y_train)
predicted = classifier.predict(X_test)

Y_test = mlb.fit_transform(y_test)

print("Y_train: ", Y_train.shape)
print("Y_test: ", Y_test.shape)
print("Predicted: ", predicted.shape)
print("Accuracy Score: ", accuracy_score(Y_test, predicted))

我似乎无法进行任何测量,因为在使用MultiLabelBinarizer进行fit_transform后,Y_test会给出不同的矩阵维度。

结果和错误:

Y_train:  (1278, 49)
Y_test:  (630, 42)
Predicted:  (630, 49)
Traceback (most recent call last):
  File "C:/Users/../PycharmProjects/MultiAutoTag/classifier.py", line 41, in <module>
    print("Accuracy Score: ", accuracy_score(Y_test, predicted))
  File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\metrics\classification.py", line 174, in accuracy_score
    differing_labels = count_nonzero(y_true - y_pred, axis=1)
  File "C:\ProgramData\Anaconda3\lib\site-packages\scipy\sparse\compressed.py", line 361, in __sub__
    raise ValueError("inconsistent shapes")
ValueError: inconsistent shapes

查看打印的Y_test,形状与其他形状不同。我做错了什么以及为什么MultiLabelBinarizer为Y_test返回不同的大小? 感谢您的帮助!

修改 新错误:

Traceback (most recent call last):
  File "C:/Users/../PycharmProjects/MultiAutoTag/classifier.py", line 47, in <module>
    Y_test = mlb.transform(y_test)
  File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\preprocessing\label.py", line 763, in transform
    yt = self._transform(y, class_to_index)
  File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\preprocessing\label.py", line 787, in _transform
    indices.extend(set(class_mapping[label] for label in labels))
  File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\preprocessing\label.py", line 787, in <genexpr>
    indices.extend(set(class_mapping[label] for label in labels))
KeyError: 'Sanction'

这就是y_test的样子:

print(y_test)

[['App'] ['Contract'] ['Pay'] ['App'] 
 ['App'] ['App']
 ['Reports'] ['Reports'] ['Executive', 'Pay']
 ['Change'] ['Reports']
 ['Reports'] ['Issue']]

1 个答案:

答案 0 :(得分:0)

您只应在测试数据上调用transform()。从不fit()或其变体如fit_transform()fit_predict()等。它们只应用于训练数据。

所以换行:

Y_test = mlb.fit_transform(y_test)

Y_test = mlb.transform(y_test)

<强>解释

当您致电fit()fit_transform()时,mlb会忘记之前的学习数据并了解新提供的数据。如果Y_trainY_test在标签中可能存在差异,则可能会出现问题。

在您的情况下,Y_train有49种不同的标签,而Y_test只有42种不同的标签。但这并不意味着Y_test是短Y_train的7个标签。 Y_test可能有完全不同的标签集,当二值化时会产生42列,这会影响结果。