scikit将输出metrics.classification_report学习为CSV /制表符分隔格式
classification
machine-learning
python
scikit-learn
6
0

我正在Scikit-Learn中进行多类文本分类。使用具有数百个标签的多项朴素贝叶斯分类器对数据集进行训练。这是Scikit Learn脚本的摘录,用于拟合MNB模型

from __future__ import print_function

# Read **`file.csv`** into a pandas DataFrame

import pandas as pd
path = 'data/file.csv'
merged = pd.read_csv(path, error_bad_lines=False, low_memory=False)

# define X and y using the original DataFrame
X = merged.text
y = merged.grid

# split X and y into training and testing sets;
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1)

# import and instantiate CountVectorizer
from sklearn.feature_extraction.text import CountVectorizer
vect = CountVectorizer()

# create document-term matrices using CountVectorizer
X_train_dtm = vect.fit_transform(X_train)
X_test_dtm = vect.transform(X_test)

# import and instantiate MultinomialNB
from sklearn.naive_bayes import MultinomialNB
nb = MultinomialNB()

# fit a Multinomial Naive Bayes model
nb.fit(X_train_dtm, y_train)

# make class predictions
y_pred_class = nb.predict(X_test_dtm)

# generate classification report
from sklearn import metrics
print(metrics.classification_report(y_test, y_pred_class))

在命令行屏幕上,metrics.classification_report的简化输出如下所示:

             precision  recall   f1-score   support
     12       0.84      0.48      0.61      2843
     13       0.00      0.00      0.00        69
     15       1.00      0.19      0.32       232
     16       0.75      0.02      0.05       965
     33       1.00      0.04      0.07       155
      4       0.59      0.34      0.43      5600
     41       0.63      0.49      0.55      6218
     42       0.00      0.00      0.00       102
     49       0.00      0.00      0.00        11
      5       0.90      0.06      0.12      2010
     50       0.00      0.00      0.00         5
     51       0.96      0.07      0.13      1267
     58       1.00      0.01      0.02       180
     59       0.37      0.80      0.51      8127
      7       0.91      0.05      0.10       579
      8       0.50      0.56      0.53      7555      
    avg/total 0.59      0.48      0.45     35919

我想知道是否有任何方法可以将报告输出转换为带有常规列标题的标准csv文件

当我将命令行输出发送到csv文件或尝试将屏幕输出复制/粘贴到电子表格-Openoffice Calc或Excel时,它将结果汇总到一栏中。看起来像这样:

在此处输入图片说明

帮助表示赞赏。谢谢!

参考资料:
Stack Overflow
收藏
评论
共 9 个回答
高赞 时间 活跃

我们可以从precision_recall_fscore_support函数获取实际值,然后将其放入数据帧中。下面的代码将给出相同的结果,但是现在在pandas df :)中。

clf_rep = metrics.precision_recall_fscore_support(true, pred)
out_dict = {
             "precision" :clf_rep[0].round(2)
            ,"recall" : clf_rep[1].round(2)
            ,"f1-score" : clf_rep[2].round(2)
            ,"support" : clf_rep[3]
            }
out_df = pd.DataFrame(out_dict, index = nb.classes_)
avg_tot = (out_df.apply(lambda x: round(x.mean(), 2) if x.name!="support" else  round(x.sum(), 2)).to_frame().T)
avg_tot.index = ["avg/total"]
out_df = out_df.append(avg_tot)
print out_df
收藏
评论

另一种选择是计算基础数据并自行编写报告。您将获得的所有统计信息

precision_recall_fscore_support
收藏
评论

虽然先前的答案可能都有效,但我发现它们有些冗长。以下内容将单个类的结果以及摘要行存储在单个数据框中。对报告中的更改不是很敏感,但是可以帮到我。

#init snippet and fake data
from io import StringIO
import re
import pandas as pd
from sklearn import metrics
true_label = [1,1,2,2,3,3]
pred_label = [1,2,2,3,3,1]

def report_to_df(report):
    report = re.sub(r" +", " ", report).replace("avg / total", "avg/total").replace("\n ", "\n")
    report_df = pd.read_csv(StringIO("Classes" + report), sep=' ', index_col=0)        
    return(report_df)

