티스토리 뷰
하이퍼 파라미터를 조정하는 내용의 글입니다.
챗봇 프로젝트를 수행하면서 최적의 파라미터를 찾기 위한 시도를 했습니다.
이 내용도 파라미터 검색에 많은 도움을 줄 수 있는 글입니다.
Keras Tuner¶
- 최적의 하이퍼파라미터 세트를 선택하는데 도움을 주는 라이브러리
- 하이퍼파라미터(hyper-parameter) 조정 / 하이퍼튜닝 : 최적의 하이퍼파라미터 세트를 선택하는 과정
- 하이퍼파라미터 유형
- 모델 하이퍼파라미터 : 숨겨진 레이어의 수 및 너비와 같은 모델 선택에 영향을 미치는 파라미터
- 알고리즘 하이퍼파라미터 : SGD(Stochastic Gradient Descent)의 학습률 및 KNN(k Nearest Neighbors) 분류자의 최근접 이웃 수와 같은 학습 알고리즘의 속도와 품질에 영향을 주는 파라미터
In [ ]:
01. 준비 / 설정¶
In [1]:
import tensorflow as tf
from tensorflow import keras
import IPython
In [2]:
!pip install -q -U keras-tuner
import kerastuner as kt
<ipython-input-2-5d7b6944a6ac>:2: DeprecationWarning: `import kerastuner` is deprecated, please use `import keras_tuner`. import kerastuner as kt
In [ ]:
02. 데이터세트 다운로드¶
In [3]:
(img_train, label_train), (img_test, label_test) = keras.datasets.fashion_mnist.load_data()
In [5]:
# Normalize pixel values between 0 and 1
img_train = img_train.astype('float32') / 255.0
img_test = img_test.astype('float32') / 255.0
In [ ]:
03. 모델 구현¶
하이퍼 튜닝을 위한 모델을 빌드
- 모델 아키텍처와 하이퍼파라미터 검색 공간도 정의 : 하이퍼 모델
하이퍼 모델 정의
- 모델 빌더 함수 사용
- Keras Tuner API의 HyperModel 클래스를 하위 클래스화
- HyperXception
- HyperResNet
In [12]:
def model_builder(hp):
model = keras.Sequential()
model.add(keras.layers.Flatten(input_shape=(28, 28)))
# Tune the number of units in the first Dense layer
# Choose an optimal value between 32-512
hp_units = hp.Int('units', min_value=32, max_value=512, step=32)
model.add(keras.layers.Dense(units=hp_units, activation='relu'))
model.add(keras.layers.Dense(10))
# Tune the learning rate for the optimizer
# Choose an optimal value from 0.01, 0.001, or 0.0001
hp_learning_rate = hp.Choice('learning_rate', values=[1e-2, 1e-3, 1e-4])
model.compile(optimizer=keras.optimizers.Adam(learning_rate=hp_learning_rate),
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
return model
In [ ]:
04. 하이퍼 튜닝 수행¶
- 튜너를 인스턴스화
- Keras Tuner
- RandomSearch
- Hyperband
- BayesianOptimization
- Sklearn
In [13]:
tuner = kt.Hyperband(model_builder,
objective='val_accuracy',
max_epochs=10,
factor=3,
directory='my_dir',
project_name='intro_to_kt')
In [16]:
# 하이퍼파라미터 검색을 실행하기 전에 훈련 단계가 끝날 때마다 훈련 결과를 지우도록 콜백 설정
class ClearTrainingOutput(tf.keras.callbacks.Callback):
def on_train_end(*args, **kwargs):
IPython.display.clear_output(wait=True)
In [18]:
# 파이퍼파라미터 검색
tuner.search(img_train, label_train, epochs=10, validation_data=(img_test, label_test),
callbacks=[ClearTrainingOutput()])
# Get the optimal hyperparameters
best_hps = tuner.get_best_hyperparameters(num_trials=1)[0]
print(f'''
The hyperparameter search is complete. The optimal number of units in the first densely-connected
layer is {best_hps.get('units')} and the optimal learning rate for the optimizer is {best_hps.get('learning_rate')}
''')
Trial 31 Complete [00h 04m 03s] val_accuracy: 0.881600022315979 Best val_accuracy So Far: 0.882099986076355 Total elapsed time: 00h 39m 28s INFO:tensorflow:Oracle triggered exit The hyperparameter search is complete. The optimal number of units in the first densely-connected layer is 128 and the optimal learning rate for the optimizer is 0.001
In [ ]:
my_dir/intro_to_kt 디렉토리¶
- 하이퍼파라미터 검색 중에 실행되는 모든 시험에 대한 상세 로그와 체크포인트가 포함
- 하이퍼파라미터 검색을 다시 실행 : Keras Tuner가 이러한 로그의 기존 상태를 사용하여 검색을 재개
- 이 동작을 비활성화
- 튜너를 인스턴스화하는 동안 "overwrite=True" 인수를 추가
추가 자료¶
- TensorFlow 블로그의 Keras Tuner : https://blog.tensorflow.org/2020/01/hyperparameter-tuning-with-keras-tuner.html
- Keras Tuner Website : https://keras.io/keras_tuner/
- TensorBoard의 HParams Dashboard : https://www.tensorflow.org/tensorboard/hyperparameter_tuning_with_hparams
In [ ]:
'machineLearning > tensorflow' 카테고리의 다른 글
tf_CSVdataLoad (0) | 2021.07.07 |
---|---|
tf_imageLoad (0) | 2021.07.06 |
tf_modelSaveLoad (0) | 2021.07.05 |
tf_OverUnderFitting (0) | 2021.07.03 |
tf_carFuelEconomy (1) | 2021.07.02 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- RAG
- Python
- streamlit
- Chatbot
- 파이썬
- TensorFlow
- prompt
- 미분계수
- 프로그래머스
- multi modal
- programmers
- FewShot
- 변화율
- 챗봇
- image depict
- LLM
- 고등학교 수학
- AI_고교수학
- 약수
- GPT
- ChatGPT
- 미분법
- 도함수
- 로피탈정리
- programmers.co.kr
- checkpoint
- 텐서플로우
- 미분
- 랭체인
- LangChain
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
글 보관함