Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
tensorflow
GitHub Repository: tensorflow/docs-l10n
Path: blob/master/site/ko/guide/migrate/early_stopping.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.

이 노트북은 먼저 tf.estimator.Estimator 및 조기 중단 후크를 사용하여 TensorFlow 1에서 조기 중단하는 모델 훈련을 설정한 다음 Keras API 혹은 사용자 정의 훈련 루프를 사용하여 TensorFlow 2에서 모델 훈련을 설정하는 방법을 보여줍니다. 조기 중단은 예를 들어 검증 손실이 특정 임계값에 도달하면 훈련을 중지하는 정규화 기술입니다.

TensorFlow 2에는 조기 중단을 구현하는 세 가지 방법이 있습니다.

  • 내장 Keras 콜백(tf.keras.callbacks.EarlyStopping)을 사용하고 이를 Model.fit에 전달합니다.

  • 사용자 정의 콜백을 정의하고 이를 Keras Model.fit에 전달합니다.

  • 사용자 정의 훈련 루프(tf.GradientTape 사용)에서 사용자 정의 조기 중단 규칙을 작성합니다.

설치하기

import time import numpy as np import tensorflow as tf import tensorflow.compat.v1 as tf1 import tensorflow_datasets as tfds

TensorFlow 1: 조기 중단 후크 및 tf.estimator를 사용하는 조기 중단

먼저 MNIST 데이터세트 로드 및 전처리용 함수와 tf.estimator.Estimator와 함께 사용할 모델 정의를 정의합니다.

def normalize_img(image, label): return tf.cast(image, tf.float32) / 255., label def _input_fn(): ds_train = tfds.load( name='mnist', split='train', shuffle_files=True, as_supervised=True) ds_train = ds_train.map( normalize_img, num_parallel_calls=tf.data.AUTOTUNE) ds_train = ds_train.batch(128) ds_train = ds_train.repeat(100) return ds_train def _eval_input_fn(): ds_test = tfds.load( name='mnist', split='test', shuffle_files=True, as_supervised=True) ds_test = ds_test.map( normalize_img, num_parallel_calls=tf.data.AUTOTUNE) ds_test = ds_test.batch(128) return ds_test def _model_fn(features, labels, mode): flatten = tf1.layers.Flatten()(features) features = tf1.layers.Dense(128, 'relu')(flatten) logits = tf1.layers.Dense(10)(features) loss = tf1.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits) optimizer = tf1.train.AdagradOptimizer(0.005) train_op = optimizer.minimize(loss, global_step=tf1.train.get_global_step()) return tf1.estimator.EstimatorSpec(mode, loss=loss, train_op=train_op)

TensorFlow 1에서 조기 중단은 tf.estimator.experimental.make_early_stopping_hook으로 조기 중단 후크를 설정하면 작동합니다. 인수가 없어도 함수를 허용할 수 있는 should_stop_fn용 매개변수로써 make_early_stopping_hook 메서드에 후크를 전달합니다. should_stop_fnTrue를 반환하면 훈련이 중단됩니다.

다음 예제는 훈련 시간을 최대 20초로 제한하는 조기 중단 기술을 구현하는 방법을 보여줍니다.

estimator = tf1.estimator.Estimator(model_fn=_model_fn) start_time = time.time() max_train_seconds = 20 def should_stop_fn(): return time.time() - start_time > max_train_seconds early_stopping_hook = tf1.estimator.experimental.make_early_stopping_hook( estimator=estimator, should_stop_fn=should_stop_fn, run_every_secs=1, run_every_steps=None) train_spec = tf1.estimator.TrainSpec( input_fn=_input_fn, hooks=[early_stopping_hook]) eval_spec = tf1.estimator.EvalSpec(input_fn=_eval_input_fn) tf1.estimator.train_and_evaluate(estimator, train_spec, eval_spec)

TensorFlow 2: 내장 콜백 및 Model.fit을 사용하는 조기 중단

MNIST 데이터세트 및 간단한 Keras 모델 준비:

(ds_train, ds_test), ds_info = tfds.load( 'mnist', split=['train', 'test'], shuffle_files=True, as_supervised=True, with_info=True, ) ds_train = ds_train.map( normalize_img, num_parallel_calls=tf.data.AUTOTUNE) ds_train = ds_train.batch(128) ds_test = ds_test.map( normalize_img, num_parallel_calls=tf.data.AUTOTUNE) ds_test = ds_test.batch(128) model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10) ]) model.compile( optimizer=tf.keras.optimizers.Adam(0.005), loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=[tf.keras.metrics.SparseCategoricalAccuracy()], )

TensorFlow 2에서 내장 Keras Model.fit(혹은 Model.evaluate)을 사용하는 경우 내장 콜백인 tf.keras.callbacks.EarlyStoppingModel.fitcallbacks 매개변수로 전달함으로써 조기 중단을 구성할 수 있습니다.