#txt report to df
report = metrics.classification_report(true_label, pred_label)
report_df = report_to_df(report)

#store, print, copy...
print (report_df)

给出所需的输出:

Classes precision   recall  f1-score    support
1   0.5 0.5 0.5 2
2   0.5 0.5 0.5 2
3   0.5 0.5 0.5 2
avg/total   0.5 0.5 0.5 6
收藏
评论

如果您希望获得个人分数,那么应该可以完成这项工作。

import pandas as pd

def classification_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('classification_report.csv', index = False)

report = classification_report(y_true, y_pred)
classification_report_csv(report)
收藏
评论

scikit-learn v0.20开始,将分类报告转换为pandas Dataframe的最简单方法是简单地将报告作为dict返回:

report = classification_report(y_test, y_pred, output_dict=True)

然后构造一个数据框并转置它:

df = pandas.DataFrame(report).transpose()

从这里开始,您可以自由使用标准的pandas方法生成所需的输出格式(CSV,HTML,LaTeX等)。

另请参阅https://scikit-learn.org/0.20/modules/generated/sklearn.metrics.classification_report.html上的文档

收藏
评论

仅将分类报告输出为dict显然是一个更好的主意:

sklearn.metrics.classification_report(y_true, y_pred, output_dict=True)

但是,这是我制作的将所有类 (仅类)结果转换为pandas数据框的函数。

def report_to_df(report):
    report = [x.split(' ') for x in report.split('\n')]
    header = ['Class Name']+[x for x in report[0] if x!='']
    values = []
    for row in report[1:-5]:
        row = [value for value in row if value!='']
        if row!=[]:
            values.append(row)
    df = pd.DataFrame(data = values, columns = header)
    return df

希望这对您有用。

收藏
评论

只是import pandas as pd ,并确保您设置output_dict参数默认为FalseTrue计算时classification_report 。这将产生一个pandas DataFrame classification_report dictionary ,然后您可以将其传递给pandas DataFrame方法。您可能需要transpose结果DataFrame以适合所需的输出格式。然后,可以根据需要将生成的DataFrame写入csv文件。

clsf_report = pd.DataFrame(classification_report(y_true = your_y_true, y_pred = your_y_preds5, output_dict=True)).transpose()
clsf_report.to_csv('Your Classification Report Name.csv', index= True)

我希望这有帮助。

收藏
评论

连同示例输入输出一起, 这是其他函数 metrics_report_to_df() 。从Sklearn指标实施precision_recall_fscore_support应该可以:

# Generates classification metrics using precision_recall_fscore_support:
from sklearn import metrics
import pandas as pd
import numpy as np; from numpy import random

# Simulating true and predicted labels as test dataset: 
np.random.seed(10)
y_true = np.array([0]*300 + [1]*700)
y_pred = np.random.randint(2, size=1000)

# Here's the custom function returning classification report dataframe:
def metrics_report_to_df(ytrue, ypred):
    precision, recall, fscore, support = metrics.precision_recall_fscore_support(ytrue, ypred)
    classification_report = pd.concat(map(pd.DataFrame, [precision, recall, fscore, support]), axis=1)
    classification_report.columns = ["precision", "recall", "f1-score", "support"] # Add row w "avg/total"
    classification_report.loc['avg/Total', :] = metrics.precision_recall_fscore_support(ytrue, ypred, average='weighted')
    classification_report.loc['avg/Total', 'support'] = classification_report['support'].sum() 
    return(classification_report)

# Provide input as true_label and predicted label (from classifier)
classification_report = metrics_report_to_df(y_true, y_pred)

# Here's the output (metrics report transformed to dataframe )
In [1047]: classification_report
Out[1047]: 
           precision    recall  f1-score  support
0           0.300578  0.520000  0.380952    300.0
1           0.700624  0.481429  0.570703    700.0
avg/Total   0.580610  0.493000  0.513778   1000.0
收藏
评论

如此处的其中一篇文章中所述, precision_recall_fscore_supportclassification_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): 使用LibreOffice打开结果

收藏
评论
新手导航
  • 社区规范
  • 提出问题
  • 进行投票
  • 个人资料
  • 优化问题
  • 回答问题

关于我们

常见问题

内容许可

联系我们

@2020 AskGo
京ICP备20001863号