0
我正在從Theano過渡到火炬。所以請耐心等待。在Theano中,計算甚至是特定重量的損失函數的梯度是很直接的。我想知道,火炬手怎麼能做到這一點?如何計算火炬中任意圖層/重量的損失梯度?
假設我們有以下的代碼生成一些數據/標籤,並且限定模型:
t = require 'torch'
require 'nn'
require 'cunn'
require 'cutorch'
-- Generate random labels
function randLabels(nExamples, nClasses)
-- nClasses: number of classes
-- nExamples: number of examples
label = {}
for i=1, nExamples do
label[i] = t.random(1, nClasses)
end
return t.FloatTensor(label)
end
inputs = t.rand(1000, 3, 32, 32) -- 1000 samples, 3 color channels
inputs = inputs:cuda()
labels = randLabels(inputs:size()[1], 10)
labels = labels:cuda()
net = nn.Sequential()
net:add(nn.SpatialConvolution(3, 6, 5, 5))
net:add(nn.ReLU())
net:add(nn.SpatialMaxPooling(2, 2, 2, 2))
net:add(nn.View(6*14*14))
net:add(nn.Linear(6*14*14, 300))
net:add(nn.ReLU())
net:add(nn.Linear(300, 10))
net = net:cuda()
-- Loss
criterion = nn.CrossEntropyCriterion()
criterion = criterion:cuda()
forwardPass = net:forward(inputs)
net:zeroGradParameters()
dEd_WeightsOfLayer1 -- How to compute this?
forwardPass = nil
net = nil
criterion = nil
inputs = nil
labels = nil
collectgarbage()
如何能夠計算梯度w.r.t convolutinal層的權重?