상세 컨텐츠

본문 제목

[딥러닝초급] Drop out and Batch Normalization

로봇-AI

by happynaraepapa 2025. 2. 18. 11:08

본문

sources :
https://www.kaggle.com/code/ryanholbrook/dropout-and-batch-normalization

Dropout and Batch Normalization

Explore and run machine learning code with Kaggle Notebooks | Using data from DL Course Data

www.kaggle.com


Introduction
There's more to the world of deep learning than just dense layers. There are dozens of kinds of layers you might add to a model. (Try browsing through the Keras docs for a sample!) Some are like dense layers and define connections between neurons, and others can do preprocessing or transformations of other sorts.
딥러닝에서 레이어만 겹겹이 쌓는다고 되는 것이 아니라 밀집 레이어외에도 사전처리(Pre-processing)이나 각종 변환(transformation)을 담당하는 레이어가 있다.

In this lesson, we'll learn about a two kinds of special layers, not containing any neurons themselves, but that add some functionality that can sometimes benefit a model in various ways. Both are commonly used in modern architectures.
이번 레슨에서는 두가지 종류의 스페셜한 레이어를 배워볼 건데 이것들은 뉴런은 없으나 모델의 성능을 향상시키는데 필요한 다양한 기능을 제공해준다.
이 두가지는 모델링 기법의 공통적인 요소로 사용된다.

Dropout
드랍아웃

The first of these is the "dropout layer", which can help correct overfitting.
첫번째 스페셜 레이어는 '드랍아웃 레이어'다.
이것은 오버피팅을 바로잡는데 도움을 준다.

In the last lesson we talked about how overfitting is caused by the network learning spurious patterns in the training data. To recognize these spurious patterns a network will often rely on very a specific combinations of weight, a kind of "conspiracy" of weights. Being so specific, they tend to be fragile: remove one and the conspiracy falls apart.
앞선 강의에서 노이즈(sprious pattern : 잘못된 패턴)가 어떻게 오버피팅을 일으키는 지 이야기 했다. 신경망에서 이러한 노이즈를 찾아내려면 특정한 조합의 가중치 - 추정 가중치를 사용하기도 한다. 이를 이용해서 노이즈로 의심되는 데이터를 추려낼 수 있다.

This is the idea behind dropout. To break up these conspiracies, we randomly drop out some fraction of a layer's input units every step of training, making it much harder for the network to learn those spurious patterns in the training data. Instead, it has to search for broad, general patterns, whose weight patterns tend to현 be more robust.
이런 아이디어가 드랍아웃의 배경이다. 노이즈를 추려내기 위해서 우리는 트레이닝의 모든 스텝에서 레이어의 input 일부를 드랍아웃한다. 이렇게 되면 신경망은 트레이닝 데이터의 비정상적인 패턴을 학습하기 어렵게 되고 대신에 좀 더 일반적인 패턴을 찾게 된다.
#참고로 여기서 noise는 fragile (잘 부서지고)
signal은 robust (단단하다)라고 표현했다.


An animation of a network cycling through various random dropout configurations. Here, 50% dropout has been added between the two hidden layers.


You could also think about dropout as creating a kind of ensemble of networks. The predictions will no longer be made by one big network, but instead by a committee of smaller networks. Individuals in the committee tend to make different kinds of mistakes, but be right at the same time, making the committee as a whole better than any individual. (If you'rE familiar with random forests as an ensemble of decision trees, it's the same idea.)
그리고 드랍아웃을 하게 되면 일종의 신경망 앙상블을 형성한다고 보면 된다. (앙상블은 일전 머신러닝때 이야기했다. 여러 학습 방법을 같이 사용하는 것.)
예측값은 하나의 큰 신경망을 통하는 것이 아니라 소규모의 신경망 조합에서 도출된다. 개별 조합은 다양한 mistake 실수를 만들수 있으나, 전체 조합은 하나의 거대한 신경망 보다 더 나은 결과를 내게 된다.  
(앞서 머신러닝에서 배운 랜덤 포레스트가 의사결정나무 (Decision Tree)보다 나은 성능을 내는 것도 유사한 원리다.)

Adding Dropout
In Keras, the dropout rate argument rate defines what percentage of the input units to shut off. Put the Dropout layer just before the layer you want the dropout applied to:
케라스에서 드랍아웃율 (Drop out rate) 인자를 지정하고 드랍아웃 레이어를 적용하기 원하는 레이어 직전에 넣는다. 아래 코드 참조

#파이썬코드
keras.Sequential([
    # ...
    layers.Dropout(rate=0.3), # apply 30% dropout to the next layer
    layers.Dense(16),
    # ...
])
#뒤에 나오는 덴스 레이어 앞에 드랍아웃 레이어를 넣고 비율은 30%를 적용한다고 인자 rate = 0.3 넣음.

Batch Normalization
배치 평준화
The next special layer we'll look at performs "batch normalization" (or "batchnorm"), which can help correct training that is slow or unstable.
다음으로 배치 평준화 레이어 (Batch norm layer)에 대해서 알아보자. 이 레이어는 트레이닝이 느리거나 불안정한 경우 도움을 줄 수 있다.

With neural networks, it's generally a good idea to put all of your data on a common scale, perhaps with something like scikit-learn's StandardScaler or MinMaxScaler. The reason is that SGD will shift the network weights in proportion to how large an activation the data produces. Features that tend to produce activations of very different sizes can make for unstable training behavior.
신경망에서 모든 데이터가 동일한 척도(scale)를 가지도록 하는 것이 좋다. 파이썬의 사이킷 런 패키지는 StandardScaler, MinMaxScaler과 같은 툴을 제공한다.
예를 들어,
SGD는 신경망에서 각 데이터가 얼마나 활성화 함수를 작동시키느냐에 따라 네트워크의 가중치를 매겨 나가기 때문에, 매우 다양한 척도의 활성화 값을 만드는 피쳐(feature: column)는 트레이닝을 불안정하게 만들 수 있다.

