1.BatchNorm
在訓練深度網絡模型時,BN(Batch Normalization)層能夠加速網絡收斂,并且能夠控制過拟合,一般放在卷積層之後。如下示意圖所示,BatchNorm是以通道為機關,對目前通道中所有的N、H、W做歸一化。

BN 層将特征歸一化後,能夠有效解決由于特征分布不均勻而導緻的梯度消失與梯度爆炸問題。并通過可學習參數保證特征的有效性。雖然 BN 層在訓練時起到了積極作用,然而,在網絡前向推斷時多了一些層的運算,影響了模型的性能,且占用了更多的記憶體或者顯存空間。基于此将卷積後的BN操作直接融合到卷積中,這是現在工程上普遍會使用的方法。
2.将BN操作合并到卷積中
3.pytorch代碼實作
很明顯,下述代碼就是将上部分中的公式進行了代碼化。在這裡不得不說一句pytorch大法NB。
conv_param = model_state_dict[merge_bn_model_dict_key[index]]
conv_bias = model_state_dict[merge_bn_model_dict_key[index+1]]
outchannel = conv_param.size()[1]
bn_weignt = model_state_dict[merge_bn_model_dict_key[index+2]]
bn_bias = model_state_dict[merge_bn_model_dict_key[index+3]]
bn_mean = model_state_dict[merge_bn_model_dict_key[index+4]]
bn_var = model_state_dict[merge_bn_model_dict_key[index+5]]
#merge
var_sqrt = torch.sqrt(bn_var+bn_eps)
merge_bn_conv_param = conv_param*((bn_weight/var_sqrt)
merge_bn_conv_bias = bn_bias + bn_weight*(conv_bias-bn_mean/var_sqrt)
new_conv_key = merge_bn_model_dict_key[index]
new_bias_key = new_conv_key[:,-6]+'bias'
merge_bn_model_dict[new_conv_key] = merge_bn_conv_param
merge_bn_model_dict[new_bias_key] = merge_bn_conv_bias