Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何绘制scikit学习分类报告?_Python_Numpy_Matplotlib_Scikit Learn - Fatal编程技术网

Python 如何绘制scikit学习分类报告?

Python 如何绘制scikit学习分类报告?,python,numpy,matplotlib,scikit-learn,Python,Numpy,Matplotlib,Scikit Learn,是否可以使用matplotlib scikit学习分类报告进行绘图?。假设我这样打印分类报告: print '\n*Classification Report:\n', classification_report(y_test, predictions) confusion_matrix_graph = confusion_matrix(y_test, predictions) plot_classification_report(classificationReport, with_

是否可以使用matplotlib scikit学习分类报告进行绘图?。假设我这样打印分类报告:

print '\n*Classification Report:\n', classification_report(y_test, predictions)
    confusion_matrix_graph = confusion_matrix(y_test, predictions)
plot_classification_report(classificationReport, with_avg_total=True)
我得到:

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
如何“绘制”avobe图表?

您可以执行以下操作:

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')

为此,我刚刚编写了一个函数
plot\u classification\u report()
。希望能有帮助。 此函数将put of CLASSION_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')
有关您提供的示例分类报告。下面是代码和输出

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)

以下是如何将其与sklearn classification_报告输出一起使用:

from sklearn.metrics import classification_report
classificationReport = classification_report(y_true, y_pred, target_names=target_names)

plot_classification_report(classificationReport)
使用此功能,还可以将“平均/总计”结果添加到绘图中。要使用它,只需添加一个参数
和_avg_total
,如下所示:

print '\n*Classification Report:\n', classification_report(y_test, predictions)
    confusion_matrix_graph = confusion_matrix(y_test, predictions)
plot_classification_report(classificationReport, with_avg_total=True)
在下面的回答中展开:

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
导入matplotlib.pyplot作为plt
将numpy作为np导入
def显示_值(pc,fmt=“%.2f”,**kw):
'''
使用matplotlib的pyplot在每个单元格中显示文本的热图
资料来源:https://stackoverflow.com/a/25074150/395857 
海瑞
'''
从itertools导入izip
pc.更新_scalarmappable()
ax=pc.获取轴()
#ax=pc.axes#用于最新的MATPLOTLIB
#在Python3中使用下面的zip
对于p,color,izip中的值(pc.get_path(),pc.get_facecolors(),pc.get_array()):
x、 y=p.顶点[:-2,:]平均值(0)
如果np.all(颜色[:3]>0.5):
颜色=(0.0,0.0,0.0)
其他:
颜色=(1.0,1.0,1.0)
最大文本(x,y,fmt%值,ha=“center”,va=“center”,color=color,**千瓦)
def cm2inch(*tupl):
'''
在matplotlib中指定地物尺寸(以厘米为单位)
资料来源:https://stackoverflow.com/a/22787457/395857
由gns ank提供
'''
英寸=2.54
如果类型(tupl[0])==tuple:
返回元组(元组[0]中i的i/英寸)
其他:
返回元组(元组中i的i/英寸)
def热图(AUC、标题、xlabel、ylabel、xticklabel、yticklabels、图宽=40、图高=20、正确方向=False、cmap='RdBu'):
'''
灵感来自:
- https://stackoverflow.com/a/16124677/395857 
- https://stackoverflow.com/a/25074150/395857
'''
#把它画出来
图,ax=plt.子批次()
#c=ax.pcolor(AUC,edgecolors='k',linestyle='虚线',线宽=0.2,cmap='RdBu',vmin=0.0,vmax=1.0)
c=ax.pcolor(AUC,edgecolors='k',linestyle='虚线',线宽=0.2,cmap=cmap)
#将主刻度放在每个单元格的中间
最大设定值(np.arange(AUC.shape[0])+0.5,小调=假)
ax.set_xticks(np.arange(AUC.shape[1])+0.5,minor=False)
#设置勾号标签
#ax.set_xticklabels(np.arange(1,AUC.shape[1]+1),minor=False)
ax.setxticklabels(xticklabels,minor=False)
ax.set_yticklabels(yticklabels,minor=False)
#设置标题和x/y标签
标题(标题)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
#删除最后一个空白列
plt.xlim((0,AUC.shape[1]))
#关掉所有的滴答声
ax=plt.gca()
对于ax.xaxis.get_major_ticks()中的t:
t、 tick1On=False
t、 tick2On=False
对于ax.yaxis.get_major_ticks()中的t:
t、 tick1On=False
t、 tick2On=False
#添加颜色栏
打印颜色条(c)
#在每个单元格中添加文本
显示_值(c)
#方向正确(原点位于左上角,而不是左下角)
如果方向正确:
ax.invert_yaxis()
ax.xaxis.tick_top()
#调整大小
图=plt.gcf()
#图设置尺寸英寸(厘米2英寸(40,20))
#图设置尺寸英寸(厘米2英寸(40*4,20*4))
图设置尺寸英寸(cm2英寸(图宽、图高))
def绘图分类报告(分类报告,标题class='classification report',cmap='RdBu'):
'''
绘制scikit学习分类报告。
基于https://stackoverflow.com/a/31689645/395857 
'''
行=分类报告。拆分('\n')
类别=[]
plotMat=[]
支持=[]
类名称=[]
对于行中的行[2:(len(line)-2)]:
t=line.strip().split()
如果len(t)<2:继续
class.append(t[0])
v=[t中x的浮点(x)[1:len(t)-1]]
support.append(int(t[-1]))
类名称。追加(t[0])
印刷品(五)
plotMat.append(v)
打印('plotMat:{0}'。格式(plotMat))
打印('支持:{0}'。格式(支持))
xlabel='Metrics'
ylabel='Classes'
xticklabels=[“精度”、“回忆”、“F1分数”]
yticklabels=['{0}({1}')。idx的格式(类名称[idx],sup),枚举中的sup(支持)]
图_宽度=25
图\u高度=长度(类别名称)+7
方向正确=错误
热图(np.数组(plotMat)、标题、xlabel、ylabel、xticklabel、yticklabels、地物宽度、地物高度、正确方位、cmap=cmap)
def main():
sampleClassificationReport=“”精确召回f1分数支持
相思树0.62 1.00 0.76 66
开花0.930.930.9340
山茶花0.59 0.97 0.73 67
黛西0.47 0.92 0.62 272
Echium 1.00 0.16 0.28 413
平均/总计0.77 0.57 0.49 858“
绘图分类报告(样本分类报告)
plt.savefig('test\u plot\u classif\u report.png',dpi=200,format='png',bbox\u inches='tight')
plt.close()
如果名称=“\uuuuu main\uuuuuuuu”:
main()
#如果要进行一些分析,请运行('main()')#
产出:

