首页 > 解决方案 > 获取 TypeError:稀疏矩阵长度不明确;在进行多类分类时使用 getnnz() 或 shape[0]

问题描述

from sklearn.naive_bayes import CategoricalNB
from sklearn.datasets import make_multilabel_classification
X, y = make_multilabel_classification(sparse = True, n_labels = 15,
return_indicator = 'sparse', allow_unlabeled = False)
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.25,random_state=0)

我尝试使用 X.todense() 但仍然出现错误。

X_train = X_train.todense()
X_test = X_test.todense()

在数据集上训练

from skmultilearn.adapt import MLkNN
from sklearn.metrics import accuracy_score
classifier = MLkNN(k=20)
classifier.fit(X_train, y_train)

预测训练数据集的输出。

y_pred = classifier.predict(X_test)
accuracy_score(y_test,y_pred)
np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)),1)

标签: pandasmachine-learningscikit-learntypeerrormulticlass-classification

解决方案


您试图从矩阵中获取长度,这是模棱两可的:

len(y_pred)

您的矩阵 y_pred 具有维度 (25,5),如y_pred.shape.

len(y_pred)因此,您可以使用代替y_pred.shape[0],这将返回 25。

但是你在使用的时候会遇到问题y_pred.reshape(y_pred.shape[0],1)

ValueError: 无法将大小为 125 的数组重新整形为形状 (25, 1)

(以前y_pred.reshape(len(y_pred),1):)

这个错误是有道理的,因为您试图将具有 125 个值的矩阵重塑为只有 25 个值的矩阵。您需要在这里重新考虑您的代码。


推荐阅读