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

时间:2015-01-27 13:22:44

标签: python lua caffe torch

在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

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

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

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:11)

首先请注意,感谢LuaJIT FFI,torch-caffe-binding(即与require 'caffe'一起使用的工具)是Caffe库的直接包装。

这意味着它可以让你方便地使用Torch张量前进或后退,但是 behind the scenes这些操作是在caffe::Net而不是在火炬上进行的nn网络。

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

require 'loadcaffe'

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

然后你可以使用findModules。但请注意,您不能再使用他们的初始标签(例如conv1fc7),因为它们是discarded after convert

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

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

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


<强>更新

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

local fc7
for _,m in pairs(net:listModules()) do
  if m.name == 'fc7' then
    fc7 = m
    break
  end
end
相关问题