How to generate classification report and confusion matrix in Python?
0

How to generate classification report and confusion matrix in Python?

This recipe helps you generate classification report and confusion matrix in Python
In [1]:
## How to generate classification report and confusion matrix in Python
def Snippet_138():
    print()
    print(format('How to generate classification report & confusion matrix in Python','*^82'))

    import warnings
    warnings.filterwarnings("ignore")

    # load libraries
    from sklearn import datasets
    from sklearn.tree import DecisionTreeClassifier
    from sklearn.model_selection import train_test_split
    from sklearn.metrics import classification_report, confusion_matrix

    # Load data
    iris = datasets.load_iris()
    X = iris.data
    y = iris.target

    # Create list of target class names
    class_names = iris.target_names

    # Create training and test set
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33)

    # Create DecisionTree model
    classifier = DecisionTreeClassifier()

    # Train model and make predictions
    y_hat = classifier.fit(X_train, y_train).predict(X_test)

    # Create a classification report
    print()
    print(classification_report(y_test, y_hat, target_names=class_names))

    # Create a confusion matrix
    print()
    print(confusion_matrix(y_test, y_hat))

Snippet_138()
********How to generate classification report & confusion matrix in Python********

              precision    recall  f1-score   support

      setosa       1.00      1.00      1.00        15
  versicolor       1.00      0.80      0.89        15
   virginica       0.87      1.00      0.93        20

   micro avg       0.94      0.94      0.94        50
   macro avg       0.96      0.93      0.94        50
weighted avg       0.95      0.94      0.94        50


[[15  0  0]
 [ 0 12  3]
 [ 0  0 20]]