728x90
배치 정규화
배치 정규화 알고리즘
- 학습을 빨리 진행할 수 있다.(학습 속도 개선)
- 초깃값에 크게 의존하지 않는다.(골치 아픈 초깃값 선택 장애여 안녕!)
- 오버피팅을 억제한다.(드론아웃 등의 필요성 감소)
[배치 정규화를 사용한 신경망의 예]
배치 정규화는 학습 시 미니배치를 단위로 정규화함.
구체적으로는 데이터 분포가 평균이 0, 분산이 1이 되도록 정규화함.
[배치 정규화 수식]
배치 정규화 계층마다 이 정규화된 데이터에 고유한 확대와 이동 변환을 수행함.
수식으로는 다음과 같음.
이 식에서 γ가 확대를, β가 이동을 담당함. 두 값은 처음에는 γ=1, β=0부터 시작하고, 학습하면서 적합한 값으로 조정해감.
이것이 배치 정규화의 알고리즘이며, 신경망에서 순전파 때 적용됨.
계산 그래프는 아래와 같음.
배치 정규화의 효과
# mnist를 이용한 배치 정규화 계층 사용 실험
import sys, os
sys.path.append(os.pardir)
import numpy as np
import matplotlib.pyplot as plt
from mnist import load_mnist
from common_multi_layer_net_extend import MultiLayerNetExtend
from common_optimizer import SGD, Adam
(x_train, t_train), (x_test, t_test) = load_mnist(normalize=True)
x_train = x_train[:1000]
t_train = t_train[:1000]
max_epochs = 20
train_size = x_train.shape[0]
batch_size = 100
learning_rate = 0.01
def __train(weight_init_std):
bn_network = MultiLayerNetExtend(input_size=784, hidden_size_list=[100, 100, 100, 100, 100], output_size=10,
weight_init_std=weight_init_std, use_batchnorm=True)
network = MultiLayerNetExtend(input_size=784, hidden_size_list=[100, 100, 100, 100, 100], output_size=10,
weight_init_std=weight_init_std)
optimizer = SGD(lr=learning_rate)
train_acc_list = []
bn_train_acc_list = []
iter_per_epoch = max(train_size / batch_size, 1)
epoch_cnt = 0
for i in range(1000000000):
batch_mask = np.random.choice(train_size, batch_size)
x_batch = x_train[batch_mask]
t_batch = t_train[batch_mask]
for _network in (bn_network, network):
grads = _network.gradient(x_batch, t_batch)
optimizer.update(_network.params, grads)
if i % iter_per_epoch == 0:
train_acc = network.accuracy(x_train, t_train)
bn_train_acc = bn_network.accuracy(x_train, t_train)
train_acc_list.append(train_acc)
bn_train_acc_list.append(bn_train_acc)
print("epoch:" + str(epoch_cnt) + " | " + str(train_acc) + " - " + str(bn_train_acc))
epoch_cnt += 1
if epoch_cnt >= max_epochs:
break
return train_acc_list, bn_train_acc_list
weight_scale_list = np.logspace(0, -4, num=16)
x = np.arange(max_epochs)
for i, w in enumerate(weight_scale_list):
print( "============== " + str(i+1) + "/16" + " ==============")
train_acc_list, bn_train_acc_list = __train(w)
plt.subplot(4,4,i+1)
plt.title("W:" + str(w))
if i == 15:
plt.plot(x, bn_train_acc_list, label='Batch Normalization', markevery=2)
plt.plot(x, train_acc_list, linestyle = "--", label='Normal(without BatchNorm)', markevery=2)
else:
plt.plot(x, bn_train_acc_list, markevery=2)
plt.plot(x, train_acc_list, linestyle="--", markevery=2)
plt.ylim(0, 1.0)
if i % 4:
plt.yticks([])
else:
plt.ylabel("accuracy")
if i < 12:
plt.xticks([])
else:
plt.xlabel("epochs")
plt.legend(loc='lower right')
plt.show()
[실선이 배치 정규화를 사용한 경우, 점선이 사용하지 않은 경우: 가중치 초깃값의 표준편차는 각 그래프 위에 표기]
- 참고: 밑바닥부터 시작하는 딥러닝1
- notobook ipynb file: https://github.com/heejvely/Deep_learning/blob/main/%EB%B0%91%EB%B0%94%EB%8B%A5%EB%B6%80%ED%84%B0_%EC%8B%9C%EC%9E%91%ED%95%98%EB%8A%94_%EB%94%A5%EB%9F%AC%EB%8B%9D_1/%ED%95%99%EC%8A%B5%20%EA%B4%80%EB%A0%A8%20%EA%B8%B0%EC%88%A0%EB%93%A4.ipynb
728x90
'Deep Learning' 카테고리의 다른 글
[Deep Learning]퍼셉트론(Perceptron) (0) | 2022.11.16 |
---|---|
[Deep Learning]overfitting, drop out, hyper-parameter 최적화 (0) | 2022.11.13 |
[Deep Learning] 가중치의 초깃값 (0) | 2022.11.13 |
[Deep Learning]Optimizer 매개변수 갱신 (2) | 2022.11.13 |
[Deep Learning]오차역전파의 계산법 (0) | 2022.11.11 |