我在Scikit-Learn中进行多类文本分类。使用具有数百个标签的Multinomial Naive Bayes分类器训练数据集。这是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时,它会将结果整合到一列中。看起来像这样:
帮助表示感谢。谢谢!
答案 0 :(得分:11)
如果你想要个人得分,这应该可以胜任。
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)
答案 1 :(得分:8)
从scikit-learn
v0.20开始,将分类报告转换为pandas
数据框的最简单方法是简单地将报告返回为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
上的文档答案 2 :(得分:7)
我们可以从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
答案 3 :(得分:6)
虽然之前的答案可能都有效但我发现它们有点冗长。以下内容将单个类结果以及摘要行存储在单个数据框中。对报告中的变化不是很敏感,但对我来说就是诀窍。
#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
答案 4 :(得分:3)
正如此处的其中一篇文章所述,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格式(请参阅here以获取其他分隔符格式,如sep =';'):
df_class_report.to_csv('my_csv_file.csv', sep=',')
我使用LibreOffice Calc打开my_csv_file.csv
(尽管您可以使用任何表格/电子表格编辑器,如excel):
答案 5 :(得分:2)
另一个选择是计算基础数据并自行编写报告。
您将获得的所有统计数据precision_recall_fscore_support
答案 6 :(得分:1)
除了示例输入输出外, 还有另一个功能 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
答案 7 :(得分:1)
我还发现一些答案有点冗长。这是我的三线解决方案,正如其他人所建议的那样使用avatar at bottom left > team name > Settings > Find integrations > Bitbucket Notebook Viewer > Add
。
precision_recall_fscore_support
答案 8 :(得分:0)
这是我的2类(pos,neg)分类的代码
report = metrics.precision_recall_fscore_support(true_labels,predicted_labels,labels=classes)
rowDicionary["precision_pos"] = report[0][0]
rowDicionary["recall_pos"] = report[1][0]
rowDicionary["f1-score_pos"] = report[2][0]
rowDicionary["support_pos"] = report[3][0]
rowDicionary["precision_neg"] = report[0][1]
rowDicionary["recall_neg"] = report[1][1]
rowDicionary["f1-score_neg"] = report[2][1]
rowDicionary["support_neg"] = report[3][1]
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writerow(rowDicionary)
答案 9 :(得分:0)
def to_table(report):
report = report.splitlines()
res = []
res.append(['']+report[0].split())
for row in report[2:-2]:
res.append(row.split())
lr = report[-1].split()
res.append([' '.join(lr[:3])]+lr[3:])
return np.array(res)
返回一个numpy数组,该数组可以转换为pandas数据帧或只保存为csv文件。
答案 10 :(得分:0)
我修改了@kindjacket的答案。 试试这个:
import collections
def classification_report_df(report):
report_data = []
lines = report.split('\n')
del lines[-5]
del lines[-1]
del lines[1]
for line in lines[1:]:
row = collections.OrderedDict()
row_data = line.split()
row_data = list(filter(None, row_data))
row['class'] = row_data[0] + " " + row_data[1]
row['precision'] = float(row_data[2])
row['recall'] = float(row_data[3])
row['f1_score'] = float(row_data[4])
row['support'] = int(row_data[5])
report_data.append(row)
df = pd.DataFrame.from_dict(report_data)
df.set_index('class', inplace=True)
return df
您可以使用熊猫将df导出到csv
答案 11 :(得分:0)
我不知道您是否仍然需要解决方案,但这是我最好的做法,可以将其保持为完美格式并仍然保存:
def classifcation_report_processing(model_to_report):
tmp = list()
for row in model_to_report.split("\n"):
parsed_row = [x for x in row.split(" ") if len(x) > 0]
if len(parsed_row) > 0:
tmp.append(parsed_row)
# Store in dictionary
measures = tmp[0]
D_class_data = defaultdict(dict)
for row in tmp[1:]:
class_label = row[0]
for j, m in enumerate(measures):
D_class_data[class_label][m.strip()] = float(row[j + 1].strip())
save_report = pd.DataFrame.from_dict(D_class_data).T
path_to_save = os.getcwd() +'/Classification_report.xlsx'
save_report.to_excel(path_to_save, index=True)
return save_report.head(5)
saving_CL_report_naive_bayes = classifcation_report_processing(classification_report(y_val, prediction))
答案 12 :(得分:0)
我遇到了同样的问题,将 metrics.classification_report 的字符串输出粘贴到google工作表或excel中,然后通过自定义5个空格将文本拆分为列。
答案 13 :(得分:0)
只需import pandas as pd
,并确保在计算output_dict
时将False
参数(默认为True
设置为classification_report
。这将产生一个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)
我希望这会有所帮助。
答案 14 :(得分:0)
最好将分类报告输出为 dict :
sklearn.metrics.classification_report(y_true, y_pred, output_dict=True)
但这是我制作的用于将所有类(仅限类)结果转换为熊猫数据框的功能。
def report_to_csv(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 None
希望这对您来说很好。
答案 15 :(得分:0)
我发现的最简单,最好的方法是:
classes = ['class 1','class 2','class 3']
report = classification_report(Y[test], Y_pred, target_names=classes)
report_path = "report.txt"
text_file = open(report_path, "w")
n = text_file.write(report)
text_file.close()
答案 16 :(得分:0)
绝对值得使用:
sklearn.metrics.classification_report(y_true, y_pred, output_dict=True)
但是Yash Nag对该函数的稍微修改版本如下。该函数包括精度、宏精度和加权精度行以及类:
def classification_report_to_dataframe(str_representation_of_report):
split_string = [x.split(' ') for x in str_representation_of_report.split('\n')]
column_names = ['']+[x for x in split_string[0] if x!='']
values = []
for table_row in split_string[1:-1]:
table_row = [value for value in table_row if value!='']
if table_row!=[]:
values.append(table_row)
for i in values:
for j in range(len(i)):
if i[1] == 'avg':
i[0:2] = [' '.join(i[0:2])]
if len(i) == 3:
i.insert(1,np.nan)
i.insert(2, np.nan)
else:
pass
report_to_df = pd.DataFrame(data=values, columns=column_names)
return report_to_df
可以找到测试分类报告的输出here
答案 17 :(得分:-3)