【发布时间】:2018-11-11 18:32:04
【问题描述】:
我正在尝试从 Python 中的 sklearn.metrics 运行 accuracy_score。我的真实 y 和预测 y 都是稀疏矩阵格式 --
import scipy.sparse as sp
from sklearn.metrics import accuracy_score
y_true = sp.csr_matrix(y.values) # where y is a multi-label dataframe
y_pred = model.predict(X) # X is same format as y_true
accuracy_score(y_true, y_pred)
我收到以下错误:
TypeError: len() of unsized object
我检查了documentation ,它应该能够接受稀疏矩阵。
为了清楚起见,当我尝试查看内容时,我得到以下两者:
[In] y_true
[Out] <9646x1248 sparse matrix of type '<class 'numpy.int64'>'
with 36700 stored elements in Compressed Sparse Row format>
[In] y_pred
[Out] <9646x1248 sparse matrix of type '<class 'numpy.int64'>'
with 373603 stored elements in Compressed Sparse Row format>
为什么我会收到此错误以及如何修复我的输入?
【问题讨论】:
-
你怎么知道
y_true或y_pred的类型有问题?根据您提供的少量信息,它可能在其他地方。我们需要部分或全部错误回溯来正确识别它正在谈论的对象。 -
对于
accuracy_score文档中的示例数组accuracy_score(np.array([[0, 1], [1, 1]]), np.ones((2, 2))),如果将它们转换为csr,它就可以工作。你的矩阵是什么让它们在密集时起作用,但在csr时不起作用? -
显然
accuracy_score使用sklearn.utils.multiclass.type_of_target检查输入的类型。当稀疏矩阵未通过sklearn.utils.multiclass.is_multilabel测试时会产生此错误。密集数组 (ndarray) 可以满足其他条件。我通过查看回溯和相关代码推断出这一点。
标签: python scipy scikit-learn typeerror sparse-matrix