Deep Learning學(xué)習(xí)筆記(四) 對(duì)Batch Normalization(批量歸一化)的理解

Batch Normalization(以下簡(jiǎn)稱BN)是在GoogleInceptionNet V2的論文中被提出的皿淋,該方法減輕了如何合理初始化神經(jīng)網(wǎng)絡(luò)這個(gè)棘手問題帶來的頭痛。

另一片博客主要從為什么要進(jìn)行Batch Normalization探孝,怎么進(jìn)行Batch Normalization,Batch Normalization究竟做了什么等方面去闡述誉裆,可以兩者結(jié)合在一起理解Batch Normalization顿颅。

一、原理介紹

BN是一個(gè)非常有效的正則化方法足丢,可以讓大型卷積網(wǎng)絡(luò)的訓(xùn)練速度加快很多倍粱腻,同時(shí)收斂后的分類準(zhǔn)確率也可以得到大幅提升。BN在用于神經(jīng)網(wǎng)絡(luò)某層時(shí)斩跌,會(huì)對(duì)每一個(gè)mini-batch數(shù)據(jù)的內(nèi)部進(jìn)行標(biāo)準(zhǔn)化處理绍些,使輸出規(guī)范化到N(0,1)的正太分布減少了內(nèi)部神經(jīng)元分布的改變Internal Covariate Shift)耀鸦。BN論文指出遇革,傳統(tǒng)的深度神經(jīng)網(wǎng)絡(luò)在訓(xùn)練時(shí),每一層的輸入分布都在變化揭糕,導(dǎo)致訓(xùn)練變得困難萝快,我們只能使用一個(gè)很小的學(xué)習(xí)率來解決這個(gè)問題。而對(duì)每一層使用BN之后著角,我們就可以有效的解決這個(gè)問題揪漩。

二、實(shí)踐細(xì)節(jié)

在實(shí)現(xiàn)層面吏口,應(yīng)用這個(gè)技巧通常意味著全連接層(或者是卷積層)與激活函數(shù)之間添加一個(gè)BN層奄容,對(duì)數(shù)據(jù)進(jìn)行處理使其服從標(biāo)準(zhǔn)高斯分布。因?yàn)闅w一化是一個(gè)簡(jiǎn)單可求導(dǎo)的操作产徊,所以上述思路是可行的昂勒。
全連接層fc/卷積層conv--->批量歸一化Batch Normalization--->激活函數(shù)activation function

單純使用BN獲得增益并不明顯,還需要一些對(duì)應(yīng)的調(diào)整:

  • 增大學(xué)習(xí)速率并加快學(xué)習(xí)衰減速度以適用BN規(guī)范化后的數(shù)據(jù)舟铜;
  • 去除Dropout并減輕L2正則化(因?yàn)锽N已經(jīng)可以起到正則化的作用)戈盈;
  • 更徹底的對(duì)訓(xùn)練樣本進(jìn)行shuffle,減少數(shù)據(jù)增強(qiáng)過程中對(duì)數(shù)據(jù)的光學(xué)畸變(因?yàn)?strong>BN訓(xùn)練更快谆刨,每個(gè)樣本被訓(xùn)練的次數(shù)更少,因此更真實(shí)的樣本對(duì)訓(xùn)練更有幫助)塘娶。

三、公式推導(dǎo)

前向傳播過程
前向傳播過程.png
反向傳播過程
反向傳播過程.png

四痊夭、代碼實(shí)現(xiàn)

前向傳播過程
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':
    # Compute output
    mu = x.mean(axis=0)
    xc = x - mu
    var = np.mean(xc ** 2, axis=0)
    std = np.sqrt(var + eps)
    xn = xc / std
    out = gamma * xn + beta

    cache = (mode, x, gamma, xc, std, xn, out)

    # Update running average of mean
    running_mean *= momentum
    running_mean += (1 - momentum) * mu

    # Update running average of variance
    running_var *= momentum
    running_var += (1 - momentum) * var
  elif mode == 'test':
    # Using running mean and variance to normalize
    std = np.sqrt(running_var + eps)
    xn = (x - running_mean) / std
    out = gamma * xn + beta
    cache = (mode, x, xn, gamma, beta, std)
  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
