TensorFlow.org で表示 | Google Colab で実行 | GitHub でソースを表示 | ノートブックをダウンロード |
継続的に「最適な」モデルまたはモデルの重み/パラメータを保存することにより、トレーニングの進行状況を追跡したり、保存されたさまざまな状態から保存されたモデルを読み込んだりできます。
TensorFlow 1 で tf.estimator.Estimator
API を使用してトレーニング/検証中にチェックポイントの保存を構成するには、tf.estimator.RunConfig
でスケジュールを指定するか、tf.estimator.CheckpointSaverHook
を使用します。このガイドでは、このワークフローから TensorFlow 2 Keras API に移行する方法を実演します。
TensorFlow 2 では、さまざまな方法で tf.keras.callbacks.ModelCheckpoint
を構成できます。
save_best_only=True
パラメータを使用して監視された指標に従って、「最適な」バージョンを保存します。ここで、monitor
は、たとえば'loss'
、'val_loss'
、'accuracy'
、または 'val_accuracy'` などになります。save_freq
引数を使用して特定の頻度で継続的に保存します。save_weights_only
をTrue
に設定して、モデル全体ではなく重み/パラメータのみを保存します。
詳細については、tf.keras.callbacks.ModelCheckpoint
API ドキュメントと、モデルの保存と読み込みチュートリアルのトレーニング中にチェックポイントを保存するセクションを参照してください。チェックポイント形式の詳細については、Keras モデルの保存と読み込みガイドの TF チェックポイント形式セクションを参照してください。さらに、フォールトトレランスを追加するには、tf.keras.callbacks.BackupAndRestore
または tf.train.Checkpoint
を手動チェックポイントに使用できます。詳細は、フォールトトレランス移行ガイドを参照してください。
Keras コールバックは、組み込みの Keras Model.fit
/Model.evaluate
/Model.predict
API のトレーニング/評価/予測時のさまざまな時点で呼び出されるオブジェクトです。詳細は、ガイドの最後の 次のステップセクションを参照してください。
セットアップ
まず、インポートし、デモ用の単純なデータセットから始めます。
import tensorflow.compat.v1 as tf1
import tensorflow as tf
import numpy as np
import tempfile
2022-12-14 22:19:35.982014: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer.so.7'; dlerror: libnvinfer.so.7: cannot open shared object file: No such file or directory 2022-12-14 22:19:35.982118: W tensorflow/compiler/xla/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libnvinfer_plugin.so.7'; dlerror: libnvinfer_plugin.so.7: cannot open shared object file: No such file or directory 2022-12-14 22:19:35.982128: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Cannot dlopen some TensorRT libraries. If you would like to use Nvidia GPU with TensorRT, please make sure the missing libraries mentioned above are installed properly.
mnist = tf.keras.datasets.mnist
(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 API でチェックポイントを保存する
次の TensorFlow 1 の例は、tf.estimator.RunConfig
を構成し、tf.estimator.Estimator
API を使用してトレーニング/評価中にすべてのステップでチェックポイントを保存する方法を示しています。
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.2,
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)
INFO:tensorflow:Using config: {'_model_dir': '/tmpfs/tmp/tmptbkbr9xq', '_tf_random_seed': None, '_save_summary_steps': 1, '_save_checkpoints_steps': 1, '_save_checkpoints_secs': None, '_session_config': allow_soft_placement: true graph_options { rewrite_options { meta_optimizer_iterations: ONE } } , '_keep_checkpoint_max': 5, '_keep_checkpoint_every_n_hours': 10000, '_log_step_count_steps': 100, '_train_distribute': None, '_device_fn': None, '_protocol': None, '_eval_distribute': None, '_experimental_distribute': None, '_experimental_max_worker_delay_secs': None, '_session_creation_timeout_secs': 7200, '_checkpoint_save_graph_def': True, '_service': None, '_cluster_spec': ClusterSpec({}), '_task_type': 'worker', '_task_id': 0, '_global_id_in_cluster': 0, '_master': '', '_evaluation_master': '', '_is_chief': True, '_num_ps_replicas': 0, '_num_worker_replicas': 1} WARNING:tensorflow:From /tmpfs/tmp/ipykernel_166379/3980459272.py:18: The name tf.estimator.inputs is deprecated. Please use tf.compat.v1.estimator.inputs instead. WARNING:tensorflow:From /tmpfs/tmp/ipykernel_166379/3980459272.py:18: The name tf.estimator.inputs.numpy_input_fn is deprecated. Please use tf.compat.v1.estimator.inputs.numpy_input_fn instead. INFO:tensorflow:Not using Distribute Coordinator. INFO:tensorflow:Running training and evaluation locally (non-distributed). INFO:tensorflow:Start train and evaluate loop. The evaluate will happen after every checkpoint. Checkpoint frequency is determined based on RunConfig arguments: save_checkpoints_steps 1 or save_checkpoints_secs None. WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.9/site-packages/tensorflow/python/training/training_util.py:396: Variable.initialized_value (from tensorflow.python.ops.variables) is deprecated and will be removed in a future version. Instructions for updating: Use Variable.read_value. Variables in 2.X are initialized automatically both in eager and graph (inside tf.defun) contexts. WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.9/site-packages/tensorflow_estimator/python/estimator/inputs/queues/feeding_queue_runner.py:60: QueueRunner.__init__ (from tensorflow.python.training.queue_runner_impl) is deprecated and will be removed in a future version. Instructions for updating: To construct input pipelines, use the `tf.data` module. WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.9/site-packages/tensorflow_estimator/python/estimator/inputs/queues/feeding_functions.py:491: add_queue_runner (from tensorflow.python.training.queue_runner_impl) is deprecated and will be removed in a future version. Instructions for updating: To construct input pipelines, use the `tf.data` module. INFO:tensorflow:Calling model_fn. INFO:tensorflow:Done calling model_fn. INFO:tensorflow:Create CheckpointSaverHook. INFO:tensorflow:Graph was finalized. INFO:tensorflow:Running local_init_op. INFO:tensorflow:Done running local_init_op. WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.9/site-packages/tensorflow/python/training/monitored_session.py:910: start_queue_runners (from tensorflow.python.training.queue_runner_impl) is deprecated and will be removed in a future version. Instructions for updating: To construct input pipelines, use the `tf.data` module. 2022-12-14 22:19:41.847421: W tensorflow/core/common_runtime/type_inference.cc:339] Type inference failed. This indicates an invalid graph that escaped type checking. Error message: INVALID_ARGUMENT: expected compatible input types, but input 1: type_id: TFT_OPTIONAL args { type_id: TFT_PRODUCT args { type_id: TFT_TENSOR args { type_id: TFT_INT64 } } } is neither a subtype nor a supertype of the combined inputs preceding it: type_id: TFT_OPTIONAL args { type_id: TFT_PRODUCT args { type_id: TFT_TENSOR args { type_id: TFT_INT32 } } } while inferring type of node 'dnn/zero_fraction/cond/output/_18' INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 0... INFO:tensorflow:Saving checkpoints for 0 into /tmpfs/tmp/tmptbkbr9xq/model.ckpt. INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 0... INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 1... INFO:tensorflow:Saving checkpoints for 1 into /tmpfs/tmp/tmptbkbr9xq/model.ckpt. INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 1... INFO:tensorflow:Calling model_fn. INFO:tensorflow:Done calling model_fn. INFO:tensorflow:Starting evaluation at 2022-12-14T22:19:42 INFO:tensorflow:Graph was finalized. INFO:tensorflow:Restoring parameters from /tmpfs/tmp/tmptbkbr9xq/model.ckpt-1 INFO:tensorflow:Running local_init_op. INFO:tensorflow:Done running local_init_op. INFO:tensorflow:Evaluation [1/10] INFO:tensorflow:Evaluation [2/10] INFO:tensorflow:Evaluation [3/10] INFO:tensorflow:Evaluation [4/10] INFO:tensorflow:Evaluation [5/10] INFO:tensorflow:Evaluation [6/10] INFO:tensorflow:Evaluation [7/10] INFO:tensorflow:Evaluation [8/10] INFO:tensorflow:Evaluation [9/10] INFO:tensorflow:Evaluation [10/10] INFO:tensorflow:Inference Time : 0.29465s INFO:tensorflow:Finished evaluation at 2022-12-14-22:19:43 INFO:tensorflow:Saving dict for global step 1: accuracy = 0.17890625, average_loss = 2.2627082, global_step = 1, loss = 289.62665 INFO:tensorflow:Saving 'checkpoint_path' summary for global step 1: /tmpfs/tmp/tmptbkbr9xq/model.ckpt-1 INFO:tensorflow:loss = 116.153244, step = 0 INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 2... INFO:tensorflow:Saving checkpoints for 2 into /tmpfs/tmp/tmptbkbr9xq/model.ckpt. INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 2... INFO:tensorflow:Calling model_fn. INFO:tensorflow:Done calling model_fn. INFO:tensorflow:Starting evaluation at 2022-12-14T22:19:43 INFO:tensorflow:Graph was finalized. INFO:tensorflow:Restoring parameters from /tmpfs/tmp/tmptbkbr9xq/model.ckpt-2 INFO:tensorflow:Running local_init_op. INFO:tensorflow:Done running local_init_op. INFO:tensorflow:Evaluation [1/10] INFO:tensorflow:Evaluation [2/10] INFO:tensorflow:Evaluation [3/10] INFO:tensorflow:Evaluation [4/10] INFO:tensorflow:Evaluation [5/10] INFO:tensorflow:Evaluation [6/10] INFO:tensorflow:Evaluation [7/10] INFO:tensorflow:Evaluation [8/10] INFO:tensorflow:Evaluation [9/10] INFO:tensorflow:Evaluation [10/10] INFO:tensorflow:Inference Time : 0.29887s INFO:tensorflow:Finished evaluation at 2022-12-14-22:19:43 INFO:tensorflow:Saving dict for global step 2: accuracy = 0.2578125, average_loss = 2.1816313, global_step = 2, loss = 279.2488 INFO:tensorflow:Saving 'checkpoint_path' summary for global step 2: /tmpfs/tmp/tmptbkbr9xq/model.ckpt-2 INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 3... INFO:tensorflow:Saving checkpoints for 3 into /tmpfs/tmp/tmptbkbr9xq/model.ckpt. INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 3... INFO:tensorflow:Calling model_fn. INFO:tensorflow:Done calling model_fn. INFO:tensorflow:Starting evaluation at 2022-12-14T22:19:44 INFO:tensorflow:Graph was finalized. INFO:tensorflow:Restoring parameters from /tmpfs/tmp/tmptbkbr9xq/model.ckpt-3 INFO:tensorflow:Running local_init_op. INFO:tensorflow:Done running local_init_op. INFO:tensorflow:Evaluation [1/10] INFO:tensorflow:Evaluation [2/10] INFO:tensorflow:Evaluation [3/10] INFO:tensorflow:Evaluation [4/10] INFO:tensorflow:Evaluation [5/10] INFO:tensorflow:Evaluation [6/10] INFO:tensorflow:Evaluation [7/10] INFO:tensorflow:Evaluation [8/10] INFO:tensorflow:Evaluation [9/10] INFO:tensorflow:Evaluation [10/10] INFO:tensorflow:Inference Time : 0.29108s INFO:tensorflow:Finished evaluation at 2022-12-14-22:19:44 INFO:tensorflow:Saving dict for global step 3: accuracy = 0.359375, average_loss = 2.1088977, global_step = 3, loss = 269.9389 INFO:tensorflow:Saving 'checkpoint_path' summary for global step 3: /tmpfs/tmp/tmptbkbr9xq/model.ckpt-3 INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 4... INFO:tensorflow:Saving checkpoints for 4 into /tmpfs/tmp/tmptbkbr9xq/model.ckpt. INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 4... INFO:tensorflow:Calling model_fn. INFO:tensorflow:Done calling model_fn. INFO:tensorflow:Starting evaluation at 2022-12-14T22:19:44 INFO:tensorflow:Graph was finalized. INFO:tensorflow:Restoring parameters from /tmpfs/tmp/tmptbkbr9xq/model.ckpt-4 INFO:tensorflow:Running local_init_op. INFO:tensorflow:Done running local_init_op. INFO:tensorflow:Evaluation [1/10] INFO:tensorflow:Evaluation [2/10] INFO:tensorflow:Evaluation [3/10] INFO:tensorflow:Evaluation [4/10] INFO:tensorflow:Evaluation [5/10] INFO:tensorflow:Evaluation [6/10] INFO:tensorflow:Evaluation [7/10] INFO:tensorflow:Evaluation [8/10] INFO:tensorflow:Evaluation [9/10] INFO:tensorflow:Evaluation [10/10] INFO:tensorflow:Inference Time : 0.28675s INFO:tensorflow:Finished evaluation at 2022-12-14-22:19:45 INFO:tensorflow:Saving dict for global step 4: accuracy = 0.396875, average_loss = 2.0425932, global_step = 4, loss = 261.45193 INFO:tensorflow:Saving 'checkpoint_path' summary for global step 4: /tmpfs/tmp/tmptbkbr9xq/model.ckpt-4 INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 5... INFO:tensorflow:Saving checkpoints for 5 into /tmpfs/tmp/tmptbkbr9xq/model.ckpt. WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.9/site-packages/tensorflow/python/training/saver.py:1064: remove_checkpoint (from tensorflow.python.checkpoint.checkpoint_management) is deprecated and will be removed in a future version. Instructions for updating: Use standard file APIs to delete files with this prefix. INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 5... INFO:tensorflow:Calling model_fn. INFO:tensorflow:Done calling model_fn. INFO:tensorflow:Starting evaluation at 2022-12-14T22:19:45 INFO:tensorflow:Graph was finalized. INFO:tensorflow:Restoring parameters from /tmpfs/tmp/tmptbkbr9xq/model.ckpt-5 INFO:tensorflow:Running local_init_op. INFO:tensorflow:Done running local_init_op. INFO:tensorflow:Evaluation [1/10] INFO:tensorflow:Evaluation [2/10] INFO:tensorflow:Evaluation [3/10] INFO:tensorflow:Evaluation [4/10] INFO:tensorflow:Evaluation [5/10] INFO:tensorflow:Evaluation [6/10] INFO:tensorflow:Evaluation [7/10] INFO:tensorflow:Evaluation [8/10] INFO:tensorflow:Evaluation [9/10] INFO:tensorflow:Evaluation [10/10] INFO:tensorflow:Inference Time : 0.29010s INFO:tensorflow:Finished evaluation at 2022-12-14-22:19:45 INFO:tensorflow:Saving dict for global step 5: accuracy = 0.428125, average_loss = 1.9790913, global_step = 5, loss = 253.32368 INFO:tensorflow:Saving 'checkpoint_path' summary for global step 5: /tmpfs/tmp/tmptbkbr9xq/model.ckpt-5 INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 6... INFO:tensorflow:Saving checkpoints for 6 into /tmpfs/tmp/tmptbkbr9xq/model.ckpt. INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 6... INFO:tensorflow:Calling model_fn. INFO:tensorflow:Done calling model_fn. INFO:tensorflow:Starting evaluation at 2022-12-14T22:19:45 INFO:tensorflow:Graph was finalized. INFO:tensorflow:Restoring parameters from /tmpfs/tmp/tmptbkbr9xq/model.ckpt-6 INFO:tensorflow:Running local_init_op. INFO:tensorflow:Done running local_init_op. INFO:tensorflow:Evaluation [1/10] INFO:tensorflow:Evaluation [2/10] INFO:tensorflow:Evaluation [3/10] INFO:tensorflow:Evaluation [4/10] INFO:tensorflow:Evaluation [5/10] INFO:tensorflow:Evaluation [6/10] INFO:tensorflow:Evaluation [7/10] INFO:tensorflow:Evaluation [8/10] INFO:tensorflow:Evaluation [9/10] INFO:tensorflow:Evaluation [10/10] INFO:tensorflow:Inference Time : 0.29371s INFO:tensorflow:Finished evaluation at 2022-12-14-22:19:46 INFO:tensorflow:Saving dict for global step 6: accuracy = 0.465625, average_loss = 1.9187992, global_step = 6, loss = 245.6063 INFO:tensorflow:Saving 'checkpoint_path' summary for global step 6: /tmpfs/tmp/tmptbkbr9xq/model.ckpt-6 INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 7... INFO:tensorflow:Saving checkpoints for 7 into /tmpfs/tmp/tmptbkbr9xq/model.ckpt. INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 7... INFO:tensorflow:Calling model_fn. INFO:tensorflow:Done calling model_fn. INFO:tensorflow:Starting evaluation at 2022-12-14T22:19:46 INFO:tensorflow:Graph was finalized. INFO:tensorflow:Restoring parameters from /tmpfs/tmp/tmptbkbr9xq/model.ckpt-7 INFO:tensorflow:Running local_init_op. INFO:tensorflow:Done running local_init_op. INFO:tensorflow:Evaluation [1/10] INFO:tensorflow:Evaluation [2/10] INFO:tensorflow:Evaluation [3/10] INFO:tensorflow:Evaluation [4/10] INFO:tensorflow:Evaluation [5/10] INFO:tensorflow:Evaluation [6/10] INFO:tensorflow:Evaluation [7/10] INFO:tensorflow:Evaluation [8/10] INFO:tensorflow:Evaluation [9/10] INFO:tensorflow:Evaluation [10/10] INFO:tensorflow:Inference Time : 0.29495s INFO:tensorflow:Finished evaluation at 2022-12-14-22:19:46 INFO:tensorflow:Saving dict for global step 7: accuracy = 0.48515624, average_loss = 1.8596061, global_step = 7, loss = 238.02959 INFO:tensorflow:Saving 'checkpoint_path' summary for global step 7: /tmpfs/tmp/tmptbkbr9xq/model.ckpt-7 INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 8... INFO:tensorflow:Saving checkpoints for 8 into /tmpfs/tmp/tmptbkbr9xq/model.ckpt. INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 8... INFO:tensorflow:Calling model_fn. INFO:tensorflow:Done calling model_fn. INFO:tensorflow:Starting evaluation at 2022-12-14T22:19:47 INFO:tensorflow:Graph was finalized. INFO:tensorflow:Restoring parameters from /tmpfs/tmp/tmptbkbr9xq/model.ckpt-8 INFO:tensorflow:Running local_init_op. INFO:tensorflow:Done running local_init_op. INFO:tensorflow:Evaluation [1/10] INFO:tensorflow:Evaluation [2/10] INFO:tensorflow:Evaluation [3/10] INFO:tensorflow:Evaluation [4/10] INFO:tensorflow:Evaluation [5/10] INFO:tensorflow:Evaluation [6/10] INFO:tensorflow:Evaluation [7/10] INFO:tensorflow:Evaluation [8/10] INFO:tensorflow:Evaluation [9/10] INFO:tensorflow:Evaluation [10/10] INFO:tensorflow:Inference Time : 0.29156s INFO:tensorflow:Finished evaluation at 2022-12-14-22:19:47 INFO:tensorflow:Saving dict for global step 8: accuracy = 0.49921876, average_loss = 1.8010334, global_step = 8, loss = 230.53227 INFO:tensorflow:Saving 'checkpoint_path' summary for global step 8: /tmpfs/tmp/tmptbkbr9xq/model.ckpt-8 INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 9... INFO:tensorflow:Saving checkpoints for 9 into /tmpfs/tmp/tmptbkbr9xq/model.ckpt. INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 9... INFO:tensorflow:Calling model_fn. INFO:tensorflow:Done calling model_fn. INFO:tensorflow:Starting evaluation at 2022-12-14T22:19:47 INFO:tensorflow:Graph was finalized. INFO:tensorflow:Restoring parameters from /tmpfs/tmp/tmptbkbr9xq/model.ckpt-9 INFO:tensorflow:Running local_init_op. INFO:tensorflow:Done running local_init_op. INFO:tensorflow:Evaluation [1/10] INFO:tensorflow:Evaluation [2/10] INFO:tensorflow:Evaluation [3/10] INFO:tensorflow:Evaluation [4/10] INFO:tensorflow:Evaluation [5/10] INFO:tensorflow:Evaluation [6/10] INFO:tensorflow:Evaluation [7/10] INFO:tensorflow:Evaluation [8/10] INFO:tensorflow:Evaluation [9/10] INFO:tensorflow:Evaluation [10/10] INFO:tensorflow:Inference Time : 0.29311s INFO:tensorflow:Finished evaluation at 2022-12-14-22:19:48 INFO:tensorflow:Saving dict for global step 9: accuracy = 0.5203125, average_loss = 1.7437397, global_step = 9, loss = 223.19868 INFO:tensorflow:Saving 'checkpoint_path' summary for global step 9: /tmpfs/tmp/tmptbkbr9xq/model.ckpt-9 INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 10... INFO:tensorflow:Saving checkpoints for 10 into /tmpfs/tmp/tmptbkbr9xq/model.ckpt. INFO:tensorflow:Calling checkpoint listeners after saving checkpoint 10... INFO:tensorflow:Calling model_fn. INFO:tensorflow:Done calling model_fn. INFO:tensorflow:Starting evaluation at 2022-12-14T22:19:48 INFO:tensorflow:Graph was finalized. INFO:tensorflow:Restoring parameters from /tmpfs/tmp/tmptbkbr9xq/model.ckpt-10 INFO:tensorflow:Running local_init_op. INFO:tensorflow:Done running local_init_op. INFO:tensorflow:Evaluation [1/10] INFO:tensorflow:Evaluation [2/10] INFO:tensorflow:Evaluation [3/10] INFO:tensorflow:Evaluation [4/10] INFO:tensorflow:Evaluation [5/10] INFO:tensorflow:Evaluation [6/10] INFO:tensorflow:Evaluation [7/10] INFO:tensorflow:Evaluation [8/10] INFO:tensorflow:Evaluation [9/10] INFO:tensorflow:Evaluation [10/10] INFO:tensorflow:Inference Time : 0.28665s INFO:tensorflow:Finished evaluation at 2022-12-14-22:19:48 INFO:tensorflow:Saving dict for global step 10: accuracy = 0.5359375, average_loss = 1.6840875, global_step = 10, loss = 215.5632 INFO:tensorflow:Saving 'checkpoint_path' summary for global step 10: /tmpfs/tmp/tmptbkbr9xq/model.ckpt-10 INFO:tensorflow:Loss for final step: 82.37556. ({'accuracy': 0.5359375, 'average_loss': 1.6840875, 'loss': 215.5632, 'global_step': 10}, [])
%ls {classifier.model_dir}
checkpoint eval/ events.out.tfevents.1671056381.kokoro-gcp-ubuntu-prod-137133934 graph.pbtxt model.ckpt-10.data-00000-of-00001 model.ckpt-10.index model.ckpt-10.meta model.ckpt-6.data-00000-of-00001 model.ckpt-6.index model.ckpt-6.meta model.ckpt-7.data-00000-of-00001 model.ckpt-7.index model.ckpt-7.meta model.ckpt-8.data-00000-of-00001 model.ckpt-8.index model.ckpt-8.meta model.ckpt-9.data-00000-of-00001 model.ckpt-9.index model.ckpt-9.meta
TensorFlow 2: Model.fit の Keras コールバックでチェックポイントを保存する
TensorFlow 2 では、組み込みの Keras Model.fit
(または Model.evaluate
)をトレーニング/評価に使用する場合、tf.keras. callbacks.ModelCheckpoint
を作成し、それを Model.fit
(または Model.evaluate
)の callbacks
パラメータに渡します。(詳細については、API ドキュメントと、組み込みメソッドを使用したトレーニングと評価ガイドのコールバックの使用セクションを参照してください。)
以下の例では、tf.keras.callbacks.ModelCheckpoint
コールバックを使用して、チェックポイントを一時ディレクトリに保存します。
def create_model():
return tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(512, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation='softmax')
])
model = create_model()
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'],
steps_per_execution=10)
log_dir = tempfile.mkdtemp()
model_checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(
filepath=log_dir)
model.fit(x=x_train,
y=y_train,
epochs=10,
validation_data=(x_test, y_test),
callbacks=[model_checkpoint_callback])
Epoch 1/10 1860/1875 [============================>.] - ETA: 0s - loss: 0.2182 - accuracy: 0.9359INFO:tensorflow:Assets written to: /tmpfs/tmp/tmpy_tezxzp/assets 1875/1875 [==============================] - 5s 2ms/step - loss: 0.2174 - accuracy: 0.9361 - val_loss: 0.1044 - val_accuracy: 0.9684 Epoch 2/10 1860/1875 [============================>.] - ETA: 0s - loss: 0.0975 - accuracy: 0.9699INFO:tensorflow:Assets written to: /tmpfs/tmp/tmpy_tezxzp/assets 1875/1875 [==============================] - 3s 2ms/step - loss: 0.0979 - accuracy: 0.9699 - val_loss: 0.0954 - val_accuracy: 0.9685 Epoch 3/10 1860/1875 [============================>.] - ETA: 0s - loss: 0.0670 - accuracy: 0.9789INFO:tensorflow:Assets written to: /tmpfs/tmp/tmpy_tezxzp/assets 1875/1875 [==============================] - 3s 2ms/step - loss: 0.0669 - accuracy: 0.9790 - val_loss: 0.0748 - val_accuracy: 0.9759 Epoch 4/10 1860/1875 [============================>.] - ETA: 0s - loss: 0.0520 - accuracy: 0.9830INFO:tensorflow:Assets written to: /tmpfs/tmp/tmpy_tezxzp/assets 1875/1875 [==============================] - 3s 2ms/step - loss: 0.0522 - accuracy: 0.9830 - val_loss: 0.0742 - val_accuracy: 0.9766 Epoch 5/10 1860/1875 [============================>.] - ETA: 0s - loss: 0.0430 - accuracy: 0.9858INFO:tensorflow:Assets written to: /tmpfs/tmp/tmpy_tezxzp/assets 1875/1875 [==============================] - 3s 2ms/step - loss: 0.0432 - accuracy: 0.9858 - val_loss: 0.0723 - val_accuracy: 0.9792 Epoch 6/10 1860/1875 [============================>.] - ETA: 0s - loss: 0.0357 - accuracy: 0.9883INFO:tensorflow:Assets written to: /tmpfs/tmp/tmpy_tezxzp/assets 1875/1875 [==============================] - 3s 2ms/step - loss: 0.0357 - accuracy: 0.9883 - val_loss: 0.0654 - val_accuracy: 0.9808 Epoch 7/10 1860/1875 [============================>.] - ETA: 0s - loss: 0.0305 - accuracy: 0.9898INFO:tensorflow:Assets written to: /tmpfs/tmp/tmpy_tezxzp/assets 1875/1875 [==============================] - 3s 2ms/step - loss: 0.0304 - accuracy: 0.9898 - val_loss: 0.0675 - val_accuracy: 0.9815 Epoch 8/10 1860/1875 [============================>.] - ETA: 0s - loss: 0.0270 - accuracy: 0.9906INFO:tensorflow:Assets written to: /tmpfs/tmp/tmpy_tezxzp/assets 1875/1875 [==============================] - 3s 2ms/step - loss: 0.0270 - accuracy: 0.9906 - val_loss: 0.0747 - val_accuracy: 0.9793 Epoch 9/10 1860/1875 [============================>.] - ETA: 0s - loss: 0.0245 - accuracy: 0.9919INFO:tensorflow:Assets written to: /tmpfs/tmp/tmpy_tezxzp/assets 1875/1875 [==============================] - 3s 2ms/step - loss: 0.0245 - accuracy: 0.9919 - val_loss: 0.0733 - val_accuracy: 0.9808 Epoch 10/10 1860/1875 [============================>.] - ETA: 0s - loss: 0.0210 - accuracy: 0.9927INFO:tensorflow:Assets written to: /tmpfs/tmp/tmpy_tezxzp/assets 1875/1875 [==============================] - 3s 2ms/step - loss: 0.0210 - accuracy: 0.9927 - val_loss: 0.0726 - val_accuracy: 0.9804 <keras.callbacks.History at 0x7fe4a0224fa0>
%ls {model_checkpoint_callback.filepath}
assets/ fingerprint.pb keras_metadata.pb saved_model.pb variables/
次のステップ
チェックポイントの詳細については、次を参照してください。
- API ドキュメント:
tf.keras.callbacks.ModelCheckpoint
- チュートリアル: モデルの保存と読み込み(トレーニング中にチェックポイントを保存するセクション)
- ガイド: Keras モデルの保存と読み込み(TF チェックポイント形式 セクション)
コールバックの詳細については、次を参照してください。
- API ドキュメント:
tf.keras.callbacks.Callback
- ガイド: コールバックを記述する
- ガイド: 組み込みメソッドを使用したトレーニングと評価(コールバックの使用セクション)
次の移行関連のリソースも参照してください。
- フォールトトレランス移行ガイド:
Model.fit
用のtf.keras.callbacks.BackupAndRestore
、または、カスタムトレーニングループ用のtf.train.Checkpoint
およびtf.train.CheckpointManager
API - 早期停止移行ガイド:
tf.keras.callbacks.EarlyStopping
は組み込みの早期停止コールバックです - TensorBoard 移行ガイド: TensorBoard により、指標の追跡と表示が可能になります
- LoggingTensorHook と StopAtStepHook から Keras コールバックへの移行ガイド
- SessionRunHook から Keras コールバックへのガイド