python-matplotlib 绘制折线图(同时解决XShell远程访问Ubuntu使用matplotlib绘制图时,出现的问题)

版权声明:转载需注明出处 https://blog.csdn.net/holmes_MX/article/details/82431418

0. 写作目的

好记性不如烂笔头。

1. 有关matplot 绘制曲线图

这里以绘制目标检测中P-R(Precision - Recall)曲线为例进行说明。

具体如何计算目标检测中的AP,和mAP请参考我的另一博客。

下面的代码是SSD/caffe版本中的caffe/exampels/ssd/score_ssd_pascal.py中的增加的绘制P-R曲线的片段。且保存了输出过程中最大Precsion。(这里绘制的P-R不是原始意义上的P-R曲线,绘制的是recall(0.0 0.1 ... 0.9 1.0)和最大precision的P-R曲线,由于计算AP就是采用此计算方法,因此可以近似看成P-R曲线)。

以下代码大体思路为:先从caffe输出的log中,找出输出最大MaxPrecision的值(此处需要修改caffe源码来便于找到带有MaxPrecision值得日志行),然后将这些MaxPrecision保存到txt文件中,便于后续使用(由于代码中给出的绘图大小为10*10,如果太小或者太大,都可以依据txt文件重新绘制)。最后对于不同的类,绘制不同的P-R曲线,并保存。

import matplotlib
#matplotlib.use('Agg')
import matplotlib.pyplot as plt
with open('{}/{}_test{}.log'.format(job_dir, model_name, max_iter), 'r') as f:
    lines = f.readlines()
if solver_param['ap_version'] == "11point":
    tempRecall = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
    counter = 0
    tempPrecision = []
    for line in lines:
        if 'for plot P-R for each class' not in line:
            continue
        else:
            counter += 0
            line = line.replace('\n',' ')
            lineList = line.split()
            tempPrecision.append(float( lineList[-1] ))
   # print(tempRecall)
   # print(tempPrecision)
    ### plot the P-R curve for every class
    with open('{}/{}_test{}_MaxPrecision.txt'.format(job_dir, model_name, max_iter), 'w') as f:
        f.write("MaxPrecision: ")
        for ii in range(len(tempPrecision)):
            if(ii == len(tempPrecision) - 1):
                f.write(str(tempPrecision[ii]) + '\n')
            else:
                f.write(str(tempPrecision[ii]) + ' ')
    plt.rcParams['figure.figsize']=(10,10)
    if(len(tempPrecision) % 11 == 0):
        counter = 0
        #print(len(tempPrecision))
        for ii in range(int(len(tempPrecision) / 11)):
            tempSort = sorted(tempPrecision[int(counter): int(counter + 11)], reverse=True)
            #print(tempSort)
            counter += 11
            fig = plt.figure()
            plt.subplot(111)
            plt.plot(tempRecall, tempSort, color='blue')
            plt.xlabel('Recall')
            plt.ylabel('Precision')
            plt.title('class:{}-P-R curve'.format(str(int(counter / 11))))

            tempSaveDir = '{}/{}_test{}-class{}_PRcurve.jpg'.format(job_dir, model_name, max_iter, int(counter/11))
            #print(tempSaveDir)
            plt.savefig(tempSaveDir)
        print('P-R Curve and AP are saved in {}'.format(job_dir))
    else:
        raise("the number of Precision is Wrong!!!!!")

2. 有关XShell远程访问Ubuntu绘图时存在的问题

存在的问题是(这里只截取了问题的最后部分):

_tkinter.TclError: no display name and no $DISPLAY environment variable

        如果只是在python文件中,简单加上如下代码,仍不能解决问题:

import matplotlib
matplotlib.use('Agg')

需要修改原配置文件中的配置:

具体步骤为:

       1) 使用ubuntu shell命令来查找matplotlibrc的位置

可能安装的python不只一个,因此可能有多个matplotlibrc文件,只修改你所用的那个即可

       2) 然后使用VIM打开该文件

      3) 找到如下行,然后修改为:

# If you omit this parameter, it will always default to "Agg", which is a
# non-interactive backend.
#backend      : TkAgg    ## original backend
backend      : Agg      ## the model of backend you need to modify

 

[Reference]

[1] 绘折线图参考:https://www.cnblogs.com/I-Tegulia/p/4615919.html

[2] 解决XShell远程访问问题: https://blog.csdn.net/qq_22194315/article/details/77984423

猜你喜欢

转载自blog.csdn.net/holmes_MX/article/details/82431418