Now, if it's good to normalize the data before it goes into the netwoIrk, maybe also normalizing inside the network would be better! In fact, we have a special kind of layer that can do this, the batch normalization layer.
여기에 더해서 만약 네트워크 안에서도 노멀라이징을 한다면 성능이 더 좋아질 수 있다.(갑자기???)
실제로 이런일을 하기 위한 스페셜한 레이어가 있고 이것을 배치 노멀라이제이션 레이어라고 한다.

A batch normalization layer looks at each batch as it comes in, first normalizing the batch with its own mean and standard deviation, and then also putting the data on a new scale with two trainable rescaling parameters. Batchnorm, in effect, performs a kind of coordinated rescaling of its inputs.

배치 노멀라이징 레이어는 일단 각 배치의 평균과 표준 편차를 이용해서 노멀라이징을 실시하고 그 것을 다시 새로운 척도(스케일 scale)로 만든다. 이것은 두개의 학습되는 rescaling parameter를 가지고 있다. Batchnorm은 입력에 대한 리스케일링 (척도를 새롭게 정의함; 척도 변경)을 효과적으로 조정해준다.


#batch는 컴퓨터 프로그래밍 용어로 자주 쓰이는데, 여러 명령어를 묶어서 하나의 작업 묶음으로 만든것.
#normalize 무슨 의미일까? 수학적인 의미를 인터넷에 찾아보자.


Most often, batchnorm is added as an aid to the optimization process (though it can sometimes also help prediction performance). Models with batchnorm tend to need fewer epochs to complete training. Moreover, batchnorm can also fix various problems that can cause the training to get "stuck". Consider adding batch normalization to your models, especially if you're having trouble during training.
batchnorm은 옵티마이저 프로세스를 돕기위한 단계로 도입되었다. (이것은 모델의 성능을 높이는데도 일조한다.)
Batchnorm을 적용한 모델은 기존 대비 같은 트레이닝을 더 적은 epoch;에포크;실행횟수로 끝낼 수 있다. 더불어 트레이닝 중간에 발생할 수 있는 몇가지 문제점을 해결하는데에도 도움을 준다.
지금 모델 트레이닝에 문제가 발생하고 있다면 당신의 모델에 Batchnorm 을 적용해보기 바란다.

Adding Batch Normalization
Batchnorm을 넣어보자.

It seems that batch normalization can be used at almost any point in a network. You can put it after a layer...
Batchnorm은 고려하려는 레이어 이후에 반영하되, 신경망의 어느 포인트에 넣어도 무방하다.

#파이썬 코드
layers.Dense(16, activation='relu'),
layers.BatchNormalization(),
... or between a layer and its activation function:

layers.Dense(16),
layers.BatchNormalization(),
layers.Activation('relu'),
#


And if you add it as the first layer of your network it can act as a kind of adaptive preprocessor, standing in for something like Sci-Kit Learn's StandardScaler.
만약 Batchnorm 레이어를 신경망의 최초 레이어로 사용하면 이것을 일종의 adaptive preprocessor 적응형 선행처리기로 작동한다. 사이킷런의 StandardScaler와 유사한 작동이다.

예시.
Example - Using Dropout and Batch NormalizationP
Let's continue developing the Red Wine model. Now we'll increase the capacity even more, but add dropout to control overfitting and batch normalization to speed up optimization. This time, we'll also leave off standardizing the data, to demonstrate how batch normalization can stabalize the training.
RedWine 모델 개발을 계속해보자.
오버피팅을 줄이기 위해 드랍아웃을 추가하고 최적화 시간을 줄이기 위해 Batchnorm을 추가하자.
이번에는 데이터의 표준화를 배제해보고 Batchnorm이 어떻게 모델 트레이닝을 안정화해주는지 확인해보자.

When adding dropout, you may need to increase the number of units in your Dense layers.
드랍아웃을 더할때는 덴스레이어의 유닛 넘버를 증가시켜야 할 필요가 있다.


#파이썬코드
from tensorflow import keras
from tensorflow.keras import layers

model = keras.Sequential([
    layers.Dense(1024, activation='relu', input_shape=[11]),
    layers.Dropout(0.3),
    layers.BatchNormalization(),
    layers.Dense(1024, activation='relu'),
    layers.Dropout(0.3),
    layers.BatchNormalization(),
    layers.Dense(1024, activation='relu'),
    layers.Dropout(0.3),
    layers.BatchNormalization(),
    layers.Dense(1),
])
#
...
#파이썬코드
model.compile(
    optimizer='adam',
    loss='mae',
)

history = model.fit(
    X_train, y_train,
    validation_data=(X_valid, y_valid),
    batch_size=256,
    epochs=100,
    verbose=0,
)

# Show the learning curves
history_df = pd.DataFrame(history.history)
history_df.loc[:, ['loss', 'val_loss']].plot();
#

You'll typically get better performance if you standardize your data before using it for training. That we were able to use the raw data at all, however, shows how effective batch normalization can be on more difficult datasets.
단순히 보면 트레이닝 전 데이터를 표준화(Standardization) 하면 성능이 개선되더라 정도일 수 있지만 더 복잡한 데이터셋을 다루는 모델을 가정한다면 이 Batchnorm 이 얼마나 효과적일지 알수 있을 것이다.

<끝>

관련글 더보기