체크포인트 저장 항목 마이그레이션하기

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', or'val_accuracy'`일 수 있습니다.
  • 정 빈도로 계속 저장합니다(save_freq 인수 사용).
  • save_weights_onlyTrue로 설정하여 전체 모델 대신 가중치/매개변수만 저장합니다.

자세한 내용은 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 20:18:02.737194: 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 20:18:02.737296: 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 20:18:02.737307: 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
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz
11490434/11490434 [==============================] - 0s 0us/step

TensorFlow 1: tf.estimator API를 사용하여 체크포인트 저장하기

이 TensorFlow 1 예제는 tf.estimator.Estimator API를 사용하여 훈련/평가를 진행하는 동안 모든 단계에서 체크포인트를 저장하도록 tf.estimator.RunConfig를 구성하는 방법을 보여줍니다.

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/tmp5q4yfi6u', '_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_24812/3980459272.py:18: The name tf.estimator.inputs is deprecated. Please use tf.compat.v1.estimator.inputs instead.

WARNING:tensorflow:From /tmpfs/tmp/ipykernel_24812/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 20:18:08.687025: 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/tmp5q4yfi6u/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/tmp5q4yfi6u/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-14T20:18:09
INFO:tensorflow:Graph was finalized.
INFO:tensorflow:Restoring parameters from /tmpfs/tmp/tmp5q4yfi6u/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.29615s
INFO:tensorflow:Finished evaluation at 2022-12-14-20:18:10
INFO:tensorflow:Saving dict for global step 1: accuracy = 0.1140625, average_loss = 2.3028054, global_step = 1, loss = 294.7591
INFO:tensorflow:Saving 'checkpoint_path' summary for global step 1: /tmpfs/tmp/tmp5q4yfi6u/model.ckpt-1
INFO:tensorflow:loss = 125.672775, step = 0
INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 2...
INFO:tensorflow:Saving checkpoints for 2 into /tmpfs/tmp/tmp5q4yfi6u/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-14T20:18:10
INFO:tensorflow:Graph was finalized.
INFO:tensorflow:Restoring parameters from /tmpfs/tmp/tmp5q4yfi6u/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.29242s
INFO:tensorflow:Finished evaluation at 2022-12-14-20:18:10
INFO:tensorflow:Saving dict for global step 2: accuracy = 0.14765625, average_loss = 2.2573345, global_step = 2, loss = 288.9388
INFO:tensorflow:Saving 'checkpoint_path' summary for global step 2: /tmpfs/tmp/tmp5q4yfi6u/model.ckpt-2
INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 3...
INFO:tensorflow:Saving checkpoints for 3 into /tmpfs/tmp/tmp5q4yfi6u/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-14T20:18:11
INFO:tensorflow:Graph was finalized.
INFO:tensorflow:Restoring parameters from /tmpfs/tmp/tmp5q4yfi6u/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.29277s
INFO:tensorflow:Finished evaluation at 2022-12-14-20:18:11
INFO:tensorflow:Saving dict for global step 3: accuracy = 0.1984375, average_loss = 2.2285006, global_step = 3, loss = 285.24808
INFO:tensorflow:Saving 'checkpoint_path' summary for global step 3: /tmpfs/tmp/tmp5q4yfi6u/model.ckpt-3
INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 4...
INFO:tensorflow:Saving checkpoints for 4 into /tmpfs/tmp/tmp5q4yfi6u/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-14T20:18:11
INFO:tensorflow:Graph was finalized.
INFO:tensorflow:Restoring parameters from /tmpfs/tmp/tmp5q4yfi6u/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.28378s
INFO:tensorflow:Finished evaluation at 2022-12-14-20:18:11
INFO:tensorflow:Saving dict for global step 4: accuracy = 0.259375, average_loss = 2.1974502, global_step = 4, loss = 281.27362
INFO:tensorflow:Saving 'checkpoint_path' summary for global step 4: /tmpfs/tmp/tmp5q4yfi6u/model.ckpt-4
INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 5...
INFO:tensorflow:Saving checkpoints for 5 into /tmpfs/tmp/tmp5q4yfi6u/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-14T20:18:12
INFO:tensorflow:Graph was finalized.
INFO:tensorflow:Restoring parameters from /tmpfs/tmp/tmp5q4yfi6u/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.28637s
INFO:tensorflow:Finished evaluation at 2022-12-14-20:18:12
INFO:tensorflow:Saving dict for global step 5: accuracy = 0.334375, average_loss = 2.1632705, global_step = 5, loss = 276.89862
INFO:tensorflow:Saving 'checkpoint_path' summary for global step 5: /tmpfs/tmp/tmp5q4yfi6u/model.ckpt-5
INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 6...
INFO:tensorflow:Saving checkpoints for 6 into /tmpfs/tmp/tmp5q4yfi6u/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-14T20:18:12
INFO:tensorflow:Graph was finalized.
INFO:tensorflow:Restoring parameters from /tmpfs/tmp/tmp5q4yfi6u/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.30018s
INFO:tensorflow:Finished evaluation at 2022-12-14-20:18:13
INFO:tensorflow:Saving dict for global step 6: accuracy = 0.396875, average_loss = 2.1213017, global_step = 6, loss = 271.5266
INFO:tensorflow:Saving 'checkpoint_path' summary for global step 6: /tmpfs/tmp/tmp5q4yfi6u/model.ckpt-6
INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 7...
INFO:tensorflow:Saving checkpoints for 7 into /tmpfs/tmp/tmp5q4yfi6u/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-14T20:18:13
INFO:tensorflow:Graph was finalized.
INFO:tensorflow:Restoring parameters from /tmpfs/tmp/tmp5q4yfi6u/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.28544s
INFO:tensorflow:Finished evaluation at 2022-12-14-20:18:13
INFO:tensorflow:Saving dict for global step 7: accuracy = 0.434375, average_loss = 2.0747333, global_step = 7, loss = 265.56586
INFO:tensorflow:Saving 'checkpoint_path' summary for global step 7: /tmpfs/tmp/tmp5q4yfi6u/model.ckpt-7
INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 8...
INFO:tensorflow:Saving checkpoints for 8 into /tmpfs/tmp/tmp5q4yfi6u/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-14T20:18:13
INFO:tensorflow:Graph was finalized.
INFO:tensorflow:Restoring parameters from /tmpfs/tmp/tmp5q4yfi6u/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.28652s
INFO:tensorflow:Finished evaluation at 2022-12-14-20:18:14
INFO:tensorflow:Saving dict for global step 8: accuracy = 0.42734376, average_loss = 2.026875, global_step = 8, loss = 259.44
INFO:tensorflow:Saving 'checkpoint_path' summary for global step 8: /tmpfs/tmp/tmp5q4yfi6u/model.ckpt-8
INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 9...
INFO:tensorflow:Saving checkpoints for 9 into /tmpfs/tmp/tmp5q4yfi6u/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-14T20:18:14
INFO:tensorflow:Graph was finalized.
INFO:tensorflow:Restoring parameters from /tmpfs/tmp/tmp5q4yfi6u/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.28533s
INFO:tensorflow:Finished evaluation at 2022-12-14-20:18:14
INFO:tensorflow:Saving dict for global step 9: accuracy = 0.4390625, average_loss = 1.982246, global_step = 9, loss = 253.7275
INFO:tensorflow:Saving 'checkpoint_path' summary for global step 9: /tmpfs/tmp/tmp5q4yfi6u/model.ckpt-9
INFO:tensorflow:Calling checkpoint listeners before saving checkpoint 10...
INFO:tensorflow:Saving checkpoints for 10 into /tmpfs/tmp/tmp5q4yfi6u/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-14T20:18:15
INFO:tensorflow:Graph was finalized.
INFO:tensorflow:Restoring parameters from /tmpfs/tmp/tmp5q4yfi6u/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.28554s
INFO:tensorflow:Finished evaluation at 2022-12-14-20:18:15
INFO:tensorflow:Saving dict for global step 10: accuracy = 0.45, average_loss = 1.9367892, global_step = 10, loss = 247.90901
INFO:tensorflow:Saving 'checkpoint_path' summary for global step 10: /tmpfs/tmp/tmp5q4yfi6u/model.ckpt-10
INFO:tensorflow:Loss for final step: 102.29101.
({'accuracy': 0.45,
  'average_loss': 1.9367892,
  'loss': 247.90901,
  'global_step': 10},
 [])
