DropPath 解析
作者:elfin
DropPath是將深度學習模型中的多分支結構隨機”刪除“
https://github.com/yueatsprograms/Stochastic_Depth
1、DropPath實現
def drop_path(x, drop_prob: float = 0., training: bool = False):
if drop_prob == 0. or not training:
return x
keep_prob = 1 - drop_prob
shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)
random_tensor.floor_() # binarize
output = x.div(keep_prob) * random_tensor
return output
class DropPath(nn.Module):
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
"""
def __init__(self, drop_prob=None):
super(DropPath, self).__init__()
self.drop_prob = drop_prob
def forward(self, x):
return drop_path(x, self.drop_prob, self.training)
2、DropPath在網絡中的應用
假設在前向傳播中有如下的代碼:
x = x + self.drop_path(self.mlp(self.norm2(x)))
那么在drop_path分支中,每個batch有drop_prob的概率樣本在self.mlp(self.norm2(x))不會”執行“,會以0直接傳遞。
對應到上面的代碼,先對傳入的x進行了x.div(keep_prob)的放縮,這是為什么?
在Dropout中我們比較好理解,對權值放縮是為了獲得輸出的一致性,即期望不變,但是這里實際上是對某個樣本進行隨機Dropout某一部分結構。這一樣嗎?
首先我們看常規的Dropout解釋:
參考資料:https://www.imooc.com/article/30129
假設一個神經元的輸出激活值為a,在不使用dropout的情況下,其輸出期望值為a,如果使用了dropout,神經元就可能有保留和關閉兩種狀態,把它看作一個離散型隨機變量,它就符合概率論中的0-1分布,其輸出激活值的期望變為 p*a+(1-p)*0=pa,此時若要保持期望和不使用dropout時一致,就要除以p。
原文鏈接:https://blog.csdn.net/qbyqby7628/article/details/103449196
應該注意到在batch中,計算期望,我們的公式仍然滿足上面的關系,也即要除以keep_prob。
完!
