如此处的其中一篇文章中所述, precision_recall_fscore_support
与classification_report
类似。
然后,只需使用python库pandas
即可轻松地将数据格式化为列格式,类似于classification_report
那样。这是一个例子:
import numpy as np
import pandas as pd
from sklearn.metrics import classification_report
from sklearn.metrics import precision_recall_fscore_support
np.random.seed(0)
y_true = np.array([0]*400 + [1]*600)
y_pred = np.random.randint(2, size=1000)
def pandas_classification_report(y_true, y_pred):
metrics_summary = precision_recall_fscore_support(
y_true=y_true,
y_pred=y_pred)
avg = list(precision_recall_fscore_support(
y_true=y_true,
y_pred=y_pred,
average='weighted'))
metrics_sum_index = ['precision', 'recall', 'f1-score', 'support']
class_report_df = pd.DataFrame(
list(metrics_summary),
index=metrics_sum_index)
support = class_report_df.loc['support']
total = support.sum()
avg[-1] = total
class_report_df['avg / total'] = avg
return class_report_df.T
使用classification_report
您将获得类似以下内容的信息:
print(classification_report(y_true=y_true, y_pred=y_pred, digits=6))
输出:
precision recall f1-score support
0 0.379032 0.470000 0.419643 400
1 0.579365 0.486667 0.528986 600
avg / total 0.499232 0.480000 0.485248 1000
然后使用我们的自定义功能pandas_classification_report
:
df_class_report = pandas_classification_report(y_true=y_true, y_pred=y_pred)
print(df_class_report)
输出:
precision recall f1-score support
0 0.379032 0.470000 0.419643 400.0
1 0.579365 0.486667 0.528986 600.0
avg / total 0.499232 0.480000 0.485248 1000.0
然后只需将其保存为csv格式(其他分隔符格式请参见此处 ,例如sep =';'):
df_class_report.to_csv('my_csv_file.csv', sep=',')
我使用LibreOffice Calc打开my_csv_file.csv
(尽管您可以使用任何表格或电子表格编辑器,例如excel):
0
我正在Scikit-Learn中进行多类文本分类。使用具有数百个标签的多项朴素贝叶斯分类器对数据集进行训练。这是Scikit Learn脚本的摘录,用于拟合MNB模型
在命令行屏幕上,metrics.classification_report的简化输出如下所示:
我想知道是否有任何方法可以将报告输出转换为带有常规列标题的标准csv文件
当我将命令行输出发送到csv文件或尝试将屏幕输出复制/粘贴到电子表格-Openoffice Calc或Excel时,它将结果汇总到一栏中。看起来像这样:
帮助表示赞赏。谢谢!