2017-10-17 66 views
0

我需要添加一個L1規範作爲正則化函數,以便在我的神經網絡中創建一個稀疏條件。我想訓練我的網絡分類,我需要添加一個L1規範作爲正規化者來創建稀疏條件。我需要訓練網絡進行分類,我先從pytorch開始,但我沒有任何意識如何做到這一點。我嘗試着自己構建一個L1規範,比如here,但沒有工作。作爲Pytorch中的正則化函數的L1規範

有人可以幫助我嗎?我需要把ConvTranspose2d在此之後正則,我想做些事情像這樣Keras:

model.add(Dense(64, input_dim=64, 
      kernel_regularizer=regularizers.l2(0.01), 
      activity_regularizer=regularizers.l1(0.01))) 

但根據下面

upconv = nn.ConvTranspose2d(inner_nc, outer_nc, 
            kernel_size=4, stride=2, 
            padding=1, bias=use_bias) 
     down = [downrelu, downconv] 
     up = [uprelu, upconv, upnorm] 
     model = down + up 

感謝

回答

1

代碼在我的網絡PyTorch創建你正在超越這個。正如我從你的Keras代碼看到的,你試圖在你的圖層的激活上施加L1懲罰。最簡單的方法也只是做一些這樣的:

activations_to_regularise = upconv(input) 
output = remaining_netowrk(activations_to_regularise) 

然後讓你的正常損失函數評價針對的目標輸出,並且也將在L1流失到目標,這樣你得到

total_loss = criterion(output, target) + 0.01 * activations_to_regularise.abs() 
1

在pytorch,你可以做以下(假設你的網絡被稱爲net):

def l1_loss(x): 
    return torch.abs(x).sum() 

to_regularise = [] 
for param in net.parameters(): 
    to_regularise.append(param.view(-1)) 
l1 = l1_weight*l1_loss(torch.cat(to_regularise))