2017-02-03 3 views
0

私は単純な畳み込みニューラルネットワークを持っています。その出力は、単一チャネルの4x4特徴マップです。訓練中、(回帰)損失は、16個の出力のうちの1つの値のみで計算する必要があります。 この値の位置は、往路通過後に決定されます。バックプロップ中に無関係なグラデーションがすべてゼロになっていることを確認しながら、この1つの出力からの損失をどのように計算すればよいですか。トーチ:出力のサブセットで計算された損失からの逆伝播

のは、私がトーチで以下のような簡単なモデルを持っているとしましょう:

require 'nn' 

-- the input 
local batch_sz = 2 
local x = torch.Tensor(batch_sz, 3, 100, 100):uniform(-1,1) 

-- the model 
local net = nn.Sequential() 
net:add(nn.SpatialConvolution(3, 128, 9, 9, 9, 9, 1, 1)) 
net:add(nn.SpatialConvolution(128, 1, 3, 3, 3, 3, 1, 1)) 
net:add(nn.Squeeze(1, 3)) 

print(net) 

-- the loss (don't know how to employ it yet) 
local loss = nn.SmoothL1Criterion() 

-- forward'ing x through the network would result in a 2x4x4 output 
y = net:forward(x) 

print(y) 

私はnn.SelectTableを見てきました、私が表形式に出力を変換する場合のように、私は私が欲しいものを実装することができるだろうと思われます?

答えて

0

これは私の現在の解決策です。私は誰かが単純ORより効率的な方法を指摘し、それを本当に感謝

require 'nn' 

-- the input 
local batch_sz = 2 
local x = torch.Tensor(batch_sz, 3, 100, 100):uniform(-1,1) 

-- the model 
local net = nn.Sequential() 
net:add(nn.SpatialConvolution(3, 128, 9, 9, 9, 9, 1, 1)) 
net:add(nn.SpatialConvolution(128, 1, 3, 3, 3, 3, 1, 1)) 
net:add(nn.Squeeze(1, 3)) 

-- convert output into a table format 
net:add(nn.View(1, -1))   -- vectorize 
net:add(nn.SplitTable(1, 1)) -- split all outputs into table elements 

print(net) 

-- the loss 
local loss = nn.SmoothL1Criterion() 

-- forward'ing x through the network would result in a (2)x4x4 output 
y = net:forward(x) 

print(y) 

-- returns the output table's index belonging to specific location 
function get_sample_idx(feat_h, feat_w, smpl_idx, feat_r, feat_c) 
    local idx = (smpl_idx - 1) * feat_h * feat_w 
    return idx + feat_c + ((feat_r - 1) * feat_w) 
end 

-- I want to back-propagate the loss of this sample at this feature location 
local smpl_idx = 2 
local feat_r = 3 
local feat_c = 4 
-- get the actual index location in the output table (for a 4x4 output feature map) 
local out_idx = get_sample_idx(4, 4, smpl_idx, feat_r, feat_c) 

-- the (fake) ground-truth 
local gt = torch.rand(1) 

-- compute loss on the selected feature map location for the selected sample 
local err = loss:forward(y[out_idx], gt) 
-- compute loss gradient, as if there was only this one location 
local dE_dy = loss:backward(y[out_idx], gt) 
-- now convert into full loss gradient (zero'ing out irrelevant losses) 
local full_dE_dy = nn.SelectTable(out_idx):backward(y, dE_dy) 
-- do back-prop through who network 
net:backward(x, full_dE_dy) 

print("The full dE/dy") 
print(table.unpack(full_dE_dy)) 

:それはテーブルに出力を分割することで動作し、その後nn.SelectTable()を使用して:完全な勾配を得るために、後方を()。

関連する問題