【问题标题】:Getting TypeError: sparse matrix length is ambiguous; use getnnz() or shape[0] while doing multi class classification获取 TypeError:稀疏矩阵长度不明确;在进行多类分类时使用 getnnz() 或 shape[0]
【发布时间】:2020-12-08 19:03:33
【问题描述】:
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)

【问题讨论】:

    标签: pandas machine-learning scikit-learn typeerror multiclass-classification


    【解决方案1】:

    您正试图从一个模棱两可的矩阵中获取长度:

    len(y_pred)
    

    您的矩阵 y_pred 的维度为 (25,5),如 y_pred.shape 所示。

    因此,您可以使用y_pred.shape[0],而不是len(y_pred),它会返回25。

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

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

    (原:y_pred.reshape(len(y_pred),1)

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

    【讨论】:

      猜你喜欢
      • 2020-07-30
      • 2015-04-03
      • 2019-08-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-07
      • 2015-07-28
      • 1970-01-01
      • 2015-06-18
      相关资源
      最近更新 更多