【问题标题】:In Torch/Lua can I split/concat tensors as they flow through a network?在 Torch/Lua 中,当张量流过网络时,我可以拆分/连接张量吗?
【发布时间】:2018-05-05 07:52:09
【问题描述】:
我是 Lua/Torch 的新手。我有一个包含最大池层的现有模型。我想将输入带入该层并将其拆分为块,将每个块馈送到一个新的最大池化层。
我编写了一个独立的 Lua 脚本,它可以将张量分成两个块,并将这两个块转发到具有两个最大池化层的网络中。
但是尝试将其重新集成到现有模型中,我无法弄清楚如何在“中流”修改数据以进行张量拆分。我已经阅读了文档,但看不到任何功能或架构示例,沿线某处将张量分成两个并分别转发每个部分。
有什么想法吗?谢谢!
【问题讨论】:
标签:
lua
neural-network
deep-learning
torch
max-pooling
【解决方案1】:
你想自己定义一个层。
如果您的图层输入是一维的,则图层将如下所示:
CSplit, parent = torch.class('nn.CSplit', 'nn.Module')
function CSplit:__init(firstCount)
self.firstCount = firstCount
parent.__init(self)
end
function CSplit:updateOutput(input)
local inputSize = input:size()[1]
local firstCount = self.firstCount
local secondCount = inputSize - firstCount
local first = torch.Tensor(self.firstCount)
local second = torch.Tensor(secondCount)
for i=1, inputSize do
if i <= firstCount then
first[i] = input[i]
else
second[i - firstCount] = input[i]
end
end
self.output = {first, second}
return self.output
end
function CSplit:updateGradInput(input, gradOutput)
local inputSize = input:size()[1]
self.gradInput = torch.Tensor(input)
for i=1, inputSize do
if i <= self.firstCount then
self.gradInput[i] = gradOutput[1][i]
else
self.gradInput[i] = gradOutput[2][i-self.firstCount]
end
end
return self.gradInput
end
如何使用它?您需要像下面的代码一样指定第一个块的大小。
testNet = nn.CSplit(4)
input = torch.randn(10)
output = testNet:forward(input)
print(input)
print(output[1])
print(output[2])
testNet:backward(input, {torch.randn(4), torch.randn(6)})
你可以看到可运行的 iTorch notebook 代码here