Answers for "how to print confusion matrix in python"

7

confusion matrix python

By definition, entry i,j in a confusion matrix is the number of 
observations actually in group i, but predicted to be in group j. 
Scikit-Learn provides a confusion_matrix function:

from sklearn.metrics import confusion_matrix
y_actu = [2, 0, 2, 2, 0, 1, 1, 2, 2, 0, 1, 2]
y_pred = [0, 0, 2, 1, 0, 2, 1, 0, 2, 0, 2, 2]
confusion_matrix(y_actu, y_pred)
# Output
# array([[3, 0, 0],
#        [0, 1, 2],
#        [2, 1, 3]], dtype=int64)
Posted by: Guest on April-24-2020
1

how to find the labels of the confusion matrix in python

""" In order to find the labels just use the Counter function to count 
the records from y_test and then check row-wise sum of the confusion 
matrix. Then apply the labels to the corresponding rows using the 
inbuilt seaborn plot as shown below"""

from collections import Counter
Counter(y_test).keys()
Counter(y_test).values()

import seaborn as sns
import matplotlib.pyplot as plt     

ax= plt.subplot()
sns.heatmap(cm, annot=True, fmt='g', ax=ax);  #annot=True to annotate cells, ftm='g' to disable scientific notation

# labels, title and ticks
ax.set_xlabel('Predicted labels');ax.set_ylabel('True labels'); 
ax.set_title('Confusion Matrix'); 
ax.xaxis.set_ticklabels(['business', 'health']); ax.yaxis.set_ticklabels(['health', 'business']);
Posted by: Guest on May-23-2021
2

confusion matrix python

df_confusion = pd.crosstab(y_actu, y_pred, rownames=['Actual'], colnames=['Predicted'], margins=True)
Posted by: Guest on January-18-2021
0

compute confusion matrix using python

import numpy as np

currentDataClass = [1, 3, 3, 2, 5, 5, 3, 2, 1, 4, 3, 2, 1, 1, 2]
predictedClass = [1, 2, 3, 4, 2, 3, 3, 2, 1, 2, 3, 1, 5, 1, 1]

def comp_confmat(actual, predicted):

    classes = np.unique(actual) # extract the different classes
    matrix = np.zeros((len(classes), len(classes))) # initialize the confusion matrix with zeros

    for i in range(len(classes)):
        for j in range(len(classes)):

            matrix[i, j] = np.sum((actual == classes[i]) & (predicted == classes[j]))

    return matrix

comp_confmat(currentDataClass, predictedClass)

array([[3., 0., 0., 0., 1.],
       [2., 1., 0., 1., 0.],
       [0., 1., 3., 0., 0.],
       [0., 1., 0., 0., 0.],
       [0., 1., 1., 0., 0.]])
Posted by: Guest on December-20-2020

Code answers related to "how to print confusion matrix in python"

Python Answers by Framework

Browse Popular Code Answers by Language