您的位置:首页 > Web前端

caffe的学习之路---Blob的基本用法

2016-10-05 19:54 483 查看
首先,参考书籍《21天实战caffe》

以前没有C++基础,所以第一次看这本书时候觉得好垃圾;

现在有了C++基础,再次看这本书,发现还是很值得学习。

在本文之前,我已经把官方tutorial看完。

要看懂blob.hpp建议将<C++ Primer>前七章看完,再学习caffe源码。

如果要看layer的相关文件,至少把前十五章看完,一起加油。


所以现在开始读源码,首先还是类模板Blob。

下面是自己将Blob写入磁盘,从磁盘读取内容存入Blob的程序,当然《21天实战caffe》的源码。主要写给自己看。

首先先说几个Member Function

1  void Reshape(const int num,const int channels,const int height,const int weight)

      void Reshape(const vector<int> &shape)

这2个函数的作用是重构blob的维数(Dim)

2     void FromProto(const BlobProto &proto, bool reshape=true)

      用法a.FromProto 将Blob类型的变量a写入一个类型为BlobProto的变量proto中

  这是数据从Blob到磁盘的中间处理层(作用就是序列化)

3    void ToProto(BlobProto *proto, bool write_diff=fasle ) 

     第二个参数输入true (将diff也序列化,默认是只把data序列化)

另外需要认识2个IO函数

1. void WriteProToBinaryFile(const Message &proto,const char *filename)

      void WriteProToBinaryFile(const Message &proto,const string filename)

  从名字就看出是将BlobPro写入二进制文件filename

2.  bool ReadProtoFromBinaryFile(const char *filename,Message *proto)

     bool ReadProtoFromBinaryFile(const string &filename,Message *proto)

#include <vector>
#include <iostream>
#include <caffe/blob.hpp>
#include <caffe/util/io.hpp>

using namespace caffe;
using namespace std;

int main(){
Blob<float> a;
a.Reshape(1,2,3,4);
float *p=a.mutable_cpu_data();
float *q=a.mutable_cpu_diff();
for(int i=0;i<a.count();i++){
p[i]=i;
q[i]=a.count()-i-1;
}
a.Update();
for(int u=0;u<a.num();u++){
for(int v=0;v<a.channels();v++){
for(int w=0;w<a.height();w++){
for(int x=0;x<a.width();x++){
cout<<"a["<<u<<"]["<<v<<"]["<<w<<"]["<<x<<"]="
<<a.data_at(u,v,w,x)<<endl;
}
}
}
}
BlobProto bp1;
a.ToProto(&bp1,true);
WriteProtoToBinaryFile(bp1,"a.blob");
BlobProto bp2;
ReadProtoFromBinaryFile("a.blob",&bp2);
Blob<float> b;
b.FromProto(bp2,true);
for(int u=0;u<b.num();u++){
for(int v=0;v<b.channels();v++){
for(int w=0;w<b.height();w++){
for(int x=0;x<b.width();x++){
cout<<"b["<<u<<"]["<<v<<"]["<<w<<"]["<<x<<"]="
<<b.data_at(u,v,w,x)<<endl;
}
}
}
}
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