plt使用汇总

 

1.保存图像的清晰度

  出处:csdn的“larry_do”博主 。详细资料见参考

plt.savefig("data/temp.png",dpi=500,bbox_inches = 'tight')#解决图片不清晰,不完整的问题

 

2.显示完图片后自动关闭窗口

  不阻塞程序 参考:CSDN LoveWeeknd 博主

  关闭参考:易特创芯的 caoshangfei 

 # 不暂停
    plt.ion()

……
plt.close('all') # 关闭所有。如果要自动关闭,前面一定要调用”ion()“

 

3.plot转 tf.image

def plot_to_TFimage(figure):
    #plt图像转化为tensor图像
    buf = io.BytesIO()  # 在内存中存储画
    plt.savefig(buf, format='png')
    plt.close(figure)
    buf.seek(0)
    # 传化为TF 图
    image = tf.image.decode_png(buf.getvalue(), channels=4)
    image = tf.expand_dims(image, 0)
    return image

出自其它博客。此处,忘记之后网络上搜寻不带出处,故未标注

 

4.将混淆矩阵保存到tensorboard

主体实现参考:https://blog.csdn.net/xiedelong/article/details/108328108
plt中文显示:https://www.cnblogs.com/hhh5460/p/4323985.html

 

绘制主体

import matplotlib
matplotlib.use('Agg') # 指定为无交互后端。需要在 “matplotlib.pyplot”之前调用。 多线程时需要指定
import matplotlib.pyplot as plt

def plot_confusion_matrix(correct_labels, predict_labels, labels, title='Confusion matrix', normalize=False): ''' Parameters: correct_labels : 这是真实标签 形式是 [n] ,值范围是labels predict_labels : 这是模型预测标签,形式是[n],值范围是labels labels : 这是要显示的标签名 title='Confusion matrix' : 显示的矩阵名 Returns: summaryImage: TensorFlow 的图,4维。可以直接传给tensorboard对象
cm :混淆矩阵
Other itema to note:
- Depending on the number of category and the data , you may have to modify the figzie, font sizes etc. - Currently, some of the ticks dont line up due to rotations. ''' cm = confusion_matrix(correct_labels, predict_labels, labels=labels) #计算混淆矩阵 if normalize: cm = cm.astype('float') * 10 / cm.sum(axis=1)[:, np.newaxis] #注意当,存在某些类数目=0时,会发生除0错误。 最好分成俩部。 对于统计到值=0的行,修正为除1 cm = np.nan_to_num(cm, copy=True) cm = cm.astype('int') np.set_printoptions(precision=2) #方法2 plt.rc('font', family='sans-serif', size='4.5') # 设置字体样式、大小 # plt.rcParams['font.sans-serif'] = ['Tahoma', 'DejaVu Sans', 'SimHei', 'Lucida Grande', 'Verdana'] # 用来正常显示中文标签 plt.rcParams['font.sans-serif'] = ['SimHei'] #设置为支持中文字体。此处为全局设置,影响到后续所有plt绘制。 plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号 # plt.figure(figsize=(200, 200)) #此处会多一个弹窗。为何源码这处多一个弹窗。需要研究 plt.rcParams['figure.dpi'] = 200 # 分辨率 #占比1%以下的单元格,设为0,防止在最后的颜色中体现出来 for i in range(cm.shape[0]): for j in range(cm.shape[1]): if int(cm[i, j] ) == 0: cm[i, j] = 0 fig, ax = plt.subplots() im = ax.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues) ax.figure.colorbar(im, ax=ax) # 侧边的颜色条带 plt.title('Confusion matrix') ax.set(xticks=np.arange(cm.shape[1]), yticks=np.arange(cm.shape[0]), # xticklabels=list(range(len(labels))), yticklabels=list(range(len(labels))), xticklabels=labels, yticklabels=labels, #设置标签信息 title=title, ylabel='Actual', xlabel='Predicted') # 通过绘制格网,模拟每个单元格的边框 ax.set_xticks(np.arange(cm.shape[1] + 1) - .5, minor=True) ax.set_yticks(np.arange(cm.shape[0] + 1) - .5, minor=True) ax.grid(which="minor", color="gray", linestyle='-', linewidth=0.05) ax.tick_params(which="minor", bottom=False, left=False) # 将x轴上的lables旋转45度 plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor") # 标注百分比信息 fmt = 'd' thresh = cm.max() / 2. for i in range(cm.shape[0]): for j in range(cm.shape[1]): # if int(cm[i, j] + 0.5) > 0: ax.text(j, i, format(int(cm[i, j]), fmt), ha="center", va="center", color="white" if cm[i, j] > thresh else "black") fig.tight_layout() plt.show() #plt转tf.image summaryImage = plot_to_TFimage(fig)

return summaryImage, cm

 

 

#tensorboard文件创建
local_summary_writer = tf.summary.create_file_writer("文件路径")
summaryImage,cm = plot_confusion_matrix(correct_txt_labels, predict_txt_labels, labelNames)
if (local_summary_writer != None):
with
local_summary_writer.as_default():
          tf.summary.image("cofunsionMatrix", summaryImage, step)

 

posted @ 2021-01-28 15:39  飘零_未知的坚持  阅读(476)  评论(0编辑  收藏  举报