EarlyStopping 콜백은 사용자가 지정한 메트릭을 모니터링하고 개선이 중단되면 훈련을 종료합니다(자세한 정보는 내장 메서드를 사용하는 훈련 및 평가 혹은 API 문서를 확인하세요).

다음은 개선을 보여주지 않는 epoch의 수를 3(patience)으로 설정한 후 손실을 모니터링하며 훈련을 중단하는 조기 중단 콜백의 예제입니다.

callback = tf.keras.callbacks.EarlyStopping(monitor='loss', patience=3) # Only around 25 epochs are run during training, instead of 100. history = model.fit( ds_train, epochs=100, validation_data=ds_test, callbacks=[callback] ) len(history.history['loss'])

TensorFlow 2: 사용자 정의 콜백 및 Model.fit을 사용하는 조기 중단

사용자 정의 조기 중단 콜백을 구현할 수도 있습니다. 이 콜백은 Model.fit(혹은 Model.evaluate)의 callbacks 매개변수로 전달할 수도 있습니다.

이 예제에서는 self.model.stop_trainingTrue로 설정하면 훈련 프로세스가 중단됩니다.

class LimitTrainingTime(tf.keras.callbacks.Callback): def __init__(self, max_time_s): super().__init__() self.max_time_s = max_time_s self.start_time = None def on_train_begin(self, logs): self.start_time = time.time() def on_train_batch_end(self, batch, logs): now = time.time() if now - self.start_time > self.max_time_s: self.model.stop_training = True
# Limit the training time to 30 seconds. callback = LimitTrainingTime(30) history = model.fit( ds_train, epochs=100, validation_data=ds_test, callbacks=[callback] ) len(history.history['loss'])

TensorFlow 2: 사용자 정의 훈련 루프를 사용하는 조기 중단

TensorFlow 2에서는 내장 Keras 메서드로 훈련과 평가를 수행하지 않은 경우 사용자 정의 훈련 루프에서 조기 중단을 구현할 수 있습니다.

먼저 Keras API를 사용하여 다른 간단한 모델, 옵티마이저, 손실 함수 및 메트릭을 정의합니다.

model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10) ]) optimizer = tf.keras.optimizers.Adam(0.005) loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) train_acc_metric = tf.keras.metrics.SparseCategoricalAccuracy() train_loss_metric = tf.keras.metrics.SparseCategoricalCrossentropy() val_acc_metric = tf.keras.metrics.SparseCategoricalAccuracy() val_loss_metric = tf.keras.metrics.SparseCategoricalCrossentropy()

tf.GradientTape속도 향상을 위한 @tf.function 데코레이터를 사용하여 매개변수 업데이트 함수를 정의합니다.

@tf.function def train_step(x, y): with tf.GradientTape() as tape: logits = model(x, training=True) loss_value = loss_fn(y, logits) grads = tape.gradient(loss_value, model.trainable_weights) optimizer.apply_gradients(zip(grads, model.trainable_weights)) train_acc_metric.update_state(y, logits) train_loss_metric.update_state(y, logits) return loss_value @tf.function def test_step(x, y): logits = model(x, training=False) val_acc_metric.update_state(y, logits) val_loss_metric.update_state(y, logits)

다음으로 조기 중단 규칙을 수동으로 구현할 수 있는 사용자 정의 훈련 루프를 작성합니다.

아래의 예제는 검증 손실이 특정 epoch 수 동안 개선되지 않을 경우 훈련을 중단하는 방식을 보여줍니다.

epochs = 100 patience = 5 wait = 0 best = float('inf') for epoch in range(epochs): print("\nStart of epoch %d" % (epoch,)) start_time = time.time() for step, (x_batch_train, y_batch_train) in enumerate(ds_train): loss_value = train_step(x_batch_train, y_batch_train) if step % 200 == 0: print("Training loss at step %d: %.4f" % (step, loss_value.numpy())) print("Seen so far: %s samples" % ((step + 1) * 128)) train_acc = train_acc_metric.result() train_loss = train_loss_metric.result() train_acc_metric.reset_states() train_loss_metric.reset_states() print("Training acc over epoch: %.4f" % (train_acc.numpy())) for x_batch_val, y_batch_val in ds_test: test_step(x_batch_val, y_batch_val) val_acc = val_acc_metric.result() val_loss = val_loss_metric.result() val_acc_metric.reset_states() val_loss_metric.reset_states() print("Validation acc: %.4f" % (float(val_acc),)) print("Time taken: %.2fs" % (time.time() - start_time)) # The early stopping strategy: stop the training if `val_loss` does not # decrease over a certain number of epochs. wait += 1 if val_loss < best: best = val_loss wait = 0 if wait >= patience: break

다음 단계