如何使用 Torch 从 Caffe 模型中获取图层。

在 Python 中,当我使用 caffe 从图层中获取数据时,我有以下代码

input_image = caffe.io.load_image(imgName)
input_oversampled = caffe.io.resize_image(input_image, self.net.crop_dims)
prediction = self.net.predict([input_image])
caffe_input = np.asarray(self.net.preprocess('data', prediction))
self.net.forward(data=caffe_input)
data = self.net.blobs['fc7'].data[4] // 我想在 lua 中获取这个值

然而,在使用 torch 时,我有些困惑,因为我不知道如何执行相同的操作。 目前我有以下代码

require 'caffe'
require 'image'
net = caffe.Net('/opt/caffe/models/bvlc_reference_caffenet/deploy.prototxt', '/opt/caffe/models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel')
img = image.lena()
dest = torch.Tensor(3, 227,227)
img = image.scale(dest, img)
img = img:resize(10,3,227,227)
output = net:forward(img:float())
conv_nodes = net:findModules('fc7') -- 不起作用

任何帮助将不胜感激。

点赞
用户1688185
用户1688185

首先请注意,torch-caffe-binding(即您与require'caffe'一起使用的工具)是LuaJIT FFI的直接封装器,围绕Caffe库构建而成。 这意味着它允许您方便地使用Torch张量进行向前或向后操作,但在幕后,这些操作是在caffe::Net上进行的,而不是在Torch nn网络上进行的。 因此,如果您想操纵普通的Torch网络 ,则应使用loadcaffe库,该库会将网络完全转换为nn.Sequential

require'loadcaffe'

local net = loadcaffe.load('net.prototxt''net.caffemodel')

然后,您可以使用findModules。但是,请注意,您不能再使用它们的初始标签(例如conv1fc7),因为它们会在convert之后被丢弃

这里的fc7(=INNER_PRODUCT)对应于N-1线性变换。因此,您可以按如下方式获取它:

local nodes = net:findModules('nn.Linear')
local fc7 = nodes[#nodes-1]

然后,您可以通过fc7.weightfc7.bias读取数据(权重和偏差) - 这些都是常规的torch.Tensor

更新 截至提交 2516fac ,loadcaffe现在也保存了层名称。因此,要检索'fc7'层,您现在可以执行以下操作:

local fc7
for _, m in pairs(net: listModules()) do
    if m.name == 'fc7' then
        fc7 = m
        break
    end
end
2015-01-28 09:51:23