Welcome to mirror list, hosted at ThFree Co, Russian Federation.

L1Penalty.lua - github.com/torch/nn.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 24ee769a119e18f40358ee94102483996d5e8612 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
local L1Penalty, parent = torch.class('nn.L1Penalty','nn.Module')

--This module acts as an L1 latent state regularizer, adding the 
--[gradOutput] to the gradient of the L1 loss. The [input] is copied to 
--the [output]. 

function L1Penalty:__init(l1weight, sizeAverage, provideOutput)
    parent.__init(self)
    self.l1weight = l1weight 
    self.sizeAverage = sizeAverage or false  
    if provideOutput == nil then
       self.provideOutput = true
    else
       self.provideOutput = provideOutput
    end
end
    
function L1Penalty:updateOutput(input)
    local m = self.l1weight 
    if self.sizeAverage == true then 
      m = m/input:nElement()
    end
    local loss = m*input:norm(1) 
    self.loss = loss  
    self.output = input 
    return self.output 
end

function L1Penalty:updateGradInput(input, gradOutput)
    local m = self.l1weight 
    if self.sizeAverage == true then 
      m = m/input:nElement() 
    end
    
    self.gradInput:resizeAs(input):copy(input):sign():mul(m)
    
    if self.provideOutput == true then 
        self.gradInput:add(gradOutput)  
    end 

    return self.gradInput 
end