pandas - 获取 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)
解决方案
您试图从矩阵中获取长度,这是模棱两可的:
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 个值的矩阵。您需要在这里重新考虑您的代码。
推荐阅读
- javascript - 我的 Servlet 端点返回 JSON,但我的 AXIOS 函数没有运行并为我的网页获取它
- python - 在 python cmd.Cmd 中绘制图表
- json - 如何将 timestamp_ms 转换为常规时间戳?
- reactjs - 在 React 上使用 Algolia 的无限滚动
- javascript - 基于 String 属性对对象数组进行排序
- reactjs - 打字稿反应 | 在变量上添加“as const”在操场和 IDE(VSCode、WebStorm)中具有不同的行为
- flutter - 错误:“RequestOptions”类型的值不能分配给“Future”类型的变量
' - c++ - 在文档中运行代码时,restbed 库为 request->get_header 发出错误
- java - Tesseract OCR 的 Java 变量问题
- angular - 如何在angular8中取消订阅行为主题