모델을 만들때 가장 중요한 것은 learning rate, optimizer, dropout rate 등 최적의 하이퍼파라미터를 찾아 튜닝하는 것이다!
이 과정에서 도와주는 wandb라는 툴이 있다. wandb는 머신러닝 실험 도구이다. 여러 기능을 제공하는데 그 중 sweep 기능은 하이퍼 파라미터를 튜닝하느 과정을 돕는다.
wandb 없이 튜닝했을때는 다음과 같이 후보군들 조합을 만들어 놓고 for문을 이용해서 튜닝했다.
Wandb 사용시에도 크게 개념이 다르지 않다고 생각한다.
Sweep config로 하이퍼파라미터들의 후보군을 설정하고 sweep agent에 sweep id를 전달하여 실행시킨다
편리한 것은 시각화가 잘되어있어 각 조합별로 성능을 비교하기가 편하다는 점이다!
Wandb 사용 on jupyter notebook
1. wandb 로그인
먼저 wandb 사이트에 회원가입을 해서 API 키를 받고 새 프로젝트를 만든다.
로컬에서 실행시
pip install wandb
wandb login
위의 명령어 입력 후 API 키를 입력하여 로그인을 한다.
이 방법을 통해서 로그인을 해두면 설정해둔 환경에서 다시 로그인 할 필요가 없다
Colab / Kaggle
notebook을 열어서 위의 코드를 통해 로그인을 할 수 있다.
커널이 재실행될 때마다 로그인을 해주어야한다.
2. 모델 빌딩
학습에 사용할 모델을 함수로 빌딩한다.
config default를 통해서 파라미터들의 초기값을 설정하고 init시 config를 설정해주었다.
배치 크기도 파라미터로 주어 배치 크기가 들어가는 image data generater도 같은 함수 안에 넣어주었다.
def train() :
tf.keras.backend.clear_session()
config_defaults = {
'pretrain_net': 'inception',
'epochs' : 10,
'batch_size': 50,
'dropout' : 0.5,
'learning_rate' : 1e-3,
'activation': 'relu',
'optimizer': 'adam'
}
wandb.init(config=config_defaults)
config = wandb.config
train_generator = train_gen.flow_from_dataframe(train_df,
x_col='image',
y_col=['disease', 'grow'],
target_size=(IMAGE_SIZE, IMAGE_SIZE),
class_mode='multi_output',
batch_size=config.batch_size)
valid_generator = valid_gen.flow_from_dataframe(test_df,
x_col='image',
y_col=['disease','grow'],
target_size=(IMAGE_SIZE, IMAGE_SIZE),
class_mode='multi_output',
batch_size=config.batch_size)
if config.pretrain_net == 'inception' :
MODEL_IMAGE_SIZE = 299
base_model = inception_resnet_v2.InceptionResNetV2(
weights='imagenet',
include_top = False,
input_shape = (MODEL_IMAGE_SIZE, MODEL_IMAGE_SIZE,3)
)
elif config.pretrain_net == 'resnet' :
MODEL_IMAGE_SIZE = 224
base_model= resnet50.ResNet50(
weights='imagenet',
include_top=False,
input_shape = (MODEL_IMAGE_SIZE, MODEL_IMAGE_SIZE,3)
)
base_model.trainable = False
# resizing model
input_data = layers.Input((IMAGE_SIZE, IMAGE_SIZE, 3))
x = tf.keras.layers.experimental.preprocessing.Resizing(MODEL_IMAGE_SIZE, MODEL_IMAGE_SIZE)(input_data)
resizing = Model(inputs=input_data, outputs=x, name='resize')
# model
inputs = layers.Input(shape=(IMAGE_SIZE, IMAGE_SIZE, 3))
x = resizing(inputs)
x = base_model(x, training=False)
x = layers.GlobalAveragePooling2D()(x)
x = layers.Dropout(config.dropout)(x)
backbone_out = layers.Dense(config.dense, activation=config.activation)(x)
disease_outputs = layers.Dense(df['disease'].nunique(), activation='softmax',
name = 'diease_outputs')(backbone_out)
grow_outputs = layers.Dense(df['grow'].nunique(), activation='softmax',
name = 'grow_outputs')(backbone_out)
model = Model(inputs=inputs,
outputs=[disease_outputs, grow_outputs],
name='strawberry')
if config.optimizer=='sgd':
optimizer = SGD(learning_rate=config.learning_rate)
elif config.optimizer=='rmsprop':
optimizer = RMSprop(learning_rate=config.learning_rate)
elif config.optimizer=='adam':
optimizer = Adam(learning_rate=config.learning_rate)
model.compile(loss={
'diease_outputs' : 'sparse_categorical_crossentropy',
'grow_outputs' : 'sparse_categorical_crossentropy'
},
optimizer=optimizer,
metrics=['accuracy'])
_ = model.fit(train_generator,
validation_data=valid_generator,
verbose=1,
epochs=config.epochs,
callbacks=[WandbCallback()],
steps_per_epoch=len(train_df)//config.batch_size)
3. sweep config
sweep에 사용할 파라미터들을 설정해준다.
sweep_config = {
'method': 'random', #grid, random
'metric': {
'name': 'val_loss',
'goal': 'minimize'
},
'parameters': {
'pretrain_net': {
'values': ['inception', 'resnet']
},
'batch_size': {
'values': [20, 50]
},
'dropout': {
'values': [0.2, 0.5]
},
'dense': {
'values': [32, 256, 1024]
},
'learning_rate': {
'values': [1e-2, 1e-3, 1e-4, 3e-5]
},
'optimizer': {
'values': ['adam', 'sgd', 'rmsprop']
},
'activation': {
'values': ['relu', 'elu', 'selu', 'softmax']
}
}
}
cmd 창에서 실행할때는 .yaml 파일로 config를 만들어주는데
jupyter notebook을 이용할 때는 딕셔너리형태로 config를 구성해준다.
method는 search strategy로 grid, random, bayes가 있다.
Sweep Configuration - Documentation
The brackets for this example are: [3, 3*eta, 3*eta*eta, 3*eta*eta*eta], which equals [3, 9, 27, 81].
docs.wandb.ai
4. sweep
sweep_id = wandb.sweep(sweep_config, project='strawberry')
스윕을 초기화해준 후
wandb.agent(sweep_id, train)
sweep id를 이용해서 sweep agent를 실행!
이런 출력이 나오면 성공이다
5. 확인
실행을 어느정도 하고 sweep page에 들어가면 결과를 시각적으로 확인할 수 있다.
참고
Running Sweeps in Jupyter - Documentation
Two components work together in a sweep: a controller on the central sweep server, which picks out new hyperparameter combinations to try, and agents, running in any number of processes on any number of machines, which query the server for hyperparameters,
docs.wandb.ai
Intro to Hyperparameter Sweeps with W&B.ipynb
Colaboratory notebook
colab.research.google.com
wandb log를 이용하면 예측한 이미지도 같이 시각화 할 수 있고, metric도 커스텀해서 사용할 수 있다.
WandbCallback을 통해서 earlystopping, 모델, 가중치를 wandb 상에 저장할 수 있다.
wandb를 이용하면 sweep이외에도 cpu 온도, gpu 온도 등도 모니터링 할 수 있다.
- wandb.log
- earlystopping
'Projects' 카테고리의 다른 글
[코드실행기능 개발기 #1] 작업이 오래걸리는 요청을 어떻게 응답할까? (2) | 2023.12.17 |
---|---|
certbot으로 HTTPS 설정하기 (1) | 2023.12.17 |
multi-columns: stratify split, 여러 개의 클래스 stratify로 데이터셋 분리하기 (0) | 2022.06.14 |
정답데이터 만들기 - Image annotation, VIA (0) | 2022.05.24 |
데이콘 경진대회 참여 - 주제, 데이터 (0) | 2022.05.24 |