简体   繁体   English

如何在c ++中加载caffe模型进行预测

[英]How to load caffe model in c++ for predicition

I have been using Caffe on Python so far and now I am trying to use C++ to familiarize myself. 到目前为止,我一直在Python上使用Caffe,现在我正在尝试使用C ++来熟悉自己。

What I have done is I tried to explore the caffe FC layers by computing features and loading thru HDF5 layer. 我所做的是我试图通过计算功能和加载HDF5层来探索caffe FC层。 I have trained the model and it works very well with python using the following code: 我已经训练了模型,使用以下代码可以很好地使用python:

caffe.set_device(0)
caffe.set_mode_gpu()
net = caffe.Net(proto_file, caffe_model, caffe.TEST)    
feats, labels = get_features('test/test.txt')   #AlexNet features
for feature, label in zip(feats, labels):
    net.blobs['data'].data[...] = feature
    output = net.forward()
    output_prob = output['loss'][0]
    print output_prob.argmax(), ", ", label

Using this python code I can check and it works very well. 使用这个python代码我可以检查它,它的工作原理非常好。

I am trying to write the code in c++ to do the same prediction. 我试图用c ++编写代码来做同样的预测。 This line 这条线

net.blobs['data'].data[...] = feature

is bit tricky and I cannot do the same in c++: How can I load features into the data layer in c++: 有点棘手,我不能在c ++中做同样的事情:如何在c ++中将功能加载到数据层:

my c++ code so far is: 到目前为止,我的c ++代码是:

    caffe::Caffe::SetDevice(0);
    caffe::Caffe::set_mode(caffe::Caffe::GPU);
    boost::shared_ptr<caffe::Net<float> > net_;
    net_.reset(new caffe::Net<float>(model_file, caffe::TEST));
    net_->CopyTrainedLayersFrom(trained_file);

    std::cout << "LOADED CAFFE MODEL\n";
    LOG(INFO) << "Blob size: "<< net_->input_blobs().size();

This caffe example is useful but it loads image and then separates the channels. 这个caffe示例很有用,但它会加载图像然后分离通道。 In my case I have 4096-D feature vector from AlexNet which I want to load directly as in Python code. 在我的例子中,我有来自AlexNet的4096-D特征向量,我想像Python代码一样直接加载。

Get the blob index according to its name: 根据名称获取blob索引:

const std::vector<std::string>& blob_names_ = net_->blob_names();
auto it = std::find(blob_names_.begin(), blob_names_.end(), "data");
int index = -1;
if (it == blob_names_.end())
{
    // no "data" blob, do error handling
}
else
{
    index = std::distance(blob_names_.begin(), it);
}

(Of course you can also get the index by iterating over blob_names_ and compare each item). (当然,您也可以通过迭代blob_names_来获取索引并比较每个项目)。

Change the blob data: 更改blob数据:

float* feature = your_func_to_get_feature(); // custom this
caffe::Blob<float>*>& blob_to_set_ = net_->blobs()[index];
blob_to_set_->set_cpu_data(feature);

Continue from this point as usual. 像往常一样从这一点继续。

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

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