Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
tensorflow
GitHub Repository: tensorflow/docs-l10n
Path: blob/master/site/ko/addons/tutorials/optimizers_cyclicallearningrate.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 애드온 최적화 도구: CyclicalLearningRate

개요

이 튜토리얼은 Addons 패키지에서 Cyclical Learning Rate를 사용하는 방법을 보여줍니다.

주기적 학습률

신경망에 대한 훈련이 진행됨에 따라 학습률을 조정하는 것이 유익한 것으로 나타났습니다. 안장점 복구에서 역전파 동안 발생할 수 있는 수치적 불안정성 방지에 이르기까지 다양한 이점이 있습니다. 그러나 특정 훈련 타임스탬프와 관련하여 얼마나 조정해야 하는지 어떻게 알 수 있습니까? 2015년에 Leslie Smith는 손실 환경에서 더 빠르게 탐색하기 위해 학습률을 높이고 싶지만 수렴에 접근할 때 학습률을 낮추고 싶어한다는 사실을 알아냈습니다. 이 아이디어를 실현하기 위해 그는 함수의 주기에 대해 학습률을 조정하는 CLR( Cyclical Learning Rates)을 제안했습니다. 시각적 데모를 보려면 이 블로그를 확인하세요. 이제 CLR을 TensorFlow API로 사용할 수 있습니다. 자세한 내용은 여기 에서 원본 문서를 확인하십시오.

설정

!pip install -q -U tensorflow_addons
from tensorflow.keras import layers import tensorflow_addons as tfa import tensorflow as tf import numpy as np import matplotlib.pyplot as plt tf.random.set_seed(42) np.random.seed(42)

데이터세트 로드 및 준비

(x_train, y_train), (x_test, y_test) = tf.keras.datasets.fashion_mnist.load_data() x_train = np.expand_dims(x_train, -1) x_test = np.expand_dims(x_test, -1)

초매개변수 정의

BATCH_SIZE = 64 EPOCHS = 10 INIT_LR = 1e-4 MAX_LR = 1e-2

모델 구축 및 모델 교육 유틸리티 정의

def get_training_model(): model = tf.keras.Sequential( [ layers.InputLayer((28, 28, 1)), layers.experimental.preprocessing.Rescaling(scale=1./255), layers.Conv2D(16, (5, 5), activation="relu"), layers.MaxPooling2D(pool_size=(2, 2)), layers.Conv2D(32, (5, 5), activation="relu"), layers.MaxPooling2D(pool_size=(2, 2)), layers.SpatialDropout2D(0.2), layers.GlobalAvgPool2D(), layers.Dense(128, activation="relu"), layers.Dense(10, activation="softmax"), ] ) return model def train_model(model, optimizer): model.compile(loss="sparse_categorical_crossentropy", optimizer=optimizer, metrics=["accuracy"]) history = model.fit(x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), epochs=EPOCHS) return history

재현성을 위해 실험을 수행하는 데 사용할 초기 모델 가중치가 직렬화됩니다.

initial_model = get_training_model() initial_model.save("initial_model")

CLR 없이 모델 훈련

standard_model = tf.keras.models.load_model("initial_model") no_clr_history = train_model(standard_model, optimizer="sgd")

CLR 일정 정의

tfa.optimizers.CyclicalLearningRate 모듈은 최적화 프로그램에 전달할 수 있는 직접 일정을 반환합니다. 일정은 입력으로 단계를 취하고 논문에 제시된 대로 CLR 공식을 사용하여 계산된 값을 출력합니다.

steps_per_epoch = len(x_train) // BATCH_SIZE clr = tfa.optimizers.CyclicalLearningRate(initial_learning_rate=INIT_LR, maximal_learning_rate=MAX_LR, scale_fn=lambda x: 1/(2.**(x-1)), step_size=2 * steps_per_epoch ) optimizer = tf.keras.optimizers.SGD(clr)

여기에서 학습률의 하한과 상한을 지정하면 일정이 해당 범위(이 경우 [1e-4, 1e-2]) 사이에서 진동합니다. scale_fn 은 주어진 주기 내에서 학습률을 확장 및 축소하는 함수를 정의하는 데 사용됩니다. step_size 는 단일 주기의 지속 시간을 정의합니다. 2의 step_size 는 한 주기를 완료하기 위해 총 4번의 반복이 필요함을 의미합니다. step_size 의 권장 값은 다음과 같습니다.

factor * steps_per_epoch 여기서 factor는 [2, 8] 범위 내에 있습니다.

같은 CLR 논문 에서 Leslie는 학습률의 경계를 선택하는 간단하고 우아한 방법도 제시했습니다. 당신도 그것을 확인하는 것이 좋습니다. 이 블로그 게시물 은 방법에 대한 좋은 소개를 제공합니다.

clr 일정이 어떻게 보이는지 시각화합니다.

step = np.arange(0, EPOCHS * steps_per_epoch) lr = clr(step) plt.plot(step, lr) plt.xlabel("Steps") plt.ylabel("Learning Rate") plt.show()

CLR의 효과를 더 잘 시각화하기 위해 증가된 단계 수로 일정을 그릴 수 있습니다.

step = np.arange(0, 100 * steps_per_epoch) lr = clr(step) plt.plot(step, lr) plt.xlabel("Steps") plt.ylabel("Learning Rate") plt.show()

이 자습서에서 사용하는 함수는 CLR 문서에서 triangular2 triangularexp (지수의 줄임말)라는 다른 두 가지 기능이 탐색되었습니다.

CLR을 사용하여 모델 학습

clr_model = tf.keras.models.load_model("initial_model") clr_history = train_model(clr_model, optimizer=optimizer)

예상대로 손실은 평소보다 높게 시작한 다음 사이클이 진행됨에 따라 안정화됩니다. 아래 도표를 통해 이를 시각적으로 확인할 수 있습니다.

손실 시각화

(fig, ax) = plt.subplots(2, 1, figsize=(10, 8)) ax[0].plot(no_clr_history.history["loss"], label="train_loss") ax[0].plot(no_clr_history.history["val_loss"], label="val_loss") ax[0].set_title("No CLR") ax[0].set_xlabel("Epochs") ax[0].set_ylabel("Loss") ax[0].set_ylim([0, 2.5]) ax[0].legend() ax[1].plot(clr_history.history["loss"], label="train_loss") ax[1].plot(clr_history.history["val_loss"], label="val_loss") ax[1].set_title("CLR") ax[1].set_xlabel("Epochs") ax[1].set_ylabel("Loss") ax[1].set_ylim([0, 2.5]) ax[1].legend() fig.tight_layout(pad=3.0) fig.show()

이 장난감 예제에서는 CLR의 효과를 많이 보지 못했지만 Super Convergence 의 주요 구성 요소 중 하나이며 대규모 설정에서 훈련할 때 정말 좋은 영향을 미칠 수 있다는 점에 주목했습니다.