Search code examples
pythonconfusion-matrix

apply Iris Dataset target names to the confusion matrix


good evening, i have done KNN classifier method for iris dataset, i can show all code, but i think it is not important to post full code, only one fragment which i did not understand is how to assign iris target names to the confusion matrix? here is confusion matrix

from sklearn.metrics import confusion_matrix
print(confusion_matrix(y_test, prediction))

which returns matrix

[[13  0  0]
 [ 0 15  1]
 [ 0  0  9]]

i have searched in internet Confussion matrix

and i know that there is additional parameter labels, so i have tried

from sklearn.metrics import confusion_matrix
class_names =iris_dataset["target_names"]
print(confusion_matrix(y_test, prediction,labels=class_names))

but i got following error :

ValueError: At least one label specified must be in y_true

please help me how to fix it?


Solution

  • I went there a few months ago, here is a piece of code, try to adapt it to your needs;) original is the original dataset iris dataset and prediction is the prediction made on the classification

    I hope this will help you !

    from sklearn.metrics import confusion_matrix
    from mlxtend.plotting import plot_confusion_matrix
    
    myarray = np.asarray(original)
    matrix = confusion_matrix((myarray),(predictions+1))
    
    class_names = ['Iris-setosa', 'Iris-versicolor', 'Iris-virginica']
    
    fig, ax = plot_confusion_matrix(conf_mat=matrix,
                                    show_absolute=True,
                                    show_normed=False,
                                    colorbar=True,
                                    class_names=class_names)
    plt.title('Confusion Matrix')
    plt.show()