具有更多类(~40)的示例:


这是我的简单解决方案,使用seaborn热图

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)

我的解决方案是使用python包Yellowbrick。简而言之,Yellowbrick将scikit learn与matplotlib相结合,为您的模型生成可视化效果。在几行代码中,您可以执行上面建议的操作。


在这里,您可以得到与的相同的绘图,但代码要短得多(可以放入单个函数)

导入
import numpy as np
import seaborn as sns
from sklearn.metrics import classification_report
import pandas as pd
true = np.random.randint(0, 10, size=100)
pred = np.random.randint(0, 10, size=100)
labels = np.arange(10)
target_names = list("ABCDEFGHI")
clf_report = classification_report(true,
                                   pred,
                                   labels=labels,
                                   target_names=target_names,
                                   output_dict=True)
# .iloc[:-1, :] to exclude support
sns.heatmap(pd.DataFrame(clf_report).iloc[:-1, :].T, annot=True)
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()


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) - 6)]: rt
        t = line.split()
        classes.append(t[0])
        v = [float(x) for x in t[1: len(t) - 1]]
        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.figure(figsize=(12,48))
    #plt.imshow(plotMat, interpolation='nearest', cmap=cmap) THIS also works but the scale is not good neither the colors for many classes(200)
    #plt.colorbar()

    plt.title(title)
    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')
    import seaborn as sns
    sns.heatmap(plotMat, annot=True) 
reportstr = classification_report(true_classes, y_pred,target_names=class_labels_no_spaces)

plot_classification_report(reportstr)
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)

    # 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) - 4)]:
        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():
    # OLD 
    # 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"""

    # NEW
    sampleClassificationReport = """              precision    recall  f1-score   support

           1       1.00      0.33      0.50         9
           2       0.50      1.00      0.67         9
           3       0.86      0.67      0.75         9
           4       0.90      1.00      0.95         9
           5       0.67      0.89      0.76         9
           6       1.00      1.00      1.00         9
           7       1.00      1.00      1.00         9
           8       0.90      1.00      0.95         9
           9       0.86      0.67      0.75         9
          10       1.00      0.78      0.88         9
          11       1.00      0.89      0.94         9
          12       0.90      1.00      0.95         9
          13       1.00      0.56      0.71         9
          14       1.00      1.00      1.00         9
          15       0.60      0.67      0.63         9
          16       1.00      0.56      0.71         9
          17       0.75      0.67      0.71         9
          18       0.80      0.89      0.84         9
          19       1.00      1.00      1.00         9
          20       1.00      0.78      0.88         9
          21       1.00      1.00      1.00         9
          22       1.00      1.00      1.00         9
          23       0.27      0.44      0.33         9
          24       0.60      1.00      0.75         9
          25       0.56      1.00      0.72         9
          26       0.18      0.22      0.20         9
          27       0.82      1.00      0.90         9
          28       0.00      0.00      0.00         9
          29       0.82      1.00      0.90         9
          30       0.62      0.89      0.73         9
          31       1.00      0.44      0.62         9
          32       1.00      0.78      0.88         9
          33       0.86      0.67      0.75         9
          34       0.64      1.00      0.78         9
          35       1.00      0.33      0.50         9
          36       1.00      0.89      0.94         9
          37       0.50      0.44      0.47         9
          38       0.69      1.00      0.82         9
          39       1.00      0.78      0.88         9
          40       0.67      0.44      0.53         9

    accuracy                           0.77       360
   macro avg       0.80      0.77      0.76       360
weighted avg       0.80      0.77      0.76       360
    """
    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