Search code examples
pythonscipyscikit-learntypeerrorsparse-matrix

Type error with sklearn's accuracy_score function


I am trying to run accuracy_score from sklearn.metrics in Python. My true y's and predicted y's are both in sparse matrix format --

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)

I get the following error:

TypeError: len() of unsized object

I checked the documentation and it should be able to accept sparse matrices.

Just for clarity, when I try to look at the contents, I get the following for both:

[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>

Why am I getting this error and how do I fix my input?


Solution

  • Convert matrices into regular matrix y_pred = y_pred.A and y_true = y_true.A, then compute accuracy_score(y_true, y_pred)