4
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

初心者がTensorBoardを呼び出してみた(Anaconda編)

Last updated at Posted at 2018-04-01

おっさんpythonビギナーです。最近はTnesorflowに挑戦中で、今回はTensorBoardの起動をまとめました。お役に立てばうれしいです。
(参照)「TensorFlowではじめるDeepLearning実装入門」

まずはログを取得します

お約束のmnistを使ってやってみます。

qiita.rb
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf

mnist = input_data.read_data_sets("data/", one_hot=True)

# 訓練用の入力データ、正解データをミニバッチ数指定
train_images, train_labels = mnist.train.next_batch(50)

# テスト用の全画像
test_images = mnist.test.images
# テスト用の全正解データ
test_labels = mnist.test.labels

# 入力データの定義
x = tf.placeholder(tf.float32, [None, 784])

# 入力画像をログに出力(1)
# reshapeの[-1]は「何も指定しない」という意味。「-1」をつけることを覚えておくと便利です。
img = tf.reshape(x, [-1, 28, 28, 1])
tf.summary.image('input_data', img, 10)

# 入力層から中間層へ
with tf.name_scope('hidden'):
    w_1 = tf.Variable(tf.truncated_normal([784, 64], stddev=0.1), name = 'w1')
    b_1 = tf.Variable(tf.zeros([64], name = 'b1'))
    h_1 = tf.nn.relu(tf.matmul(x, w_1) + b_1)
    
    #中間層の重みの分布をログ出力(2)
    tf.summary.histogram('w_1', w_1)

# 初期化
tf.truncated_normal([784, 64], stddev=0.1)
tf.matmul(x, w_1) 

# 中間層から出力層へ
with tf.name_scope('output'):
    w_2 = tf.Variable(tf.truncated_normal([64, 10], stddev=0.1), name = 'w2')
    b_2 = tf.Variable(tf.zeros([10], name = 'b2'))
    out = tf.nn.softmax(tf.matmul(h_1, w_2) + b_2)

y = tf.placeholder(tf.float32, [None, 10])

ここまでで2層のCNNが完成です。
そして、「入力画像(1)」と「中間層の重みの分布/ヒストグラム(2)」の2つを指定しています。
次に、損失関数と精度の設定を行います。

qiita.rb
# 誤差関数とログ出力(3)
with tf.name_scope('loss'):
    loss = tf.reduce_mean(tf.square(y - out))
    
    tf.summary.scalar('loss', loss)

# 訓練
with tf.name_scope('train'):
    train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

# 精度とログ出力(4)
with tf.name_scope('accuracy'):
    correct = tf.equal(tf.argmax(out, 1), tf.argmax(y, 1))
    accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))
    
    tf.summary.scalar('accuracy', accuracy)

# 全部初期化の呪文
init = tf.global_variables_initializer()

これで「誤差関数(3)」と「精度(4)」の2つのログが出力できました。
2つともスカラーなのでご注意を。

ログの統合と書き込みです

最後はsessで計算実行とこれまでの4つのログの統合(tf.summary.merge_all())と書き込み(tf.summary.FileWriter('logs', sess.graph) です。

qiita.rb
with tf.Session() as sess:
    
    sess.run(init)
    
    summary_op = tf.summary.merge_all()
    summary_writer = tf.summary.FileWriter('logs', sess.graph)  
      
    
     #テストデータをロード
    test_images = mnist.test.images
    test_labels = mnist.test.labels
    
    for i in range(1000):
        step = i + 1 
        train_images, train_labels = mnist.train.next_batch(50)
        sess.run(train_step, feed_dict={x:train_images, y:train_labels})
        
        if step % 10 == 0:
            
            #ログを取る処理を実行(出力はログ情報が書かれたプロトコルバッファ)
            summary_str = sess.run(summary_op, feed_dict={x:test_images, y:test_labels})
            
            #ログ情報のプロトコルバッファを書き込む
            summary_writer.add_summary(summary_str, step)

ここ、結構苦しみました。
summary_op、summary_writerをどこに置いていいかわからなかったです。色々な方のサイトを見て、最終的にいまの場所になりましたが、summary_opはwith tf.Session以下じゃなくても良いかも。でもsummary_writerはsess.graphがあるので、with tf.Session以下じゃないとダメだと思います。
あと、ログを取る処理とかログ情報のプロトコルバッファとか、いまだによくわかっていません(泣)

その上、初心者にはさらに色々面倒が降り続きます。

TensorBoardを起動します

ここまでは呼び出すものをコーディングしていたましたが、起動はちょっと異なります。色々なやり方がるようですが、Anacondaの方なら、このやり方がおススメです。
こちらを見ながらご説明します。

1.Anaconda NavigatorのEnvironmentからtensorflow13(私のバージョン)を起動します。
2.open terminalをクリックします。
@FukuharaYoheiさんの下記参照。https://qiita.com/FukuharaYohei/items/7ea120005f73cf882146

3.コーダー画面が出てきますので、次のようにtensorboard --logdir=以下にログファイルを格納したディレクタを指定します。

qiita.rb
(tensorflow13) C:\Users\●●●●(私の名前>tensorboard --logdir=C:\Users\●●●●\Tensorflow_DeepLearnig\logs

4.すると下記が返されるので、http://LAPTOP-1A7IV5KK:6006をコピーし、URLとして貼り付けてください。

qiita.rb
TensorBoard 1.5.1 at http://LAPTOP-1A7IV5KK:6006 (Press CTRL+C to quit)

TensorBoardが起動されました

こんな感じです。なんか、カッコいいですね。

「入力画像(1)」です。
tensorboard3.png

「中間層の重みの分布/ヒストグラム(2)」です。なぜかdistributionも表示されます。(まぁ、当然か)
tensorboard5.png

「誤差関数(loss)(3)」と「精度(accuracy(4)」です。
tensorboard1.png
tensorboard2.png

画像が上手く作れない方が問題でした、笑。

4
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?