如何将 Sklearn 的分类报告输出到 csv 文件中?

use*_*918 4 python classification scikit-learn

有谁知道无论如何将分类报告输出为文本文件或CSV文件?

print(metrics.classification_report(y_test, y_pred))python中的这一行给了我分类报告。我想要这份报告的csv格式。

我试图复制和粘贴,但列会混在一起!任何帮助表示赞赏!

Rab*_*iaz 9

该函数有一个参数可以解决这个确切的问题。

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)
Run Code Online (Sandbox Code Playgroud)

将字典转换为数据框后,您可以将其写入 csv,轻松绘制它,对其进行操作或其他任何操作。


mak*_*kis 2

这是可能的,但您需要创建一个函数。

假设我想将报告写入 report.csv 文件(需要在运行代码之前创建)

完整示例:

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)
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。打开csv文件可以看到:

截屏:

在此输入图像描述