%ls {classifier.model_dir}
checkpoint
eval/
events.out.tfevents.1671049088.kokoro-gcp-ubuntu-prod-1438429585
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.2214 - accuracy: 0.9346INFO:tensorflow:Assets written to: /tmpfs/tmp/tmp6wzij4ud/assets
1875/1875 [==============================] - 5s 2ms/step - loss: 0.2208 - accuracy: 0.9348 - val_loss: 0.1155 - val_accuracy: 0.9640
Epoch 2/10
1860/1875 [============================>.] - ETA: 0s - loss: 0.0974 - accuracy: 0.9701INFO:tensorflow:Assets written to: /tmpfs/tmp/tmp6wzij4ud/assets
1875/1875 [==============================] - 3s 2ms/step - loss: 0.0973 - accuracy: 0.9701 - val_loss: 0.0810 - val_accuracy: 0.9739
Epoch 3/10
1860/1875 [============================>.] - ETA: 0s - loss: 0.0685 - accuracy: 0.9783INFO:tensorflow:Assets written to: /tmpfs/tmp/tmp6wzij4ud/assets
1875/1875 [==============================] - 3s 2ms/step - loss: 0.0682 - accuracy: 0.9783 - val_loss: 0.0745 - val_accuracy: 0.9769
Epoch 4/10
1860/1875 [============================>.] - ETA: 0s - loss: 0.0540 - accuracy: 0.9827INFO:tensorflow:Assets written to: /tmpfs/tmp/tmp6wzij4ud/assets
1875/1875 [==============================] - 3s 2ms/step - loss: 0.0543 - accuracy: 0.9827 - val_loss: 0.0766 - val_accuracy: 0.9769
Epoch 5/10
1860/1875 [============================>.] - ETA: 0s - loss: 0.0433 - accuracy: 0.9861INFO:tensorflow:Assets written to: /tmpfs/tmp/tmp6wzij4ud/assets
1875/1875 [==============================] - 3s 2ms/step - loss: 0.0432 - accuracy: 0.9861 - val_loss: 0.0748 - val_accuracy: 0.9796
Epoch 6/10
1860/1875 [============================>.] - ETA: 0s - loss: 0.0356 - accuracy: 0.9883INFO:tensorflow:Assets written to: /tmpfs/tmp/tmp6wzij4ud/assets
1875/1875 [==============================] - 3s 2ms/step - loss: 0.0354 - accuracy: 0.9883 - val_loss: 0.0590 - val_accuracy: 0.9818
Epoch 7/10
1860/1875 [============================>.] - ETA: 0s - loss: 0.0306 - accuracy: 0.9896INFO:tensorflow:Assets written to: /tmpfs/tmp/tmp6wzij4ud/assets
1875/1875 [==============================] - 3s 2ms/step - loss: 0.0309 - accuracy: 0.9896 - val_loss: 0.0695 - val_accuracy: 0.9791
Epoch 8/10
1860/1875 [============================>.] - ETA: 0s - loss: 0.0284 - accuracy: 0.9906INFO:tensorflow:Assets written to: /tmpfs/tmp/tmp6wzij4ud/assets
1875/1875 [==============================] - 3s 2ms/step - loss: 0.0283 - accuracy: 0.9906 - val_loss: 0.0671 - val_accuracy: 0.9830
Epoch 9/10
1860/1875 [============================>.] - ETA: 0s - loss: 0.0251 - accuracy: 0.9912INFO:tensorflow:Assets written to: /tmpfs/tmp/tmp6wzij4ud/assets
1875/1875 [==============================] - 3s 1ms/step - loss: 0.0250 - accuracy: 0.9912 - val_loss: 0.0772 - val_accuracy: 0.9815
Epoch 10/10
1860/1875 [============================>.] - ETA: 0s - loss: 0.0222 - accuracy: 0.9925INFO:tensorflow:Assets written to: /tmpfs/tmp/tmp6wzij4ud/assets
1875/1875 [==============================] - 3s 1ms/step - loss: 0.0223 - accuracy: 0.9925 - val_loss: 0.0713 - val_accuracy: 0.9817
<keras.callbacks.History at 0x7fd3ec5d0520>
%ls {model_checkpoint_callback.filepath}
assets/  fingerprint.pb  keras_metadata.pb  saved_model.pb  variables/

다음 단계

체크포인트에 대한 자세한 내용:

콜백에 대한 자세한 내용:

다음과 같은 마이그레이션 관련 리소스도 유용할 수 있습니다.