Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

confusion_matrix - too many values to unpack

I'm trying to use the confusion_matrix function, as follows:

tn, fp, fn, tp = confusion_matrix(y_true, y_predict).ravel()

y_true and y_predict are both lists. When I return their shape, I get: (71,).

I'm however getting the following error for the above statement:

ValueError: too many values to unpack

I'm not sure if it is because of the second (empty) dimension in (71,)? I'm not sure how to remove it if it is the issue here.

Any thoughts?

Thanks.

like image 212
Simplicity Avatar asked Oct 19 '25 17:10

Simplicity


2 Answers

You can only assign multiple variables dynamically if the number of outputs is certain. If you assign the result of confusion_matrix to a single variable, you can then check its contents in a loop and assign the contents conditionally:

returned = confusion_matrix(y_true, y_predict).ravel()

for var in returned:
    #... do stuff with each item in the returned collection

You could also just check its length and if it is 4, you can proceed as usual:

if len(returned) == 4:
    tn, fp, fn, tp = returned
like image 173
JacobIRR Avatar answered Oct 21 '25 07:10

JacobIRR


The line you're trying to execute tn, fp, fn, tp = confusion_matrix(y_true, y_predict).ravel() is valid only if you have 2 classes in output (binary classification). However, the error you get is an indicator that you have more than 2 classes (multi-class classification). In this case, there's no meaning of tn, fp, fn, tp. Instead you can visualize the confusion matrix (e.g. by using heatmap).

like image 31
Abdulwahab Almestekawy Avatar answered Oct 21 '25 08:10

Abdulwahab Almestekawy