How to output Classification Report of Sklearn into a csv file?

Viewed 23238

Does anyone know is there anyway to output the classification report as the text file or CSV file?

This line print(metrics.classification_report(y_test, y_pred)) in python gives me the classification report. I want to have this report in csv format.

I tried to copy and paste but the the columns would be lumped together! Any help appreciated!

5 Answers

The function has a parameter which solves this exact problem.

import pandas as pd
from sklearn.metrics import classification_report

report_dict = classification_report(y_true, y_pred, output_dict=True)
pd.DataFrame(report_dict)

After converting the dictionary into a dataframe, you can write it to a csv, easily plot it, do operations on it or whatever.

To have a csv similar to the output of classification report, you can use this:

    labels = list(set(targcol))
    report_dict = classification_report(targcol, predcol, output_dict=True)
    repdf = pd.DataFrame(report_dict).round(2).transpose()
    repdf.insert(loc=0, column='class', value=labels + ["accuracy", "macro avg", "weighted avg"])
    repdf.to_csv("results.csv", index=False)
Related