Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

confusion matrix python

from sklearn.metrics import confusion_matrix
conf_mat = confusion_matrix(y_test, y_pred)
sns.heatmap(conf_mat, square=True, annot=True, cmap='Blues', fmt='d', cbar=False)
Comment

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)
Comment

confusion matrix python code

from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_predicted)
cm
# after creating the confusion matrix, for better understaning plot the cm.
import seaborn as sn
plt.figure(figsize = (10,7))
sn.heatmap(cm, annot=True)
plt.xlabel('Predicted')
plt.ylabel('Truth')
Comment

confusion matrix python

from sklearn.metrics import accuracy_score
from sklearn.metrics import classification_report, confusion_matrix

print(confusion_matrix(y_test, y_pred_test.round()))
print(classification_report(y_test, y_pred_test.round()))

# Output:
[[99450   250]
 [ 4165 11192]]
              precision    recall  f1-score   support

           0       0.96      1.00      0.98     99700
           1       0.98      0.73      0.84     15357

    accuracy                           0.96    115057
   macro avg       0.97      0.86      0.91    115057
weighted avg       0.96      0.96      0.96    115057
Comment

how to get confusion matrix in python

from sklearn.metrics import confusion_matrix
conf_mat = confusion_matrix(y_test, y_pred)
Comment

confusion matrix python

df_confusion = pd.crosstab(y_actu, y_pred, rownames=['Actual'], colnames=['Predicted'], margins=True)
Comment

Create confusion matrix manually using python

import matplotlib.pyplot as plt
import numpy
from sklearn import metrics

confusion_matrix = numpy.array([[  6,  94, 10],[ 80, 821 , 100], [ 80, 821 , 10]])

cm_display = metrics.ConfusionMatrixDisplay(confusion_matrix = confusion_matrix, display_labels = ['Sat', 'Sun', 'Mon'])

cm_display.plot()
plt.show()
Comment

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.]])

Comment

PREVIOUS NEXT
Code Example
Python :: return key from value dictionary python 
Python :: graph outlier detection 
Python :: pytesseract.image_to 
Python :: split long list into chunks of 100 
Python :: random forest 
Python :: how to convert user integer input to string in python 
Python :: semaphore in python 
Python :: how to add virtual environment in vscode 
Python :: set password django 
Python :: python check for exception 
Python :: join tables pandas 
Python :: import os python 
Python :: if then else python 
Python :: how to inherit a class in python 
Python :: when to use map function in python 
Python :: IndexError: list assignment index out of range 
Python :: upload image to s3 python 
Python :: Issue AttributeError: ‘numpy.ndarray’ object has no attribute ‘index’ 
Python :: python tuples 
Python :: fizzbuzz program in python 
Python :: django filter on related field 
Python :: import turtle 
Python :: python 4 release date 
Python :: read header of csv file python 
Python :: python multiclass inheritance with inputs 
Python :: print statements 
Python :: how to add two strings in python 
Python :: google oauth python tutorial 
Python :: Python Projects for Beginners: A Ten-Week Bootcamp Approach to Python Programming 
Python :: This code is supposed to display "2 + 2 = 4" on the screen, but there is an error. Find the error in the code and fix it, so that the output is correct. 
ADD CONTENT
Topic
Content
Source link
Name
2+3 =