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!
A Classification report is used to measure the quality of predictions from a classification algorithm. How many predictions are True and how many are False. More specifically, True Positives, False Positives, True negatives and False Negatives are used to predict the metrics of a classification report as shown below.
The F1 score is a weighted harmonic mean of precision and recall such that the best score is 1.0 and the worst is 0.0. F1 scores are lower than accuracy measures as they embed precision and recall into their computation.
A classification report is a performance evaluation metric in machine learning. It is used to show the precision, recall, F1 Score, and support of your trained classification model. If you have never used it before to evaluate the performance of your model then this article is for you.
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.
It is possible but you need to create a function.
Let's say that I want to write the report to my report.csv file (this need to be created before running the code)
Full Example:
from sklearn.metrics import classification_report
import csv
import pandas as pd
y_true = [0, 1, 2, 2, 2]
y_pred = [0, 0, 2, 2, 1]
target_names = ['class 0', 'class 1', 'class 2']
def classifaction_report_csv(report):
report_data = []
lines = report.split('\n')
for line in lines[2:-3]:
row = {}
row_data = line.split(' ')
row['class'] = row_data[0]
row['precision'] = float(row_data[1])
row['recall'] = float(row_data[2])
row['f1_score'] = float(row_data[3])
row['support'] = float(row_data[4])
report_data.append(row)
dataframe = pd.DataFrame.from_dict(report_data)
dataframe.to_csv('report.csv', index = False)
#call the classification_report first and then our new function
report = classification_report(y_true, y_pred, target_names=target_names)
classifaction_report_csv(report)
Hope this helps. Open the csv file and see:
Screenshot:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With