在 Torch 中将 Softmax 添加到 ResNet 模型

Adding Softmax to ResNet model in Torch

Context:我正在尝试修改 this Facebook's ResNet feature extractor script 以 class 化图像并打印 ImageNet class 标签。 假设我在火炬中有模型:

local model = torch.load('resnet-101.t7')
local output = model:forward(img:cuda()):squeeze(1)

这给了我每个 class 的分数。我想获得前 5 个 classes 及其概率。我认为要将分数转换为概率,我应该首先使用 SoftMax 层。

所以我这样做:

local model = torch.load('resnet-101.t7')
local softMaxLayer = cudnn.LogSoftMax()
model:add(softMaxLayer)
local output = model:forward(img:cuda()):squeeze(1)

但是当我 运行 它时,我得到:

/SpatialSoftMax.lua:38: bad argument #1 to 'resizeAs' (torch.DoubleTensor expected, got torch.CudaTensor)

我觉得模型不错:(只显示最后一层)

  ...
  (9): cudnn.SpatialAveragePooling(7,7,1,1)
  (10): nn.View(2048)
  (11): nn.Linear(2048 -> 1000)
  (12): cudnn.LogSoftMax
}

有什么可能出错的想法吗?

层具有与之关联的类型。默认情况下,您会得到一个 double 类型

local softMaxLayer = cudnn.LogSoftMax():cuda()
model:add(softMaxLayer)