close

How to plot scikit learn classification report?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to plot scikit learn classification report in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to plot scikit learn classification report?

  1. How to plot scikit learn classification report?

    One issue with this visualisation is that imbalanced classes are not obvious, but are important in interpreting the results.

  2. plot scikit learn classification report

    One issue with this visualisation is that imbalanced classes are not obvious, but are important in interpreting the results.

Method 1

If you just want to plot the classification report as a bar chart in a Jupyter notebook, you can do the following.

# Assuming that classification_report, y_test and predictions are in scope...
import pandas as pd

# Build a DataFrame from the classification_report output_dict.
report_data = []
for label, metrics in classification_report(y_test, predictions, output_dict=True).items():
    metrics['label'] = label
    report_data.append(metrics)

report_df = pd.DataFrame(
    report_data, 
    columns=['label', 'precision', 'recall', 'f1-score', 'support']
)

# Plot as a bar chart.
report_df.plot(y=['precision', 'recall', 'f1-score'], x='label', kind='bar')

One issue with this visualisation is that imbalanced classes are not obvious, but are important in interpreting the results. One way to represent this is to add a version of the label that includes the number of samples (i.e. the support):

# Add a column to the DataFrame.
report_df['labelsupport'] = [f'{label} (n={support})' 
                             for label, support in zip(report_df.label, report_df.support)]

# Plot the chart the same way, but use `labelsupport` as the x-axis.
report_df.plot(y=['precision', 'recall', 'f1-score'], x='labelsupport', kind='bar')

Method 2

This works for me, pieced it together from the top answer above, also, i cannot comment but THANKS all for this thread, it helped a LOT!

def plot_classification_report(cr, title='Classification report ', with_avg_total=False, cmap=plt.cm.Blues):
    lines = cr.split('\n')
    classes = []
    plotMat = []
    for line in lines[2 : (len(lines) - 6)]: rt
        t = line.split()
        classes.append(t[0])
        v = [float(x) for x in t[1: len(t) - 1]]
        plotMat.append(v)

    if with_avg_total:
        aveTotal = lines[len(lines) - 1].split()
        classes.append('avg/total')
        vAveTotal = [float(x) for x in t[1:len(aveTotal) - 1]]
        plotMat.append(vAveTotal)

    plt.figure(figsize=(12,48))
    #plt.imshow(plotMat, interpolation='nearest', cmap=cmap) THIS also works but the scale is not good neither the colors for many classes(200)
    #plt.colorbar()

    plt.title(title)
    x_tick_marks = np.arange(3)
    y_tick_marks = np.arange(len(classes))
    plt.xticks(x_tick_marks, ['precision', 'recall', 'f1-score'], rotation=45)
    plt.yticks(y_tick_marks, classes)
    plt.tight_layout()
    plt.ylabel('Classes')
    plt.xlabel('Measures')
    import seaborn as sns
    sns.heatmap(plotMat, annot=True) 

After this, make sure class labels don’t contain any space due the splits

reportstr = classification_report(true_classes, y_pred,target_names=class_labels_no_spaces)

plot_classification_report(reportstr)

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read