到目前为止,我一直在 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++ 中做同样的事情:How can I load features into the data layer in 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很有用,但它会加载图像,然后分离 channel 。在我的例子中,我有来自 AlexNet 的 4096-D 特征向量,我想像在 Python 代码中一样直接加载它。
最佳答案
根据名称获取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);
像往常一样从这里开始。
关于c++ - 如何在C++中加载caffe模型进行预测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38529132/