如何使用火炬从caffe模型中获取图层

Ale*_*xis 2 python lua 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] // I want to get this value in lua
Run Code Online (Sandbox Code Playgroud)

当我使用火炬时,我有点卡住,因为我不知道如何执行相同的动作.目前我有以下代码

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') -- not working
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激

del*_*eil 11

首先请注意,由于LuaJIT FFI,火炬咖啡绑定(即您使用的工具require 'caffe')是Caffe库的直接包装.

这意味着它允许您方便地使用Torch张量向前或向后进行, 在幕后这些操作是在一个caffe::Net而不是在Torch nn网络上进行的.

因此,如果您想操作普通的Torch网络,您应该使用的是loadcaffe库,它将网络完全转换为nn.Sequential:

require 'loadcaffe'

local net = loadcaffe.load('net.prototxt', 'net.caffemodel')
Run Code Online (Sandbox Code Playgroud)

然后你可以使用findModules.但请注意,您不能再使用他们的初始标签(如conv1fc7),因为它们在转换后会被丢弃.

这里fc7(= INNER_PRODUCT)对应于N-1线性变换.所以你可以得到如下:

local nodes = net:findModules('nn.Linear')
local fc7 = nodes[#nodes-1]
Run Code Online (Sandbox Code Playgroud)

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


UPDATE

从提交2516fac开始, loadcaffe现在另外保存了图层名称.因此,要检索'fc7'图层,您现在可以执行以下操作:

local fc7
for _,m in pairs(net:listModules()) do
  if m.name == 'fc7' then
    fc7 = m
    break
  end
end
Run Code Online (Sandbox Code Playgroud)