我在 C++
中使用caffe进行机器学习。
在通过网络net_->Forward();
后,我想提取单个图层的信息。
我做的是
net_->Forward();
//Extract layer information
cout << "Num layers:" << "'" << net_->layer_names().size() << "'"<< endl;
for (int layer_index = 0; layer_index < net_->layer_names().size(); ++layer_index)
{
// get that layer blob and its dimension
const boost::shared_ptr<Blob<float> > blob = net_->blob_by_name(net_->blob_names()[layer_index]);
int batch_size = blob->num();
int dim_features = blob->count() / batch_size;
std::cout << "Layer name:" << "'" << net_->layer_names()[layer_index] << "'" << " Blob name:" << "'" <<net_->blob_names()[layer_index] << "'" << " batch size " << "'" << batch_size << "'" << " dim_features:" << "'" << dim_features << "'" << std::endl;
}
我可以看到所有图层名称和尺寸。
Layer name'image' Blob name'image' batch_size'1' dim_features'921600'
Layer name'conv1/7x7_s2' Blob name'conv1/7x7_s2' batch_size'1' dim_features'4915200'
Layer name'conv1/relu_7x7' Blob name'pool1/3x3_s2' batch_size'1' dim_features'1228800'
Layer name'pool1/3x3_s2' Blob name'pool1/norm1' batch_size'1' dim_features'1228800'
Layer name'pool1/norm1' Blob name'conv2/3x3_reduce' batch_size'1' dim_features'1228800'
Layer name'conv2/3x3_reduce' Blob name'conv2/3x3' batch_size'1' dim_features'3686400'
Layer name'conv2/relu_3x3_reduce' Blob name'conv2/norm2' batch_size'1' dim_features'3686400'
但在这里我仍然需要更深入的信息。
当前尺寸为921600,由批量大小x通道x高x宽= 921600组成。
(1)所以我的第一个问题是如何拆分信息?
(2)说我有这个信息批量大小x通道x高x宽= 1 x 3 x 480 x 640.然后
如何在blob中提取每个图层,如1 x 1 x 480 x 640,这样我就可以打印或者我可以进行绘图。
我可以用Python做的那种事情,比如
for layer_name, blob in net.blobs.iteritems():
print layer_name + '\t' + str(blob.data.shape)
mydata = net.blobs[layer_name].data[0,0,:,:]
#cv2.imshow("mydata",mydata);
#cv2.waitKey(1)
layer_name = layer_name.replace('/', '_')
np.savetxt("printdata/"+layer_name+".csv", mydata, delimiter=",")
但就目前而言,我喜欢 C++
。
答案 0 :(得分:2)
问题1:
如果你查看blob.hpp
文件,它有几种方法来获取blob的维度。您可以调用返回shape()
的{{1}}或已弃用的方法,例如const vector<int>&
,num()
,channels()
,height()
,返回width()
。所以对于你的情况应该是这样的:
int
编辑:
问题2: 如果图层有3个通道,那么您可以执行此操作以显示为图像:
int batch_size = blob->num();
int channels = blob->channels();
int height = blob->height();
int width = blob->width();
std::cout << "Layer name:" << "'" << net_->layer_names()[layer_index] << "'" << " Blob name:" << "'" <<net_->blob_names()[layer_index] << "'" << " batch size " << "'" << batch_size << "'" << " channels:" << "'" << channels << "'" << " height:" << "'" << height << "'" << " width:" << "'" << width << "'" << std::endl;