ValueError with sklearn metrics.average_precision_score

314 views Asked by At

I'm trying to use metrics.average_precision_score to calculate the average_precision of my sklearn KNN model, my code is like this:

average_precision = metrics.average_precision_score(y_test.values, np.array(y_pre.tolist))

But I get this error:

...
File "C:\My software\Anaconda\lib\site-packages\sklearn\metrics\_ranking.py", line 211, in average_precision_score
    "y_true." % pos_label)
ValueError: pos_label=1 is invalid. Set it to a label in y_true.

To check my y_test and y_pre, I used:

print(type(y_test))
print(type(y_test.values))
print(type(y_pre))
print(y_test.values)
print(y_pre)

I got result:

<class 'pandas.core.series.Series'>
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
[3 3 3 3 3 2 3 3 3 2 2 3 3 2 3 3 3 2 3 2 3 3 3 2 3 2 3 3 3 3 3 2 2 3 2 3 3
 3 3 2 3 2 3 3 2 3 3 3 2 3 3 3 3 2 3 3 3 3 2 3 3 3 3 3 3 2 3 3 2 3 3 3 3 3
 3 3 3 3 2 3 3 2 2 3 3 3 3 3 3 3 3 3 2 3 3 3 3 3 3 3 2 3 3 2 3 2 3 3 2 2 3
 2 3 2 2 3 2 3 3]
[3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
 3 3 3 3 3 3 3 3]

I have no idea why this can't work, please help me, thank you.

1

There are 1 answers

1
Henrique Branco On BEST ANSWER

Map your labels to 0 and 1 in y_test.values and y_pre instead of 3 and 2.

Remember: 1 must be the positive label.