【问题标题】:How to load caffe model in c++ for predicition如何在 C++ 中加载 caffe 模型进行预测
【发布时间】:2016-11-26 12:23:01
【问题描述】:

到目前为止,我一直在 Python 上使用 Caffe,现在我正在尝试使用 C++ 来熟悉自己。

我所做的是尝试通过计算特征并通过 HDF5 层加载来探索 caffe FC 层。我已经训练了模型,它使用以下代码与 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

使用这个 python 代码,我可以检查它,它工作得很好。

我正在尝试用 C++ 编写代码来做同样的预测。这一行

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

有点棘手,我不能在 c++ 中做同样的事情:如何在 c++ 中将特征加载到数据层:

到目前为止,我的 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 很有用,但它会加载图像然后分离通道。就我而言,我有来自 AlexNet 的 4096-D 特征向量,我想像在 Python 代码中一样直接加载它。

【问题讨论】:

    标签: c++ machine-learning neural-network deep-learning caffe


    【解决方案1】:

    根据名称获取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);
    }
    

    (当然你也可以通过遍历blob_names_得到索引,然后比较每一项)。

    更改 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);
    

    像往常一样从这一点继续。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-16
      • 2022-01-12
      • 2016-02-19
      • 2017-12-11
      • 2021-11-03
      • 2020-07-14
      • 2022-08-10
      • 2016-08-24
      相关资源
      最近更新 更多