關於batch normalization的論文閱讀可以參考以前的一篇博文Batch Normalization,這裏主要對BN的導數進行推導,並且看一下tensorflow中的源碼實現。
BN導數推導
正向計算
回顧一下Batch Normalization的正向計算公式:
(1)
(2)
(3)
(4)
自己實現這個功能代碼如下:
def batchnorm_forward(x, gamma, beta, bn_param):
"""
Forward pass for batch normalization.
During training the sample mean and (uncorrected) sample variance are
computed from minibatch statistics and used to normalize the incoming data.
During training we also keep an exponentially decaying running mean of the
mean and variance of each feature, and these averages are used to normalize
data at test-time.
At each timestep we update the running averages for mean and variance using
an exponential decay based on the momentum parameter:
running_mean = momentum * running_mean + (1 - momentum) * sample_mean
running_var = momentum * running_var + (1 - momentum) * sample_var
Note that the batch normalization paper suggests a different test-time
behavior: they compute sample mean and variance for each feature using a
large number of training images rather than using a running average. For
this implementation we have chosen to use running averages instead since
they do not require an additional estimation step; the torch7
implementation of batch normalization also uses running averages.
Input:
- x: Data of shape (N, D)
- gamma: Scale parameter of shape (D,)
- beta: Shift paremeter of shape (D,)
- bn_param: Dictionary with the following keys:
- mode: 'train' or 'test'; required
- eps: Constant for numeric stability
- momentum: Constant for running mean / variance.
- running_mean: Array of shape (D,) giving running mean of features
- running_var Array of shape (D,) giving running variance of features
Returns a tuple of:
- out: of shape (N, D)
- cache: A tuple of values needed in the backward pass
"""
mode = bn_param['mode']
eps = bn_param.get('eps', 1e-5)
momentum = bn_param.get('momentum', 0.9)
N, D = x.shape
running_mean = bn_param.get('running_mean', np.zeros(D, dtype=x.dtype))
running_var = bn_param.get('running_var', np.zeros(D, dtype=x.dtype))
out, cache = None, None
if mode == 'train':
#######################################################################
# TODO: Implement the training-time forward pass for batch norm. #
# Use minibatch statistics to compute the mean and variance, use #
# these statistics to normalize the incoming data, and scale and #
# shift the normalized data using gamma and beta. #
# #
# You should store the output in the variable out. Any intermediates #
# that you need for the backward pass should be stored in the cache #
# variable. #
# #
# You should also use your computed sample mean and variance together #
# with the momentum variable to update the running mean and running #
# variance, storing your result in the running_mean and running_var #
# variables. #
# #
# Note that though you should be keeping track of the running #
# variance, you should normalize the data based on the standard #
# deviation (square root of variance) instead! #
# Referencing the original paper (https://arxiv.org/abs/1502.03167) #
# might prove to be helpful. #
#######################################################################
pass
mean = np.sum(x, axis=0) / N
var = np.sum((x - mean) ** 2, axis=0) / N
x_hat = (x - mean) / np.sqrt(var + eps)
out = gamma * x_hat + beta
cache = {}
cache['x_hat'] = x_hat
cache['gamma'] = gamma
cache['var_eps'] = var + eps
cache['x_norm'] = x - mean
running_mean = momentum * running_mean + (1 - momentum) * mean
running_var = momentum * running_var + (1 - momentum) * var
#######################################################################
# END OF YOUR CODE #
#######################################################################
elif mode == 'test':
#######################################################################
# TODO: Implement the test-time forward pass for batch normalization. #
# Use the running mean and variance to normalize the incoming data, #
# then scale and shift the normalized data using gamma and beta. #
# Store the result in the out variable. #
#######################################################################
pass
x_hat = (x - running_mean) / np.sqrt(running_var + eps)
out = gamma * x_hat + beta
#######################################################################
# END OF YOUR CODE #
#######################################################################
else:
raise ValueError('Invalid forward batchnorm mode "%s"' % mode)
# Store the updated running means back into bn_param
bn_param['running_mean'] = running_mean
bn_param['running_var'] = running_var
return out, cache
代碼中有幾個點需要注意:
- 我們需要區分訓練和測試階段,因爲訓練時mean和var是用當前數據計算的,但是測試時我們需要使用running_mean和running_var來計算。
- running_mean和running_var是用每次的mean和var加上動量計算出來的,在數據測試時使用。
- 需要cache很多數據,爲了在求導時使用。
- 表示樣本個數,表示feature個數,所以的尺寸按照cs231那種的表示習慣爲,的尺寸爲,的會與每個相乘所以尺寸爲,尺寸爲,的尺寸爲,因爲我們只是用batch normaliaztion做分佈變換,所以變換後尺寸是不變的。
反向計算
因爲在正向傳播中的計算都是矩陣元素計算,不是點積,所以我們基本不用考慮矩陣轉置的問題,而需要考慮的是何時求和的問題。
反向傳播中我們已知cache中保存的信息和損失函數對的導數(是對全部求導的矩陣),需要求三個導數分別是,和(雖然這裏實際上是損失函數對他們求偏導,但是爲了表示方便,就直接寫成)。
首先求
因爲最後的損失函數是每個相關函數的求和,所以對求導需要進行求和
(5)
接着求
(6)
最後求
因爲與,和相關,所以寫出下面的導數
(7)
所以接下來的任務就是要求出
(8)
因爲只與相關,並且與每個參與計算後求和纔是最後的cost函數,所以可以推導公式如下:
(9)
而與有關,所以可以推導公式如下:
(10)
將8,9,10式子互相帶入再帶入7就可以得到
自己實現代碼如下:
def batchnorm_backward(dout, cache):
"""
Backward pass for batch normalization.
For this implementation, you should write out a computation graph for
batch normalization on paper and propagate gradients backward through
intermediate nodes.
Inputs:
- dout: Upstream derivatives, of shape (N, D)
- cache: Variable of intermediates from batchnorm_forward.
Returns a tuple of:
- dx: Gradient with respect to inputs x, of shape (N, D)
- dgamma: Gradient with respect to scale parameter gamma, of shape (D,)
- dbeta: Gradient with respect to shift parameter beta, of shape (D,)
"""
dx, dgamma, dbeta = None, None, None
###########################################################################
# TODO: Implement the backward pass for batch normalization. Store the #
# results in the dx, dgamma, and dbeta variables. #
# Referencing the original paper (https://arxiv.org/abs/1502.03167) #
# might prove to be helpful. #
###########################################################################
pass
x_hat = cache['x_hat']
gamma = cache['gamma']
var_eps = cache['var_eps']
x_norm = cache['x_norm']
N = dout.shape[0]
dgamma = np.sum(dout * x_hat, axis=0)
dbeta = np.sum(dout, axis=0)
dx_hat = dout * gamma
dvar = np.sum(dx_hat * (x_norm * (-1 / 2) * (var_eps ** (-3 / 2))), axis=0)
dmean = np.sum(dx_hat * (-1 / np.sqrt(var_eps)), axis=0) + dvar * (-2) * np.sum(x_norm, axis=0) / N
dx = dx_hat / np.sqrt(var_eps) + dmean / N + dvar * 2 * x_norm / N
###########################################################################
# END OF YOUR CODE #
###########################################################################
return dx, dgamma, dbeta
論文中提供的公式如下:
公式簡化
但是求導公式其實還可以簡化,因爲
,所以可以簡化如下:
而是近似於0的,所以我們可以簡化
所以簡化後的和帶入
代碼如下:
def batchnorm_backward_alt(dout, cache):
"""
Alternative backward pass for batch normalization.
For this implementation you should work out the derivatives for the batch
normalizaton backward pass on paper and simplify as much as possible. You
should be able to derive a simple expression for the backward pass.
See the jupyter notebook for more hints.
Note: This implementation should expect to receive the same cache variable
as batchnorm_backward, but might not use all of the values in the cache.
Inputs / outputs: Same as batchnorm_backward
"""
dx, dgamma, dbeta = None, None, None
###########################################################################
# TODO: Implement the backward pass for batch normalization. Store the #
# results in the dx, dgamma, and dbeta variables. #
# #
# After computing the gradient with respect to the centered inputs, you #
# should be able to compute gradients with respect to the inputs in a #
# single statement; our implementation fits on a single 80-character line.#
###########################################################################
pass
x_hat = cache['x_hat']
gamma = cache['gamma']
var_eps = cache['var_eps']
N = dout.shape[0]
dgamma = np.sum(dout * x_hat, axis=0)
dbeta = np.sum(dout, axis=0)
dx_hat = dout * gamma
dx = 1 / (N * np.sqrt(var_eps)) * (dx_hat * N - np.sum(dx_hat, axis=0) - x_hat * np.sum(dx_hat * x_hat, axis=0))
###########################################################################
# END OF YOUR CODE #
###########################################################################
return dx, dgamma, dbeta