反向傳播過程
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,)
  """
 

 mode = cache[0]
  if mode == 'train':
    mode, x, gamma, xc, std, xn, out = cache

    N = x.shape[0]
    dbeta = dout.sum(axis=0)
    dgamma = np.sum(xn * dout, axis=0)
    dxn = gamma * dout
    dxc = dxn / std
    dstd = -np.sum((dxn * xc) / (std * std), axis=0)
    dvar = 0.5 * dstd / std
    dxc += (2.0 / N) * xc * dvar
    dmu = np.sum(dxc, axis=0)
    dx = dxc - dmu / N
  elif mode == 'test':
    mode, x, xn, gamma, beta, std = cache
    dbeta = dout.sum(axis=0)
    dgamma = np.sum(xn * dout, axis=0)
    dxn = gamma * dout
    dx = dxn / std
  else:
    raise ValueError(mode)

  return dx, dgamma, dbeta

在實(shí)踐中刁岸,使用了批量歸一化的網(wǎng)絡(luò)對(duì)于不好的初始值有更強(qiáng)的魯棒性∷遥總結(jié)起來說就是批量歸一化可以理解為在網(wǎng)絡(luò)的每一層之前都做預(yù)處理虹曙,只是這種操作以另一種方式與網(wǎng)絡(luò)集成在了一起迫横。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市酝碳,隨后出現(xiàn)的幾起案子矾踱,更是在濱河造成了極大的恐慌,老刑警劉巖击敌,帶你破解...
    沈念sama閱讀 223,207評(píng)論 6 521
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異拴事,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)刃宵,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,455評(píng)論 3 400
  • 文/潘曉璐 我一進(jìn)店門衡瓶,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人牲证,你說我怎么就攤上這事哮针。” “怎么了坦袍?”我有些...
    開封第一講書人閱讀 170,031評(píng)論 0 366
  • 文/不壞的土叔 我叫張陵十厢,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我捂齐,道長(zhǎng)蛮放,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 60,334評(píng)論 1 300
  • 正文 為了忘掉前任奠宜,我火速辦了婚禮包颁,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘压真。我一直安慰自己娩嚼,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,322評(píng)論 6 398
  • 文/花漫 我一把揭開白布滴肿。 她就那樣靜靜地躺著岳悟,像睡著了一般。 火紅的嫁衣襯著肌膚如雪泼差。 梳的紋絲不亂的頭發(fā)上竿音,一...
    開封第一講書人閱讀 52,895評(píng)論 1 314
  • 那天,我揣著相機(jī)與錄音拴驮,去河邊找鬼春瞬。 笑死,一個(gè)胖子當(dāng)著我的面吹牛套啤,可吹牛的內(nèi)容都是我干的宽气。 我是一名探鬼主播随常,決...
    沈念sama閱讀 41,300評(píng)論 3 424
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼萄涯!你這毒婦竟也來了绪氛?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 40,264評(píng)論 0 277
  • 序言:老撾萬榮一對(duì)情侶失蹤涝影,失蹤者是張志新(化名)和其女友劉穎枣察,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體燃逻,經(jīng)...
    沈念sama閱讀 46,784評(píng)論 1 321
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡序目,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,870評(píng)論 3 343
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了伯襟。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片猿涨。...
    茶點(diǎn)故事閱讀 40,989評(píng)論 1 354
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖姆怪,靈堂內(nèi)的尸體忽然破棺而出叛赚,到底是詐尸還是另有隱情,我是刑警寧澤稽揭,帶...
    沈念sama閱讀 36,649評(píng)論 5 351
  • 正文 年R本政府宣布俺附,位于F島的核電站,受9級(jí)特大地震影響溪掀,放射性物質(zhì)發(fā)生泄漏昙读。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,331評(píng)論 3 336
  • 文/蒙蒙 一膨桥、第九天 我趴在偏房一處隱蔽的房頂上張望蛮浑。 院中可真熱鬧,春花似錦只嚣、人聲如沸沮稚。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,814評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽蕴掏。三九已至,卻和暖如春调鲸,著一層夾襖步出監(jiān)牢的瞬間盛杰,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,940評(píng)論 1 275
  • 我被黑心中介騙來泰國(guó)打工藐石, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留即供,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 49,452評(píng)論 3 379
  • 正文 我出身青樓于微,卻偏偏與公主長(zhǎng)得像逗嫡,于是被迫代替她去往敵國(guó)和親青自。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,995評(píng)論 2 361