Python 向Tensorflow中Tensorboard的混淆矩阵添加文本标签
我正在自定义Tensorflow示例中的代码,通过添加额外的密集层、辍学、动量梯度下降等,在我自己的图像上进行训练 我想在Tensorboard中添加一个混淆矩阵,所以我遵循了post中的第一个答案(Jerod的)(我也尝试了第二个答案,但面临一些调试问题),并在Python 向Tensorflow中Tensorboard的混淆矩阵添加文本标签,python,tensorflow,machine-learning,tensorboard,confusion-matrix,Python,Tensorflow,Machine Learning,Tensorboard,Confusion Matrix,我正在自定义Tensorflow示例中的代码,通过添加额外的密集层、辍学、动量梯度下降等,在我自己的图像上进行训练 我想在Tensorboard中添加一个混淆矩阵,所以我遵循了post中的第一个答案(Jerod的)(我也尝试了第二个答案,但面临一些调试问题),并在add\u evaluation\u step函数中添加了几行。所以现在看起来像: def add_evaluation_step(result_tensor, ground_truth_tensor): with tf.name
add\u evaluation\u step
函数中添加了几行。所以现在看起来像:
def add_evaluation_step(result_tensor, ground_truth_tensor):
with tf.name_scope('accuracy'):
with tf.name_scope('correct_prediction'):
prediction = tf.argmax(result_tensor, 1)
correct_prediction = tf.equal(
prediction, tf.argmax(ground_truth_tensor, 1))
with tf.name_scope('accuracy'):
evaluation_step = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
tf.summary.scalar('accuracy', evaluation_step)
print('prediction shape :: {}'.format(ground_truth_tensor))
#Add confusion matrix
batch_confusion = tf.confusion_matrix(tf.argmax(ground_truth_tensor, 1), prediction,
num_classes=7,
name='batch_confusion')
# Create an accumulator variable to hold the counts
confusion = tf.Variable( tf.zeros([7,7],
dtype=tf.int32 ),
name='confusion' )
# Create the update op for doing a "+=" accumulation on the batch
confusion_update = confusion.assign( confusion + batch_confusion )
# Cast counts to float so tf.summary.image renormalizes to [0,255]
confusion_image = tf.reshape( tf.cast( confusion_update, tf.float32),
[1, 7, 7, 1])
tf.summary.image('confusion',confusion_image)
return evaluation_step, prediction
这给了我:
我的问题是如何将标签添加到行(实际类)和列(预测类)中。要获得类似于:
Jerod的几乎包含了您需要的所有内容,例如yauheni_selivonchyk的另一篇关于如何将自定义图像添加到Tensorboard的文章
然后,这只是一个将所有内容组合在一起的问题,即:
1.实现将打印图像传递到摘要的方法
导入matplotlib
将matplotlib.pyplot作为plt导入
作为pd进口熊猫
导入seaborn作为sns
将numpy作为np导入
导入tensorflow作为tf
#灵感来源于yauheni_selivonchyk等(https://stackoverflow.com/a/42815564/624547)
def get_图(figsize=(10,10),dpi=300):
"""
返回pyplot图形
:param figsize:
:参数dpi:
:返回:
"""
图=plt.图(num=0,figsize=figsize,dpi=dpi)
图clf()
返回图
def fig_至_rgb_阵列(图,展开=真):
"""
将图形转换为RGB阵列
:参数图:PyPlot图
:param expand:要展开的标志
:return:RGB数组
"""
图canvas.draw()
buf=图canvas.tostring_rgb()
ncols,nrows=fig.canvas.get\u width\u height()
形状=(nrows,ncols,3)如果不展开else(1,nrows,ncols,3)
返回np.fromstring(buf,dtype=np.uint8)。重塑(形状)
def图到图摘要(图、摘要、位置支架):
"""
将数字转换为TF摘要
:参数图:图
:参数摘要:要评估的摘要
:param place_holder:摘要图像占位符
:返回:摘要
"""
图像=图到图rgb图阵列(图)
返回summary.eval(feed_dict={place_holder:image})
2.将矩阵数据转换为经过修饰的混淆图像
(这里有一个例子,但这取决于你想要什么)
def混淆矩阵到图像摘要(混淆矩阵、摘要、放置架、,
列出_类,figsize=(9,9)):
"""
绘制混淆矩阵并作为TF摘要返回
:参数矩阵:混淆矩阵(N x N)
:param filename:filename
:参数列表\类:类列表(N)
:param figsize:Pyplot figsize用于混淆图像
:返回:/
"""
图=获取图(图大小=(9,9))
df=pd.DataFrame(混乱矩阵,索引=列表类,列=列表类)
ax=sns.heatmap(df,annot=True,fmt='.0%'))
#无论你想要什么样的装饰:
产品名称(“混淆矩阵”)
plt.xticks(旋转=90)
plt.yticks(旋转=0)
图像汇总=图汇总(图、汇总、位置保持架)
返回图像和
3.定义评估操作并准备占位符
#受Jerod对SO的回答启发(https://stackoverflow.com/a/42857070/624547)
def add_evaluation_step(结果张量、基础真值张量、数量类、混淆矩阵figsize=(9,9)):
"""
设置评估操作,计算运行精度和混乱图像
:param result_tensor:输出张量
:param ground\u truth\u张量:目标类张量
:param num_classes:类数
:param confusion_matrix_figsize:混乱图像的Pyplot figsize
:return:TF操作、摘要和占位符(参见下面的用法)
"""
scope=“评估”
使用tf.name\u范围(范围):
预测=tf.argmax(结果张量,1,name=“预测”)
#流精度(查找和更新张量):
准确度,准确度\u更新=tf.metrics.accurity(地面真理张量,预测,name='accurity')
#每批混淆矩阵:
批次混淆=tf.混淆矩阵(基本真值张量,预测,num类=num类,
name='batch\u-mission')
#综合混淆矩阵:
混淆矩阵=tf.Variable(tf.zero([num\u classes,num\u classes],dtype=tf.int32),
姓名(混淆)
混乱更新=混乱矩阵。分配(混乱矩阵+批量混乱)
#我们假设每个批次都包含一个完整的类,通过其大小直接进行规范化:
评估\u流\u度量\u op=tf.group(准确度\u更新、混乱度\u更新)
#矩阵中的混乱图像(需要将dims+cast扩展为浮点,以便tf.summary.image重新规范化为[0255]:
confusion\u image=tf.reformate(tf.cast(confusion\u update,tf.float32),[1,num\u类,num\u类,1])
#摘要:
tf.summary.scalar('accurity',accurity,collections=[scope])
summary\u op=tf.summary.merge\u all(范围)
#准备混乱图像的占位符(以便我们可以将打印的图像传递给它):
#(我们基本上预先分配一个绘图图形,并将其RGB数组传递给占位符)
混乱\u图像\u占位符=tf.placeholder(tf.uint8,
图到rgb图阵列(获取图(figsize=混淆矩阵figsize)).shape)
模糊图像
from textwrap import wrap
import itertools
import matplotlib
import tfplot
import os
import re
def plot_confusion_matrix(correct_labels, predict_labels,labels,session, title='Confusion matrix', tensor_name = 'MyFigure/image', normalize=False):
conf = tf.contrib.metrics.confusion_matrix(correct_labels, predict_labels)
cm=session.run(conf)
if normalize:
cm = cm.astype('float')*10 / cm.sum(axis=1)[:, np.newaxis]
cm = np.nan_to_num(cm, copy=True)
cm = cm.astype('int')
np.set_printoptions(precision=2)
fig = matplotlib.figure.Figure(figsize=(7, 7), dpi=320, facecolor='w', edgecolor='k')
ax = fig.add_subplot(1, 1, 1)
im = ax.imshow(cm, cmap='Oranges')
classes = [re.sub(r'([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))', r'\1 ', x) for x in labels]
classes = ['\n'.join(wrap(l, 40)) for l in classes]
tick_marks = np.arange(len(classes))
ax.set_xlabel('Predicted', fontsize=7)
ax.set_xticks(tick_marks)
c = ax.set_xticklabels(classes, fontsize=10, rotation=-90, ha='center')
ax.xaxis.set_label_position('bottom')
ax.xaxis.tick_bottom()
ax.set_ylabel('True Label', fontsize=7)
ax.set_yticks(tick_marks)
ax.set_yticklabels(classes, fontsize=10, va ='center')
ax.yaxis.set_label_position('left')
ax.yaxis.tick_left()
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
ax.text(j, i, format(cm[i, j], 'd') if cm[i,j]!=0 else '.', horizontalalignment="center", fontsize=6, verticalalignment='center', color= "black")
fig.set_tight_layout(True)
summary = tfplot.figure.to_summary(fig, tag=tensor_name)
return summary