TensorFlow-7-TensorBoard Embedding可视化

学习资料
https://www.tensorflow.org/get_started/summaries_and_tensorboard

今天来看 TensorBoard 的一个内置的可视化工具 Embedding Projector, 是个交互式的可视化,可用来分析诸如 embeddings 的高维数据。
embedding projector 将从你的 checkpoint 文件中读取 embeddings。
默认情况下,embedding projector 会用 PCA 主成分分析方法将高维数据投影到 3D 空间, 还有一种投影方法是 T-SNE。

主要就是通过3步来实现这个可视化:

  1. Setup a 2D tensor that holds your embedding(s).
embedding_var = tf.Variable(....)
  1. Periodically save your model variables in a checkpoint in LOG_DIR.
saver = tf.train.Saver()
saver.save(session, os.path.join(LOG_DIR, "model.ckpt"), step)
  1. (Optional) Associate metadata with your embedding.

本节官方教程没有给出完整的例子,这里用 MNIST 举一个简单的例子。

1. 引入 projector,data,定义 path:

%matplotlib inline
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
import os

from tensorflow.contrib.tensorboard.plugins import projector
from tensorflow.examples.tutorials.mnist import input_data

LOG_DIR = 'minimalsample'
NAME_TO_VISUALISE_VARIABLE = "mnistembedding"
TO_EMBED_COUNT = 500


path_for_mnist_sprites =  os.path.join(LOG_DIR,'mnistdigits.png')
path_for_mnist_metadata =  os.path.join(LOG_DIR,'metadata.tsv')

mnist = input_data.read_data_sets("MNIST_data/", one_hot=False)
batch_xs, batch_ys = mnist.train.next_batch(TO_EMBED_COUNT)

2. 建立 embeddings,也就是前面的第一步,最主要的就是你要知道想可视化查看的 variable 的名字:

embedding_var = tf.Variable(batch_xs, name=NAME_TO_VISUALISE_VARIABLE)
summary_writer = tf.summary.FileWriter(LOG_DIR)

3. 建立 embedding projectorc:
这一步很重要,要指定想要可视化的 variable,metadata 文件的位置

config = projector.ProjectorConfig()
embedding = config.embeddings.add()
embedding.tensor_name = embedding_var.name

# Specify where you find the metadata
embedding.metadata_path = path_for_mnist_metadata #'metadata.tsv'

# Specify where you find the sprite (we will create this later)
embedding.sprite.image_path = path_for_mnist_sprites #'mnistdigits.png'
embedding.sprite.single_image_dim.extend([28,28])

# Say that you want to visualise the embeddings
projector.visualize_embeddings(summary_writer, config)

4. 保存,即上面第二步:
Tensorboard 会从保存的图形中加载保存的变量,所以初始化 session 和变量,并将其保存在 logdir 中,

sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
saver = tf.train.Saver()
saver.save(sess, os.path.join(LOG_DIR, "model.ckpt"), 1)

5. 定义 helper functions:

  • **create_sprite_image:** 将 sprits 整齐地对齐在方形画布上
  • **vector_to_matrix_mnist:** 将 MNIST 的 vector 数据形式转化为 images
  • **invert_grayscale: **将黑背景变为白背景
def create_sprite_image(images):
    """Returns a sprite image consisting of images passed as argument. Images should be count x width x height"""
    if isinstance(images, list):
        images = np.array(images)
    img_h = images.shape[1]
    img_w = images.shape[2]
    n_plots = int(np.ceil(np.sqrt(images.shape[0])))
    
    
    spriteimage = np.ones((img_h * n_plots ,img_w * n_plots ))
    
    for i in range(n_plots):
        for j in range(n_plots):
            this_filter = i * n_plots + j
            if this_filter < images.shape[0]:
                this_img = images[this_filter]
                spriteimage[i * img_h:(i + 1) * img_h,
                  j * img_w:(j + 1) * img_w] = this_img
    
    return spriteimage

def vector_to_matrix_mnist(mnist_digits):
    """Reshapes normal mnist digit (batch,28*28) to matrix (batch,28,28)"""
    return np.reshape(mnist_digits,(-1,28,28))

def invert_grayscale(mnist_digits):
    """ Makes black white, and white black """
    return 1-mnist_digits

6. 保存 sprite image:
将 vector 转换为 images,反转灰度,并创建并保存 sprite image。

to_visualise = batch_xs
to_visualise = vector_to_matrix_mnist(to_visualise)
to_visualise = invert_grayscale(to_visualise)

sprite_image = create_sprite_image(to_visualise)

plt.imsave(path_for_mnist_sprites,sprite_image,cmap='gray')
plt.imshow(sprite_image,cmap='gray')

7. 保存 metadata:
将数据写入 metadata,因为如果想在可视化时看到不同数字用不同颜色表示,需要知道每个 image 的标签,在这个 metadata 文件中有这样两列:”Index” , “Label”

with open(path_for_mnist_metadata,'w') as f:
    f.write("Index\tLabel\n")
    for index,label in enumerate(batch_ys):
        f.write("%d\t%d\n" % (index,label))

8. 执行:
我是用 jupyter notebook 写的,执行前面的代码后,会在当前 ipynb 所在文件夹下生成一个 minimalsample 文件夹,

要打开 tensorboard ,需要在终端执行:

$ tensorboard --logdir=YOUR FOLDER/minimalsample

9. 然后在 embeddings 中可以看到图了:

《TensorFlow-7-TensorBoard Embedding可视化》

如果提示了 metadata.tsv is not a file 这个错误,
那么,去 minimalsample 文件夹下会找到一个 projector_config.pbtxt 文件,把里面的 metadata_path: 和 image_path: 改为你的 metadata.tsv 和 mnistdigits.png 所在的绝对路径。

参考:
https://www.pinchofintelligence.com/simple-introduction-to-tensorboard-embedding-visualisation/

推荐阅读 历史技术博文链接汇总
http://www.jianshu.com/p/28f02bb59fe5
也许可以找到你想要的

    原文作者:不会停的蜗牛
    原文地址: https://www.jianshu.com/p/d5339d04aa17
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