TensorboardでMNISTのデータをグリグリ回して観察してみた[PCA][t-SNE]
TensorFlow 0.12から”Embedding Visualization”というものが追加され, データをグリグリ回しながら3次元的に観察できるようになった.
そこで, 本記事では下の方のわかりやすい説明を参考に(ほぼコピペだが)MNISTのデータをグリグリ回して観察することに挑戦.
本記事のコードを順番通りに実行すれば, MNISTの可視化が行えるようになっている. 自身でデータをダウンロードする必要ないので楽ちんだ.
また, ソースに%matplotlib inlineの記述があったので, JupyterNotebookで実行した.
まずはライブラリとパスを追加
%matplotlib inlineimport matplotlib.pyplot as pltimport tensorflow as tfimport numpy as npimport osfrom tensorflow.contrib.tensorboard.plugins import projectorfrom tensorflow.examples.tutorials.mnist import input_dataLOG_DIR = 'minimalsample'NAME_TO_VISUALISE_VARIABLE = "mnistembedding"TO_EMBED_COUNT = 500path_for_mnist_sprites = os.path.join(LOG_DIR,'mnistdigits.png')path_for_mnist_metadata = os.path.join(LOG_DIR,'metadata.tsv')MNISTのデータをダウンロードしてくる
ちなみにMNISTのサイズは28*28=784
mnist = input_data.read_data_sets("MNIST_data/", one_hot=False)batch_xs, batch_ys = mnist.train.next_batch(TO_EMBED_COUNT)MNISTをTensorflowで扱うためEmbedding
embedding_var = tf.Variable(batch_xs, name=NAME_TO_VISUALISE_VARIABLE)summary_writer = tf.summary.FileWriter(LOG_DIR)データを可視化する為のパラメータの設定
リンク元のコードのようにパスの指定すると, ファイルが読み取れないので2点修正した.
config = projector.ProjectorConfig()embedding = config.embeddings.add()embedding.tensor_name = embedding_var.name# Specify where you find the metadataembedding.metadata_path = "metadata.tsv" # 1つ目の修正はココ!# Specify where you find the sprite (we will create this later)embedding.sprite.image_path = "mnistdigits.png" # 2つ目の修正はココ!embedding.sprite.single_image_dim.extend([28,28])# Say that you want to visualise the embeddingsprojector.visualize_embeddings(summary_writer, config)データを保存
sess = tf.InteractiveSession()sess.run(tf.global_variables_initializer())saver = tf.train.Saver()saver.save(sess, os.path.join(LOG_DIR, "model.ckpt"), 1)分割された画像を作成するための関数の定義
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 + jif this_filter
#### メタデータを保存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))
#### Tensorboardを開く
[コマンドプロンプト](http://d.hatena.ne.jp/keyword/%A5%B3%A5%DE%A5%F3%A5%C9%A5%D7%A5%ED%A5%F3%A5%D7%A5%C8)から以下のコマンドを実行し,tensorboard –logdir=minimalsample
[Webブラウザ](http://d.hatena.ne.jp/keyword/Web%A5%D6%A5%E9%A5%A6%A5%B6)で[http://127.0.0.1:6006](http://127.0.0.1:6006)に接続すれば可視化結果が見れる.(筆者の環境ではなぜか[Firefox](http://d.hatena.ne.jp/keyword/Firefox)では見れないのだが, [Chromium](http://d.hatena.ne.jp/keyword/Chromium)にすると見れるようになった)