I think there is a desire to output the classification result to a CSV file using sklearn.metrics.classification_report. I will. That's why I created a sample code to output a CSV file, so please have a look.
classification_report2csv.py
import numpy as np
import pandas as pd
from sklearn.metrics import classification_report
# https://scikitlearn.org/stable/modules/generated/sklearn.metrics.classification_report.html
y_true = np.array([0, 1, 2, 2, 2])
y_pred = np.array([0, 0, 2, 2, 1])
target_names = ['class 0', 'class 1', 'class 2']
report = classification_report(y_pred=y_pred, y_true=y_true,
target_names=target_names, output_dict=True)
#Transposed to make the metrics name header
report_df = pd.DataFrame(report).T
report_df
"""
precision recall f1-score support
class 0 0.5 1.000000 0.666667 1.0
class 1 0.0 0.000000 0.000000 1.0
class 2 1.0 0.666667 0.800000 3.0
accuracy 0.6 0.600000 0.600000 0.6
macro avg 0.5 0.555556 0.488889 5.0
weighted avg 0.7 0.600000 0.613333 5.0
"""
# index=Note that if set to False, the label name will disappear.
report_df.to_csv("report.csv")
pd.read_csv("report.csv", index_col=0)
"""
precision recall f1-score support
class 0 0.5 1.000000 0.666667 1.0
class 1 0.0 0.000000 0.000000 1.0
class 2 1.0 0.666667 0.800000 3.0
accuracy 0.6 0.600000 0.600000 0.6
macro avg 0.5 0.555556 0.488889 5.0
weighted avg 0.7 0.600000 0.613333 5.0
"""
Recommended Posts