簡體   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