Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
tensorflow
GitHub Repository: tensorflow/docs-l10n
Path: blob/master/site/ko/guide/migrate/checkpoint_saver.ipynb
25118 views
Kernel: Python 3
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.

"최고" 모델 또는 모델 가중치/매개변수를 지속적으로 저장하면 많은 이점이 있습니다. 이러한 이점에는 교육 진행 상황을 추적하고 다른 저장된 상태에서 저장된 모델을 로드하기 등이 있습니다.

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
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.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)
%ls {classifier.model_dir}

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])
%ls {model_checkpoint_callback.filepath}

다음 단계

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

콜백에 대한 자세한 내용:

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