■ Key words
ㆍModel Architecture Selection; Arts, not science
ㆍ학습 규제 전략(Regularization Strategies)
ㆍWeight Regularization(가중치 규제) : L1, L2 regularization / Drop out
ㆍWeight Constraints
ㆍLearning Rate Decay / Scheduling
ㆍ활성함수(Activation Function)별 trade-off
ㆍ추가 활성화함수(Activation Functions) : Tanh Function / Leaky ReLU / Softmax
■ 주요내용
ㆍ가중치 초기화(Weight Initialization) : 학습 시작 시점의 가중치를 정해주는 것
- 모든 가중치가 같은 값을 가지면 노드와 층(layer)을 나누는 의미가 없음
- 초기 가중치값에 따라 경사하강법의 최저점이 달라질 수 있음(극소값; local minima)
ㆍ학습 규제 전략(Regularization Strategies) : 과적합(overfitting)을 피하기 위해 학습을 규제함
- Early stopping : 학습이 진행될 수록 training set의 loss(error)는 감소하지만, validation/test set의
loss는 어느 시점(과적합) 이후 다시 증가하므로, loss 감소가 정체되면 학습 종료
- 가중치 감소(Weight Decay) : 가중치를 제거하거나 값을 규제하여 매개변수를 과도하게 적합시키는 것을 방지
* Weight Constraint / Weight Decusion / Weight Restriction은 모두 같은 목적의 다른 방법이기 때문에
중복하여 적용하진 않음
· L1 Regularization : loss함수에 상수(λ)와 가중치의 절대값을 곱한 값을 반영한 것.
· L2 Regularization : loss함수에 상수(λ)와 가중치의 제곱값을 곱한 값을 반영한 것.
⇒ 가중치의 합이 loss함수에 반영되어 가중치가 커지는 것(과적합; 영향력이 커지는 것)을 방지함
· Drop Out : 학습(train)할 때, 각 layer에서 일부 노드를 제외하고 학습하는 방법.
→ 배제되지 않는 node의 가중치만 남으므로, 해당 가중치를 보다 잘 학습할 수 있음
→ 가중치의 일부를 제외함으로써 하나의 가중치에 모델이 과하게 의지하는 것을 방지할 수 있음
i. e.> 모델이 w₂에 의존도가 높게 나올 수 있지만, 학습(iteration) 시 이를 배제하고 학습함으로써
보다 객관적으로 w₂의 비중을 계산하여 과적합을 피할 수 있음
⇒ Dropout은 학습(train)에만 반영하고, 검정(validation)과 테스트(test)에는 모든 노드 경로를 살림
- Constraints : weight decay와 다르게 학습 전 가중치의 범위(cap)를 한정하여 과적합을 조정하는 방법
ㆍ학습률 감소(Learning Rate Decay) : 오차함수의 최저값을 찾기 위해 학습 정도에 따라 학습률을 조정하는 것
- 경사하강법 적용 시 초기에는 크게 이동해도 되나, 학습이 진행되며 골짜기에 근접할 수록 조금씩 이동(학습)해야 함
- Learning Rate Scheduling : 학습이 진행됨에 따라 학습률 조정을 계획(schedule)하는 것
* comile : 모델을 학습시키기 위한 학습과정을 설정하는 단계. fit. 전에 적용
■ Session note
ㅁ 오전 세션
? drop out과 batch를 나눠서 학습하는 것 : node를 제외하는 것과 sample을 제외하는 것
ㆍ과적합을 피하는 방법
- early stopping : test set의 오차가 일정 이상 감소하지 않으면 학습 종료
- drop out : 각각의 노드에 대한 학습이 강화될 수 있도록, 랜덤하게 일부 노드 제외 /
학습 시에만 배제하고, 예측할 떄는 모두 사용
- constraints : 올림하여 물리적으로 통제
ㆍL1 : 절대값 사용; y축에서 접점 생성 / L2 : 제곱값 사용; 모든 가중치가
ㆍ모델을 저장하기 위해 두는 체크포인트 : 파일 경로에 저장
- epoch별로 학습을 할 때, 매 epoch의 학습이 종료되면 update 되기 때문에 가장 성능이 좋은 epoch가 덮어씌어지기 때문에 체크포인트를 저장하게 됨
ㆍ가중치 규제(weight decay)를 하는 이유 : 가중치의 합 또한 비용함수에 넣어서 각 노드의 영향력이 너무 커지는 과적합을 방지하기 위함
- LASSO : 가중치의 절대값합 반영; 작은 가중치는 0 / Ridge : 가중치의 제곱값합 반영; 작은 가중치도 모두 반영
⇒
ㆍDrop out 범위 : 일반적으로 통용되는 범위가 있음
ㆍkernel_regularizer / activity_regularizer 의미 찾아보기
ㆍflatten에서 input_shape을 입력하지 않아도 되지만, 명확하기 위해 입력해주는 것이 좋음
ㆍkernel_regularizer=regulrizers.l2(0.01)에서 0.01(weight의 상수인 λ값)도 최적값을 찾아내야 함
* code 공부법 : 공식문서 찾아보기
ㆍKeras와 tensorflow는 별개의 library이지만, 상보적으로 사용됨
ㆍinput_dim : 입력 차원 / input_shape : 데이터 사이즈
* 과제 seed 고정하기
ㅁ 오후 session
ㆍloss : cost function과 같음. target과 output 차이(error와 같음)
cf> 분류문제에서는 회귀와 다르게 수치로 나타낼 수 없기 때문에 MSE, MAE 등을 사용할 수 없음; error 대신 loss를 사용하는 이유?
ㆍdeep learning의 hyperparameter tuning이 machine learning 보다 크게 영향이 적은 이유
: deep learning은 좀 더 복잡해서
ㆍdrop out 비율 : cross validation
ㆍkernel : layer
ㆍL1, L2를 동시에 사용 가능 : L(θw) = Σerror + λ₁|θw| + λ₂||θw||₂
* colab 런타임에서 GPU 활성화하기
* 학습률 다시 보기
■ 주요함수
ㆍWeight Decay
## 모델 학습을 위한 코드
# 변수 설정을 따로 하는 방법을 적용하기 위한 코드
batch_size = 30
epochs_max = 1
# 학습시킨 데이터를 저장시키기 위한 코드
checkpoint_filepath = "FMbest.hdf5"
# overfitting을 방지하기 위해서 학습 중 early stop을 수행하기 위한 코드
early_stop = keras.callbacks.EarlyStopping(monitor='val_loss', min_delta=0, patience=10, verbose=1)
# Validation Set을 기준으로 가장 최적의 모델을 찾기 위한 코드
save_best = tf.keras.callbacks.ModelCheckpoint(
filepath=checkpoint_filepath, monitor='val_loss', verbose=1, save_best_only=True,
save_weights_only=True, mode='auto', save_freq='epoch', options=None)
# 모델 학습 코드 + early stop + Best model
model.fit(X_train, y_train, batch_size=batch_size, epochs=epochs_max, verbose=1,
validation_data=(X_test,y_test),
callbacks=[early_stop, save_best])
## 학습된 모델을 이용하여 테스트하는 코드
model.predict(X_test[0:1])
test_loss, test_acc = model.evaluate(X_test, y_test, verbose=2)
## 체크포인트에 저장된 가중치들을 불러들이는 코드
model.load_weights(checkpoint_filepath)
## best model을 이용한 테스트 데이터 예측 정확도 재확인 코드
model.predict(X_test[0:1])
test_loss, test_acc = model.evaluate(X_test, y_test, verbose=1)
ㆍConstraints
# 모델 구성을 확인합니다.
model = Sequential([
Flatten(input_shape=(28, 28)),
Dense(64,
kernel_regularizer=regularizers.l2(0.01),
activity_regularizer=regularizers.l1(0.01),
kernel_constraint=MaxNorm(2.)), ## add constraints
Dense(10, activation='softmax')
])
# 업데이트 방식을 설정합니다.
model.compile(optimizer='adam'
, loss='sparse_categorical_crossentropy'
, metrics=['accuracy'])
model.summary()
model.fit(X_train, y_train, batch_size=30, epochs=1, verbose=1,
validation_data=(X_test,y_test))
ㆍDrop Out
from tensorflow.keras.layers import Dropout
from tensorflow.keras.constraints import MaxNorm
from tensorflow.keras import regularizers
# 모델 구성을 확인합니다.
model = Sequential([
Flatten(input_shape=(28, 28)),
Dense(64,
kernel_regularizer=regularizers.l2(0.01),
activity_regularizer=regularizers.l1(0.01),
kernel_constraint=MaxNorm(2.)),
Dropout(0.5) , ## add dropout
Dense(10, activation='softmax')
])
# 업데이트 방식을 설정합니다.
model.compile(optimizer='adam'
, loss='sparse_categorical_crossentropy'
, metrics=['accuracy'])
model.summary()
model.fit(X_train, y_train, batch_size=30, epochs=1, verbose=1,
validation_data=(X_test,y_test))
ㆍLearning Rate Scheduling
model.compile(optimizer=tf.keras.optimizers.Adam(lr=0.001, beta_1 = 0.89)
, loss='sparse_categorical_crossentropy'
, metrics=['accuracy'])
model.summary()
model.fit(X_train, y_train, batch_size=30, epochs=1, verbose=1,
validation_data=(X_test,y_test))
# Scheduling
lr_schedule = keras.optimizers.schedules.ExponentialDecay(
initial_learning_rate=1e-2,
decay_steps=10000,
decay_rate=0.9)
def decayed_learning_rate(step):
step = min(step, decay_steps)
cosine_decay = 0.5 * (1 + cos(pi * step / decay_steps))
decayed = (1 - alpha) * cosine_decay + alpha
return initial_learning_rate * decayed
first_decay_steps = 1000
initial_learning_rate = 0.01
lr_decayed_fn = (
tf.keras.experimental.CosineDecayRestarts(
initial_learning_rate,
first_decay_steps))
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=lr_schedule)
, loss='sparse_categorical_crossentropy'
, metrics=['accuracy'])
model.summary()
model.fit(X_train, y_train, batch_size=30, epochs=1, verbose=1,
validation_data=(X_test,y_test))
■ Reference
ㆍOverfitting, Regularization : https://youtu.be/_sz3KTyB9Lk
ㆍL1(LASSO Regression), L2(Ridge Regression) Loss : https://light-tree.tistory.com/125
딥러닝 용어 정리, L1 Regularization, L2 Regularization 의 이해, 용도와 차이 설명
제가 공부하고 정리한 것을 나중에 다시 보기 위해 적는 글입니다. 제가 잘못 설명한 내용이 있다면 알려주시길 부탁드립니다. 사용된 이미지들의 출처는 본문에 링크로 나와 있거나 글의 가장
light-tree.tistory.com
ㆍDrop out : https://youtu.be/ajeliDMD86U
ㆍXavier 초기값 : https://youtu.be/ScWTYHQra5E
ㆍpython OS : https://docs.python.org/ko/3/tutorial/stdlib.html
10. 표준 라이브러리 둘러보기 — Python 3.9.6 문서
10.3. 명령행 인자 일반적인 유틸리티 스크립트는 종종 명령행 인자를 처리해야 할 필요가 있습니다. 이 인자들은 sys 모듈의 argv 어트리뷰트에 리스트로 저장됩니다. 예를 들어, 명령행에서 python
docs.python.org
ㆍpython random 함수 : https://wikidocs.net/79
위키독스
온라인 책을 제작 공유하는 플랫폼 서비스
wikidocs.net
ㆍ인공신경망 손실함수와 오차함수 : https://umbum.dev/210
인공신경망 ( ANN ) #4-1 학습 ( 손실함수, 오차함수 )
손실 함수 ( loss function ) ANN에서는 학습을 통해 최적의 가중치 매개변수를 결정하기 위한 지표로(기준으로) 손실 함수(loss function)를 사용한다. 손실 함수의 결과값(오차)을 가장 작게 만드는 것이
umbum.dev
ㆍKeras compile optimizer : https://keras.io/api/optimizers/
Keras documentation: Optimizers
Optimizers Usage with compile() & fit() An optimizer is one of the two arguments required for compiling a Keras model: from tensorflow import keras from tensorflow.keras import layers model = keras.Sequential() model.add(layers.Dense(64, kernel_initializer
keras.io
ㆍ가중치 초기화(weight initialization) : https://yngie-c.github.io/deep%20learning/2020/03/17/parameter_init/
가중치 초기화 (Weight Initialization) · Data Science
이번 게시물은 “밑바닥부터 시작하는 딥러닝”과 “Weight Initialization Techniques in Neural Networks”를 참조하여 작성하였습니다. Parameter Initialization 신경망 모델의 목적은 손실(Loss)을 최소화하는 과
yngie-c.github.io
ㆍkeras 오차함수 : https://keras.io/api/losses/
Keras documentation: Losses
Losses The purpose of loss functions is to compute the quantity that a model should seek to minimize during training. Available losses Note that all losses are available both via a class handle and via a function handle. The class handles enable you to pas
keras.io
ㆍDrop out : https://ko.d2l.ai/chapter_deep-learning-basics/dropout.html
3.13. 드롭아웃(dropout) — Dive into Deep Learning documentation
ko.d2l.ai
ㆍCNN(Convolutional Neural Network) : http://taewan.kim/post/cnn/
CNN, Convolutional Neural Network 요약
Convolutional Neural Network, CNN을 정리합니다.
taewan.kim
ㆍLearning Rate Decay : https://gentlej90.tistory.com/75
Learning rate decay
Learning rate decay 보통 일반적인 Stochastic gradient descent를 이용한 backprop을 할때 weight 의 learning rate를 잘 조정하는 것이 중요하다. 초기에는 이 learning rate를 grid search(요즘엔 random sear..
gentlej90.tistory.com
ㆍcompile : https://hyjykelly.tistory.com/17
딥러닝 모델 생성, 컴파일 그리고 학습시키기
* 저는 머신러닝/딥러닝에 관해 공부하고 있는 사람입니다. 잘못된 내용이나 참고할 만한 내용이 있다면 댓글로 남겨주시면 정말 감사드리겠습니다! 이번 포스팅에서는 예측을 수행하는 딥러닝
hyjykelly.tistory.com
'Data Science > 4. 딥러닝' 카테고리의 다른 글
[n422]Distributed Representation (0) | 2021.08.18 |
---|---|
[n421]Count-based Representation (0) | 2021.08.17 |
[n414]Neural Network Hyperparameters (0) | 2021.08.12 |
[n412]경사하강법과 역전파 알고리즘 (0) | 2021.08.10 |
[n411]Neural Network(NN) Foundation (0) | 2021.08.09 |