2
4

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.

CollaboratoryのTensorflow2.0で簡単にTensorboardを利用

Last updated at Posted at 2019-09-24

Google CollaboratoryのTensorflow2.0はTensorboardが簡単に使える。メモ。

1. 準備

# tf-nightly-2.0-previewのインストール
%pip install tf-nightly-2.0-preview

import tensorflow as tf
from tensorflow.keras.layers import Input, Dense, Flatten, Dropout
from tensorflow.keras import Model
import datetime, os
print(tf.version)

# テスト用のFashion MNISTデータセットロード
fashion_mnist = tf.keras.datasets.fashion_mnist
(xTrain, yTrain),(xTest, yTest)=fashion_mnist.load_data()
# 正規化
xTrain,xTest = xTrain/255.0,xTest/255.0

2. Tensorboardの呼び出し

# Tensorboardの呼び出し
%load_ext tensorboard
# モニタリング用にTensorboardを表示
%tensorboard --logdir logs

最初は何もない
無題.png

3. 簡単なモデルの作成

def create_model():
  inputs = Input((xTrain.shape[1],xTrain.shape[2]))
  x = Flatten()(inputs)
  x = Dense(256, activation="relu")(x)
  x = Dense(256, activation="relu")(x)
  x = Dropout(0.2)(x)
  x = Dense(512, activation="relu")(x)
  predictions = Dense(10, activation='softmax')(x)
  model = Model(inputs=inputs, outputs=predictions)
  model.summary()
  return model

model = create_model()
model.compile(optimizer="adam",loss='sparse_categorical_crossentropy',metrics=['accuracy'])

4. コールバックにTensorboardを使用する定義

# ログディレクトリの命名
logdir = os.path.join("logs", datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))

# tensorbordコールバックの定義。histogram_freqは書き込み頻度。
# 少ないほど細かくなるが、重くなるので注意
tensorboard_callback = tf.keras.callbacks.TensorBoard(logdir, histogram_freq=1)

5. トレーニングの実行

コールバックにTensorboardを入れて、トレーニングを実施。

# トレーニングによるモデルの最適化
model.fit(x=xTrain, y=yTrain, epochs=30,validation_data=(xTest, yTest),callbacks=[tensorboard_callback])

これだけで先ほど呼び出したTensorboardでリアルタイムにモニタリング可能。
無題2.png

  • リアルタイムで更新されない場合は、'Write a regex to filter runs' のチェックボックスを一旦外して入れ直すと表示される。

先にTensorboardを呼び出してリアルタイムモニタリングを行うと、HistogramやDistributionなど、一部の項目が消えるバグがあるのが残念。
終了後のTensorboard呼び出しなら問題なし。

参考

2
4
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
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?