![]() |
![]() |
![]() |
![]() |
TensorBoard 是一種內建工具,用於在 TensorFlow 中提供測量和視覺化。常見的機器學習實驗指標 (例如準確度和損失) 可以在 TensorBoard 中追蹤和顯示。TensorBoard 與 TensorFlow 1 和 2 程式碼相容。
在 TensorFlow 1 中,tf.estimator.Estimator
預設會儲存 TensorBoard 的摘要。相較之下,在 TensorFlow 2 中,可以使用 tf.keras.callbacks.TensorBoard
回呼來儲存摘要。
本指南示範如何使用 TensorBoard,首先在 TensorFlow 1 中搭配 Estimator 使用,然後說明如何在 TensorFlow 2 中執行對等程序。
設定
import tensorflow.compat.v1 as tf1
import tensorflow as tf
import tempfile
import numpy as np
import datetime
%load_ext tensorboard
mnist = tf.keras.datasets.mnist # The MNIST dataset.
(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
TensorFlow 1:搭配 tf.estimator 的 TensorBoard
在此 TensorFlow 1 範例中,您會執行個體化 tf.estimator.DNNClassifier
、在 MNIST 資料集上訓練和評估它,並使用 TensorBoard 顯示指標
%reload_ext tensorboard
feature_columns = [tf1.feature_column.numeric_column("x", shape=[28, 28])]
config = tf1.estimator.RunConfig(save_summary_steps=1,
save_checkpoints_steps=1)
path = tempfile.mkdtemp()
classifier = tf1.estimator.DNNClassifier(
feature_columns=feature_columns,
hidden_units=[256, 32],
optimizer=tf1.train.AdamOptimizer(0.001),
n_classes=10,
dropout=0.1,
model_dir=path,
config = config
)
train_input_fn = tf1.estimator.inputs.numpy_input_fn(
x={"x": x_train},
y=y_train.astype(np.int32),
num_epochs=10,
batch_size=50,
shuffle=True,
)
test_input_fn = tf1.estimator.inputs.numpy_input_fn(
x={"x": x_test},
y=y_test.astype(np.int32),
num_epochs=10,
shuffle=False
)
train_spec = tf1.estimator.TrainSpec(input_fn=train_input_fn, max_steps=10)
eval_spec = tf1.estimator.EvalSpec(input_fn=test_input_fn,
steps=10,
throttle_secs=0)
tf1.estimator.train_and_evaluate(estimator=classifier,
train_spec=train_spec,
eval_spec=eval_spec)
%tensorboard --logdir {classifier.model_dir}
TensorFlow 2:搭配 Keras 回呼和 Model.fit 的 TensorBoard
在此 TensorFlow 2 範例中,您可以使用 tf.keras.callbacks.TensorBoard
回呼建立和儲存記錄,並訓練模型。此回呼會追蹤每個 epoch 的準確度和損失。它會在 callbacks
清單中傳遞至 Model.fit
。
%reload_ext tensorboard
def create_model():
return tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28), name='layers_flatten'),
tf.keras.layers.Dense(512, activation='relu', name='layers_dense'),
tf.keras.layers.Dropout(0.2, name='layers_dropout'),
tf.keras.layers.Dense(10, activation='softmax', name='layers_dense_2')
])
model = create_model()
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'],
steps_per_execution=10)
log_dir = tempfile.mkdtemp()
tensorboard_callback = tf.keras.callbacks.TensorBoard(
log_dir=log_dir,
histogram_freq=1) # Enable histogram computation with each epoch.
model.fit(x=x_train,
y=y_train,
epochs=10,
validation_data=(x_test, y_test),
callbacks=[tensorboard_callback])
%tensorboard --logdir {tensorboard_callback.log_dir}
後續步驟
- 請參閱入門指南,進一步瞭解 TensorBoard。
- 如需較低層級的 API,請參閱tf.summary 遷移至 TensorFlow 2 指南。