Python 如何绘制scikit学习分类报告?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28200786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to plot scikit learn classification report?
提问by tumbleweed
Is it possible to plot with matplotlib scikit-learn classification report?. Let's assume I print the classification report like this:
是否可以使用 matplotlib scikit-learn 分类报告进行绘图?。假设我像这样打印分类报告:
print '\n*Classification Report:\n', classification_report(y_test, predictions)
confusion_matrix_graph = confusion_matrix(y_test, predictions)
and I get:
我得到:
Clasification Report:
precision recall f1-score support
1 0.62 1.00 0.76 66
2 0.93 0.93 0.93 40
3 0.59 0.97 0.73 67
4 0.47 0.92 0.62 272
5 1.00 0.16 0.28 413
avg / total 0.77 0.57 0.49 858
How can I "plot" the avobe chart?.
我怎样才能“绘制” avobe 图表?
采纳答案by Franck Dernoncourt
Expanding on Bin's answer:
扩展Bin的回答:
import matplotlib.pyplot as plt
import numpy as np
def show_values(pc, fmt="%.2f", **kw):
'''
Heatmap with text in each cell with matplotlib's pyplot
Source: https://stackoverflow.com/a/25074150/395857
By HYRY
'''
from itertools import izip
pc.update_scalarmappable()
ax = pc.get_axes()
#ax = pc.axes# FOR LATEST MATPLOTLIB
#Use zip BELOW IN PYTHON 3
for p, color, value in izip(pc.get_paths(), pc.get_facecolors(), pc.get_array()):
x, y = p.vertices[:-2, :].mean(0)
if np.all(color[:3] > 0.5):
color = (0.0, 0.0, 0.0)
else:
color = (1.0, 1.0, 1.0)
ax.text(x, y, fmt % value, ha="center", va="center", color=color, **kw)
def cm2inch(*tupl):
'''
Specify figure size in centimeter in matplotlib
Source: https://stackoverflow.com/a/22787457/395857
By gns-ank
'''
inch = 2.54
if type(tupl[0]) == tuple:
return tuple(i/inch for i in tupl[0])
else:
return tuple(i/inch for i in tupl)
def heatmap(AUC, title, xlabel, ylabel, xticklabels, yticklabels, figure_width=40, figure_height=20, correct_orientation=False, cmap='RdBu'):
'''
Inspired by:
- https://stackoverflow.com/a/16124677/395857
- https://stackoverflow.com/a/25074150/395857
'''
# Plot it out
fig, ax = plt.subplots()
#c = ax.pcolor(AUC, edgecolors='k', linestyle= 'dashed', linewidths=0.2, cmap='RdBu', vmin=0.0, vmax=1.0)
c = ax.pcolor(AUC, edgecolors='k', linestyle= 'dashed', linewidths=0.2, cmap=cmap)
# put the major ticks at the middle of each cell
ax.set_yticks(np.arange(AUC.shape[0]) + 0.5, minor=False)
ax.set_xticks(np.arange(AUC.shape[1]) + 0.5, minor=False)
# set tick labels
#ax.set_xticklabels(np.arange(1,AUC.shape[1]+1), minor=False)
ax.set_xticklabels(xticklabels, minor=False)
ax.set_yticklabels(yticklabels, minor=False)
# set title and x/y labels
plt.title(title)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
# Remove last blank column
plt.xlim( (0, AUC.shape[1]) )
# Turn off all the ticks
ax = plt.gca()
for t in ax.xaxis.get_major_ticks():
t.tick1On = False
t.tick2On = False
for t in ax.yaxis.get_major_ticks():
t.tick1On = False
t.tick2On = False
# Add color bar
plt.colorbar(c)
# Add text in each cell
show_values(c)
# Proper orientation (origin at the top left instead of bottom left)
if correct_orientation:
ax.invert_yaxis()
ax.xaxis.tick_top()
# resize
fig = plt.gcf()
#fig.set_size_inches(cm2inch(40, 20))
#fig.set_size_inches(cm2inch(40*4, 20*4))
fig.set_size_inches(cm2inch(figure_width, figure_height))
def plot_classification_report(classification_report, title='Classification report ', cmap='RdBu'):
'''
Plot scikit-learn classification report.
Extension based on https://stackoverflow.com/a/31689645/395857
'''
lines = classification_report.split('\n')
classes = []
plotMat = []
support = []
class_names = []
for line in lines[2 : (len(lines) - 2)]:
t = line.strip().split()
if len(t) < 2: continue
classes.append(t[0])
v = [float(x) for x in t[1: len(t) - 1]]
support.append(int(t[-1]))
class_names.append(t[0])
print(v)
plotMat.append(v)
print('plotMat: {0}'.format(plotMat))
print('support: {0}'.format(support))
xlabel = 'Metrics'
ylabel = 'Classes'
xticklabels = ['Precision', 'Recall', 'F1-score']
yticklabels = ['{0} ({1})'.format(class_names[idx], sup) for idx, sup in enumerate(support)]
figure_width = 25
figure_height = len(class_names) + 7
correct_orientation = False
heatmap(np.array(plotMat), title, xlabel, ylabel, xticklabels, yticklabels, figure_width, figure_height, correct_orientation, cmap=cmap)
def main():
sampleClassificationReport = """ precision recall f1-score support
Acacia 0.62 1.00 0.76 66
Blossom 0.93 0.93 0.93 40
Camellia 0.59 0.97 0.73 67
Daisy 0.47 0.92 0.62 272
Echium 1.00 0.16 0.28 413
avg / total 0.77 0.57 0.49 858"""
plot_classification_report(sampleClassificationReport)
plt.savefig('test_plot_classif_report.png', dpi=200, format='png', bbox_inches='tight')
plt.close()
if __name__ == "__main__":
main()
#cProfile.run('main()') # if you want to do some profiling
outputs:
输出:
Example with more classes (~40):
更多类的示例(~40):
回答by elyase
You can do:
你可以做:
import matplotlib.pyplot as plt
cm = [[0.50, 1.00, 0.67],
[0.00, 0.00, 0.00],
[1.00, 0.67, 0.80]]
labels = ['class 0', 'class 1', 'class 2']
fig, ax = plt.subplots()
h = ax.matshow(cm)
fig.colorbar(h)
ax.set_xticklabels([''] + labels)
ax.set_yticklabels([''] + labels)
ax.set_xlabel('Predicted')
ax.set_ylabel('Ground truth')
回答by Bin
I just wrote a function plot_classification_report()
for this purpose. Hope it helps.
This function takes out put of classification_report function as an argument and plot the scores. Here is the function.
我只是plot_classification_report()
为此目的编写了一个函数。希望能帮助到你。该函数将分类报告函数的输出作为参数并绘制分数。这是功能。
def plot_classification_report(cr, title='Classification report ', with_avg_total=False, cmap=plt.cm.Blues):
lines = cr.split('\n')
classes = []
plotMat = []
for line in lines[2 : (len(lines) - 3)]:
#print(line)
t = line.split()
# print(t)
classes.append(t[0])
v = [float(x) for x in t[1: len(t) - 1]]
print(v)
plotMat.append(v)
if with_avg_total:
aveTotal = lines[len(lines) - 1].split()
classes.append('avg/total')
vAveTotal = [float(x) for x in t[1:len(aveTotal) - 1]]
plotMat.append(vAveTotal)
plt.imshow(plotMat, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
x_tick_marks = np.arange(3)
y_tick_marks = np.arange(len(classes))
plt.xticks(x_tick_marks, ['precision', 'recall', 'f1-score'], rotation=45)
plt.yticks(y_tick_marks, classes)
plt.tight_layout()
plt.ylabel('Classes')
plt.xlabel('Measures')
For the example classification_report provided by you. Here are the code and output.
对于您提供的示例分类报告。这是代码和输出。
sampleClassificationReport = """ precision recall f1-score support
1 0.62 1.00 0.76 66
2 0.93 0.93 0.93 40
3 0.59 0.97 0.73 67
4 0.47 0.92 0.62 272
5 1.00 0.16 0.28 413
avg / total 0.77 0.57 0.49 858"""
plot_classification_report(sampleClassificationReport)
Here is how to use it with sklearn classification_report output:
以下是如何将它与 sklearn 分类报告输出一起使用:
from sklearn.metrics import classification_report
classificationReport = classification_report(y_true, y_pred, target_names=target_names)
plot_classification_report(classificationReport)
With this function, you can also add the "avg / total" result to the plot. To use it just add an argument with_avg_total
like this:
使用此功能,您还可以将“平均/总计”结果添加到绘图中。要使用它,只需添加一个with_avg_total
这样的参数:
plot_classification_report(classificationReport, with_avg_total=True)
回答by cosmin
This is my simple solution, using seaborn heatmap
这是我的简单解决方案,使用seaborn heatmap
import seaborn as sns
import numpy as np
from sklearn.metrics import precision_recall_fscore_support
import matplotlib.pyplot as plt
y = np.random.randint(low=0, high=10, size=100)
y_p = np.random.randint(low=0, high=10, size=100)
def plot_classification_report(y_tru, y_prd, figsize=(10, 10), ax=None):
plt.figure(figsize=figsize)
xticks = ['precision', 'recall', 'f1-score', 'support']
yticks = list(np.unique(y_tru))
yticks += ['avg']
rep = np.array(precision_recall_fscore_support(y_tru, y_prd)).T
avg = np.mean(rep, axis=0)
avg[-1] = np.sum(rep[:, -1])
rep = np.insert(rep, rep.shape[0], avg, axis=0)
sns.heatmap(rep,
annot=True,
cbar=False,
xticklabels=xticks,
yticklabels=yticks,
ax=ax)
plot_classification_report(y, y_p)
回答by larrywgray
My solution is to use the python package, Yellowbrick. Yellowbrick in a nutshell combines scikit-learn with matplotlib to produce visualizations for your models. In a few lines you can do what was suggested above. http://www.scikit-yb.org/en/latest/api/classifier/classification_report.html
我的解决方案是使用 python 包 Yellowbrick。简而言之,Yellowbrick 将 scikit-learn 与 matplotlib 相结合,为您的模型生成可视化效果。在几行中,您可以执行上面建议的操作。 http://www.scikit-yb.org/en/latest/api/classifier/classification_report.html
from sklearn.naive_bayes import GaussianNB
from yellowbrick.classifier import ClassificationReport
# Instantiate the classification model and visualizer
bayes = GaussianNB()
visualizer = ClassificationReport(bayes, classes=classes, support=True)
visualizer.fit(X_train, y_train) # Fit the visualizer and the model
visualizer.score(X_test, y_test) # Evaluate the model on the test data
visualizer.show() # Draw/show the data
回答by Mohd Shahril
Here you can get the plot same as Franck Dernoncourt's, but with much shorter code (can fit into a single function).
在这里,您可以获得与Franck Dernoncourt相同的图,但代码更短(可以放入单个函数)。
import matplotlib.pyplot as plt
import numpy as np
import itertools
def plot_classification_report(classificationReport,
title='Classification report',
cmap='RdBu'):
classificationReport = classificationReport.replace('\n\n', '\n')
classificationReport = classificationReport.replace(' / ', '/')
lines = classificationReport.split('\n')
classes, plotMat, support, class_names = [], [], [], []
for line in lines[1:]: # if you don't want avg/total result, then change [1:] into [1:-1]
t = line.strip().split()
if len(t) < 2:
continue
classes.append(t[0])
v = [float(x) for x in t[1: len(t) - 1]]
support.append(int(t[-1]))
class_names.append(t[0])
plotMat.append(v)
plotMat = np.array(plotMat)
xticklabels = ['Precision', 'Recall', 'F1-score']
yticklabels = ['{0} ({1})'.format(class_names[idx], sup)
for idx, sup in enumerate(support)]
plt.imshow(plotMat, interpolation='nearest', cmap=cmap, aspect='auto')
plt.title(title)
plt.colorbar()
plt.xticks(np.arange(3), xticklabels, rotation=45)
plt.yticks(np.arange(len(classes)), yticklabels)
upper_thresh = plotMat.min() + (plotMat.max() - plotMat.min()) / 10 * 8
lower_thresh = plotMat.min() + (plotMat.max() - plotMat.min()) / 10 * 2
for i, j in itertools.product(range(plotMat.shape[0]), range(plotMat.shape[1])):
plt.text(j, i, format(plotMat[i, j], '.2f'),
horizontalalignment="center",
color="white" if (plotMat[i, j] > upper_thresh or plotMat[i, j] < lower_thresh) else "black")
plt.ylabel('Metrics')
plt.xlabel('Classes')
plt.tight_layout()
def main():
sampleClassificationReport = """ precision recall f1-score support
Acacia 0.62 1.00 0.76 66
Blossom 0.93 0.93 0.93 40
Camellia 0.59 0.97 0.73 67
Daisy 0.47 0.92 0.62 272
Echium 1.00 0.16 0.28 413
avg / total 0.77 0.57 0.49 858"""
plot_classification_report(sampleClassificationReport)
plt.show()
plt.close()
if __name__ == '__main__':
main()
回答by wejradford
If you just want to plot the classification report as a bar chart in a Jupyter notebook, you can do the following.
如果您只想将分类报告绘制为 Jupyter notebook 中的条形图,您可以执行以下操作。
# Assuming that classification_report, y_test and predictions are in scope...
import pandas as pd
# Build a DataFrame from the classification_report output_dict.
report_data = []
for label, metrics in classification_report(y_test, predictions, output_dict=True).items():
metrics['label'] = label
report_data.append(metrics)
report_df = pd.DataFrame(
report_data,
columns=['label', 'precision', 'recall', 'f1-score', 'support']
)
# Plot as a bar chart.
report_df.plot(y=['precision', 'recall', 'f1-score'], x='label', kind='bar')
One issue with this visualisation is that imbalanced classes are not obvious, but are important in interpreting the results. One way to represent this is to add a version of the label
that includes the number of samples (i.e. the support
):
这种可视化的一个问题是不平衡的类并不明显,但在解释结果时很重要。表示这一点的一种方法是添加一个label
包含样本数量的版本(即support
):
# Add a column to the DataFrame.
report_df['labelsupport'] = [f'{label} (n={support})'
for label, support in zip(report_df.label, report_df.support)]
# Plot the chart the same way, but use `labelsupport` as the x-axis.
report_df.plot(y=['precision', 'recall', 'f1-score'], x='labelsupport', kind='bar')
回答by akilat90
No string processing + sns.heatmap
无字符串处理 + sns.heatmap
The following solution uses the output_dict=True
option in classification_report
to get a dictionary and then a heat map is drawn using seaborn to the dataframe created from the dictionary.
以下解决方案使用output_dict=True
in 选项classification_report
获取字典,然后使用 seaborn 将热图绘制到从字典创建的数据帧。
import numpy as np
import seaborn as sns
from sklearn.metrics import classification_report
import pandas as pd
Generating data. Classes: A,B,C,D,E,F,G,H,I
生成数据。课程:A,B,C,D,E,F,G,H,I
true = np.random.randint(0, 10, size=100)
pred = np.random.randint(0, 10, size=100)
labels = np.arange(10)
target_names = list("ABCDEFGHI")
Call classification_report
with output_dict=True
呼叫classification_report
与output_dict=True
clf_report = classification_report(true,
pred,
labels=labels,
target_names=target_names,
output_dict=True)
Create a dataframe from the dictionary and plot a heatmap of it.
从字典中创建一个数据框并绘制它的热图。
# .iloc[:-1, :] to exclude support
sns.heatmap(pd.DataFrame(clf_report).iloc[:-1, :].T, annot=True)
回答by Juan Costamagna
It was really useful for my Franck Dernoncourt and Bin's answer, but I had two problems.
这对我的Franck Dernoncourt 和 Bin的回答非常有用,但我有两个问题。
First, when I tried to use it with classes like "No hit" or a name with space inside, the plot failed.
And the other problem was to use this functions with MatPlotlib 3.* and scikitLearn-0.22.* versions. So I did some little changes:
首先,当我尝试将它与诸如“No hit”或带有空格的名称之类的类一起使用时,情节失败了。
另一个问题是在MatPlotlib 3.* 和 scikitLearn-0.22.* 版本中使用这个函数。所以我做了一些小改动:
import matplotlib.pyplot as plt
import numpy as np
def show_values(pc, fmt="%.2f", **kw):
'''
Heatmap with text in each cell with matplotlib's pyplot
Source: https://stackoverflow.com/a/25074150/395857
By HYRY
'''
pc.update_scalarmappable()
ax = pc.axes
#ax = pc.axes# FOR LATEST MATPLOTLIB
#Use zip BELOW IN PYTHON 3
for p, color, value in zip(pc.get_paths(), pc.get_facecolors(), pc.get_array()):
x, y = p.vertices[:-2, :].mean(0)
if np.all(color[:3] > 0.5):
color = (0.0, 0.0, 0.0)
else:
color = (1.0, 1.0, 1.0)
ax.text(x, y, fmt % value, ha="center", va="center", color=color, **kw)
def cm2inch(*tupl):
'''
Specify figure size in centimeter in matplotlib
Source: https://stackoverflow.com/a/22787457/395857
By gns-ank
'''
inch = 2.54
if type(tupl[0]) == tuple:
return tuple(i/inch for i in tupl[0])
else:
return tuple(i/inch for i in tupl)
def heatmap(AUC, title, xlabel, ylabel, xticklabels, yticklabels, figure_width=40, figure_height=20, correct_orientation=False, cmap='RdBu'):
'''
Inspired by:
- https://stackoverflow.com/a/16124677/395857
- https://stackoverflow.com/a/25074150/395857
'''
# Plot it out
fig, ax = plt.subplots()
#c = ax.pcolor(AUC, edgecolors='k', linestyle= 'dashed', linewidths=0.2, cmap='RdBu', vmin=0.0, vmax=1.0)
c = ax.pcolor(AUC, edgecolors='k', linestyle= 'dashed', linewidths=0.2, cmap=cmap, vmin=0.0, vmax=1.0)
# put the major ticks at the middle of each cell
ax.set_yticks(np.arange(AUC.shape[0]) + 0.5, minor=False)
ax.set_xticks(np.arange(AUC.shape[1]) + 0.5, minor=False)
# set tick labels
#ax.set_xticklabels(np.arange(1,AUC.shape[1]+1), minor=False)
ax.set_xticklabels(xticklabels, minor=False)
ax.set_yticklabels(yticklabels, minor=False)
# set title and x/y labels
plt.title(title, y=1.25)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
# Remove last blank column
plt.xlim( (0, AUC.shape[1]) )
# Turn off all the ticks
ax = plt.gca()
for t in ax.xaxis.get_major_ticks():
t.tick1line.set_visible(False)
t.tick2line.set_visible(False)
for t in ax.yaxis.get_major_ticks():
t.tick1line.set_visible(False)
t.tick2line.set_visible(False)
# Add color bar
plt.colorbar(c)
# Add text in each cell
show_values(c)
# Proper orientation (origin at the top left instead of bottom left)
if correct_orientation:
ax.invert_yaxis()
ax.xaxis.tick_top()
# resize
fig = plt.gcf()
#fig.set_size_inches(cm2inch(40, 20))
#fig.set_size_inches(cm2inch(40*4, 20*4))
fig.set_size_inches(cm2inch(figure_width, figure_height))
def plot_classification_report(classification_report, number_of_classes=2, title='Classification report ', cmap='RdYlGn'):
'''
Plot scikit-learn classification report.
Extension based on https://stackoverflow.com/a/31689645/395857
'''
lines = classification_report.split('\n')
#drop initial lines
lines = lines[2:]
classes = []
plotMat = []
support = []
class_names = []
for line in lines[: number_of_classes]:
t = list(filter(None, line.strip().split(' ')))
if len(t) < 4: continue
classes.append(t[0])
v = [float(x) for x in t[1: len(t) - 1]]
support.append(int(t[-1]))
class_names.append(t[0])
plotMat.append(v)
xlabel = 'Metrics'
ylabel = 'Classes'
xticklabels = ['Precision', 'Recall', 'F1-score']
yticklabels = ['{0} ({1})'.format(class_names[idx], sup) for idx, sup in enumerate(support)]
figure_width = 10
figure_height = len(class_names) + 3
correct_orientation = True
heatmap(np.array(plotMat), title, xlabel, ylabel, xticklabels, yticklabels, figure_width, figure_height, correct_orientation, cmap=cmap)
plt.show()