繁体   English   中英

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

[英]How to get a layer from a caffe model using 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

任何帮助,将不胜感激

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

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

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

require 'loadcaffe'

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

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

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

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

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


UPDATE

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM