caffe源码中会出现不少explicit、inline关键字; 
C++中的explicit关键字的作用是禁止单参数构造函数的隐式转换,只能用于修饰只有一个参数的类构造函数, 它的作用是表明该构造函数是显示的, 而非隐式的;还有inline的作用,iniline主要是将代码进行复制,扩充,会使代码总量上升,好处就是可以节省调用的开销,能提高执行效率。

2.Blob

Caffe 使用 blobs 结构来存储、交换和处理网络中正向和反向迭代时的数据和导数信息: blob 是 Caffe 的标准数组结构,它提供了一个统一的内存接口。Blob 详细描述了信息是如何在 layer 和 net 中存储和交换的。同时它还隐含提供了在CPU和GPU之间同步数据的能力,从数学意义上说, blob 是按 C 风格连续存储的 N 维数组。 
对于批量图像数据来说, blob 常规的维数为图像数量 N 通道数 K 图像高度 H 图像宽度 W。 Blob 按行为主(row-major) 进行存储,所以一个 4 维 blob 中,坐标为(n, k, h, w)的值的物理位置为((n K + k) * H + h) * W + w,这也使得最后面/最右边的维度更新最快。

Blob是一个模板类,声明在include/caffe/blob.hpp中,封装了SyncedMemory类,作为计算单元服务Layer、Net、Sovler等;

主要成员变量

protected:shared_ptr<SyncedMemory> data_;// 存放数据shared_ptr<SyncedMemory> diff_;//存放梯度vector<int> shape_; //存放形状int count_; //数据个数int capacity_; //数据容量

BLob只是一个基本的数据结构,因此内部的变量相对较少,首先是data_指针,指针类型是shared_ptr,属于boost库的一个智能指针,这一部分主要用来申请内存存储data,data主要是正向传播的时候用的。同理,diff_主要用来存储偏差,update data,shape_data和shape_都是存储Blob的形状,一个是老版本一个是新版本。count表示Blob中的元素个数,也就是个数通道数高度*宽度,capacity表示当前的元素个数,因为Blob可能会reshape。

主要函数

template <typename Dtype>
class Blob {  public:  //blob的构造函数,不允许隐式的数据类型转换  Blob(): data_(), diff_(), count_(0), capacity_(0) {}  explicit Blob(const int num, const int channels, const int height,  const int width);  explicit Blob(const vector<int>& shape);  //几个Reshape函数,对blob的维度进行更改  void Reshape(const int num, const int channels, const int height, const int width);       // 用户的reshape接口(常用)  

其中Blob作为一个最基础的类,其中构造函数开辟一个内存空间来存储数据,Reshape函数在Layer中的reshape或者forward操作中来adjust dimension。同时在改变Blob大小时,内存将会被重新分配如果内存大小不够了,并且额外的内存将不会被释放。对input的blob进行reshape,如果立马调用Net::Backward是会出错的,因为reshape之后,要么Net::forward或者Net::Reshape就会被调用来将新的input shape 传播到高层。

Blob类里面还有重载很多个count()函数,主要还是为了统计Blob的容量(volume),或者是某一片(slice),从某个axis到具体某个axis的shape乘积。还有看意思也知道了,CHECK_GE肯定是在做比较Geater or Eqal这样的意思,是用来做比较的。这其实是GLOG,谷歌的一个日志库,Caffe里面用用了大量这样的宏,看起来也比较直观

inline int count(int start_axis, int end_axis) const {      // 返回特定维度区间的元素的个数  CHECK_LE(start_axis, end_axis); //保证start_axis <= end_axis CHECK_GE(start_axis, 0);        //保证start_axis >= 0CHECK_GE(end_axis, 0);          //保证end_axis >=0CHECK_LE(start_axis, num_axes());  //保证start_axis <= 总的维度数目CHECK_LE(end_axis, num_axes());  //end_axis  <= 总的维度数目int count = 1;  for (int i = start_axis; i < end_axis; ++i) {  count *= shape(i);  }  return count;  }  

并且Blob的Index是可以从负坐标开始读的,这一点跟Python好像

inline int CanonicalAxisIndex(int axis_index)

对于Blob中的4个基本变量num,channel,height,width可以直接通过shape(0),shape(1),shape(2),shape(3)来访问。

计算offset

inline int offset(const int n, const int c = 0, const int h = 0, const int w = 0)
inline int offset(const vector<int>& indices)

offset计算的方式也支持两种方式,一种直接指定n,c,h,w或者放到一个vector中进行计算,偏差是根据对应的n,c,h,w,返回的offset是((n * channels() + c) * height() + h) * width() + w

void CopyFrom(const Blob<Dtype>& source, bool copy_diff = false,bool reshape = false);

从一个blob中copy数据 ,通过开关控制是否copy_diff,如果是False则copy data。reshape控制是否需要reshape。好我们接着往下看

inline Dtype data_at(const int n, const int c, const int h, const int w)
inline Dtype diff_at(const int n, const int c, const int h, const int w)
inline Dtype data_at(const vector<int>& index)
inline Dtype diff_at(const vector<int>& index)
inline const shared_ptr<SyncedMemory>& data()
inline const shared_ptr<SyncedMemory>& diff()

这一部分函数主要通过给定的位置访问数据,根据位置计算与数据起始的偏差offset,在通过cpu_data*指针获得地址。下面几个函数都是获得

  const Dtype* cpu_data() const; //cpu使用的数据void set_cpu_data(Dtype* data);//用数据块的值来blob里面的data。const Dtype* gpu_data() const;//返回不可更改的指针,下同const Dtype* cpu_diff() const;const Dtype* gpu_diff() const;Dtype* mutable_cpu_data();//返回可更改的指针,下同Dtype* mutable_gpu_data();Dtype* mutable_cpu_diff();Dtype* mutable_gpu_diff();

Blob同时保存了data_和diff_,其类型为SyncedMemory的指针。 
对于data_(diff_相同),其实际值要么存储在CPU(cpu_ptr_)要么存储在GPU(gpu_ptr_),有两种方式访问CPU数据(GPU相同),因而有了这两种数据访问方式:静态方式,不改变数值;动态方式,改变数值。带mutable_开头的意味着可以对返回的指针内容进行更改,而不带mutable_开头的返回const 指针,不能对其指针的内容进行修改, 
之所以这么设计是因为 blob 使用了一个 SyncedMem 类来同步 CPU 和 GPU 上的数值,以隐藏同步的细节和最小化传送数据。一个经验准则是,如果不想改变数值,就一直使用常量调用,而且绝不要在自定义类中存储指针。 每次操作 blob 时, 调用相应的函数来获取它的指针,因为 SyncedMem 需要用这种方式来确定何时需要复制数据。 
实际上,使用 GPU 时, Caffe 中 CPU 代码先从磁盘中加载数据到 blob,同时请求分配一个 GPU 设备核(device kernel) 以使用 GPU 进行计算,再将计算好的 blob 数据送入下一层,这样既实现了高效运算,又忽略了底层细节。 只要所有 layers 均有 GPU 实现,这种情况下所有的中间数据和梯度都会保留在 GPU 上。 
这里有一个示例,用以确定 blob 何时会复制数据:

// 假定数据在 CPU 上进行初始化,我们有一个 blob
const Dtype* foo;
Dtype* bar;
foo = blob.gpu_data(); // 数据从 CPU 复制到 GPU
foo = blob.cpu_data(); // 没有数据复制,两者都有最新的内容
bar = blob.mutable_gpu_data(); // 没有数据复制
// ... 一些操作 ...
bar = blob.mutable_gpu_data(); // 仍在 GPU,没有数据复制
foo = blob.cpu_data(); // 由于 GPU 修改了数值,数据从 GPU 复制到 CPU
foo = blob.gpu_data(); //没有数据复制,两者都有最新的内容
bar = blob.mutable_cpu_data(); // 依旧没有数据复制
bar = blob.mutable_gpu_data(); //数据从 CPU 复制到 GPU
bar = blob.mutable_cpu_data(); //数据从 GPU 复制到 CPU

说明: 
1、经验上来说,如果不需要改变其值,则使用常量调用的方式,并且,不要在你对象中保存其指针。为何要这样设计呢,因为这样涉及能够隐藏CPU到GPU的同步细节,以及减少数据传递从而提高效率,当你调用它们的时候,SyncedMem会决定何时去复制数据,通常情况是仅当gnu或cpu修改后有复制操作,引用上述官方文档实例说明何时进行复制操作。 
2、调用mutable_cpu_data()可以让head转移到cpu上 
3、第一次调用mutable_cpu_data(),将为cpu_ptr_分配host内存 
4、若head从gpu转移到cpu,将把数据从gpu复制到cpu中

void Update();

update里面面调用了

caffe_axpy<float>(const int N, const float alpha, const float* X,float* Y)
{ cblas_saxpy(N, alpha, X, 1, Y, 1); }

这个函数在caffe的util下面的match-functions.cpp里面,主要是负责了线性代数库的调用,实现的功能是 
也就是blob里面的data部分减去diff部分 
可以参考http://blog.csdn.net/seven_first/article/details/47378697

大部分代码都有注释就不一一列举了

include/caffe/blob.hpp

*************************************************************************
#ifndef CAFFE_BLOB_HPP_
#define CAFFE_BLOB_HPP_
#include <algorithm>
#include <string>
#include <vector>
#include "caffe/common.hpp"
#include "caffe/proto/caffe.pb.h" //里面声明了Blobproto、Blobshape等遵循caffe.proto协议的数据结构
#include "caffe/syncedmem.hpp"    //CPU/GPU共享内存类,用于数据同步,很多实际的动作都在这里面执行
*************************************************************************
const int kMaxBlobAxes = 32;     //blob的最大维数目
namespace caffe {
template <typename Dtype>
class Blob {  public:  //blob的构造函数,不允许隐式的数据类型转换  Blob(): data_(), diff_(), count_(0), capacity_(0) {}  explicit Blob(const int num, const int channels, const int height,  const int width);  explicit Blob(const vector<int>& shape);  //几个Reshape函数,对blob的维度进行更改  void Reshape(const int num, const int channels, const int height, const int width);       // 用户的reshape接口(常用)  void Reshape(const vector<int>& shape);       // 通过重载调用真正的reshape函数  void Reshape(const BlobShape& shape);         // 用户的reshape接口  void ReshapeLike(const Blob& other);          // 用户的reshape接口  //获取Blob的形状字符串,用于打印log,比如: 10 3 256 512 (3932160),总元素个数    inline string shape_string() const {  ostringstream stream;  for (int i = 0; i < shape_.size(); ++i) {  stream << shape_[i] << " ";           //打印每一个维度信息  }  stream << "(" << count_ << ")";         //打印总的元素的个数  return stream.str();  }  inline const vector<int>& shape() const { return shape_; }  // 成员函数,返回blob的形状信息(常用)  inline int shape(int index) const {                         // 返回blob特定维度的大小(常用)  return shape_[CanonicalAxisIndex(index)];   }  inline int num_axes() const { return shape_.size(); }       // 返回blob维度  inline int count() const { return count_; }                 // 返回元素的个数  inline int count(int start_axis, int end_axis) const {      // 返回特定维度区间的元素的个数  CHECK_LE(start_axis, end_axis);  CHECK_GE(start_axis, 0);  CHECK_GE(end_axis, 0);  CHECK_LE(start_axis, num_axes());  CHECK_LE(end_axis, num_axes());  int count = 1;  for (int i = start_axis; i < end_axis; ++i) {  count *= shape(i);  }  return count;  }  inline int CanonicalAxisIndex(int axis_index) const {       // 检查输入的维度的合法性  CHECK_GE(axis_index, -num_axes())  << "axis " << axis_index << " out of range for " << num_axes()  << "-D Blob with shape " << shape_string();  CHECK_LT(axis_index, num_axes())  << "axis " << axis_index << " out of range for " << num_axes()  << "-D Blob with shape " << shape_string();  if (axis_index < 0) {  return axis_index + num_axes();  }  return axis_index;  }  inline int num() const { return LegacyShape(0); }           // 返回样本的个数(常用)  inline int channels() const { return LegacyShape(1); }      // 返回通道的个数(常用)  inline int height() const { return LegacyShape(2); }        // 返回样本维度一,对于图像而言是高度(常用)  inline int width() const { return LegacyShape(3); }         // 返回样本维度二,对于图像而言是宽度(常用)  //返回特定维度的大小,包含对输入维度的合法性检查,被上面函数调用  inline int LegacyShape(int index) const {       CHECK_LE(num_axes(), 4)  << "Cannot use legacy accessors on Blobs with > 4 axes.";  CHECK_LT(index, 4);  CHECK_GE(index, -4);  if (index >= num_axes() || index < -num_axes()) {  // Axis is out of range, but still in [0, 3] (or [-4, -1] for reverse  // indexing) -- this special case simulates the one-padding used to fill  // extraneous axes of legacy blobs.  return 1;  }  return shape(index);  }  // 计算当前的样本的偏移量,供后面序列化寻址使用  inline int offset(const int n, const int c = 0, const int h = 0,const int w = 0) const {  CHECK_GE(n, 0);  CHECK_LE(n, num());  CHECK_GE(channels(), 0);  CHECK_LE(c, channels());  CHECK_GE(height(), 0);  CHECK_LE(h, height());  CHECK_GE(width(), 0);  CHECK_LE(w, width());  return ((n * channels() + c) * height() + h) * width() + w;  }  inline int offset(const vector<int>& indices) const {  CHECK_LE(indices.size(), num_axes());  int offset = 0;  for (int i = 0; i < num_axes(); ++i) {  offset *= shape(i);  if (indices.size() > i) {  CHECK_GE(indices[i], 0);  CHECK_LT(indices[i], shape(i));  offset += indices[i];  }  }  return offset;  }  // 从其他的blob来拷贝到当前的blob中,默认是不拷贝梯度的,如果形状不一致需要使能reshape,不然无法拷贝  void CopyFrom(const Blob<Dtype>& source, bool copy_diff = false,  bool reshape = false);  // 返回特定位置的元素值  inline Dtype data_at(const int n, const int c, const int h,  const int w) const {  return cpu_data()[offset(n, c, h, w)];  }  // 返回特定位置的梯度值  inline Dtype diff_at(const int n, const int c, const int h,  const int w) const {  return cpu_diff()[offset(n, c, h, w)];     //这个是序列话的值  }  // 重载返回特定元素的值,作用与上面函数相同  inline Dtype data_at(const vector<int>& index) const {  return cpu_data()[offset(index)];  }  // 重载返回特定梯度的值,作用与上面函数相同  inline Dtype diff_at(const vector<int>& index) const {  return cpu_diff()[offset(index)];  }  // 返回当前的训练样本的数据(指针)(常用)  inline const shared_ptr<SyncedMemory>& data() const {  CHECK(data_);  return data_;  }  // 返回当前训练样本的梯度(指针)(常用)  inline const shared_ptr<SyncedMemory>& diff() const {  CHECK(diff_);  return diff_;  }  const Dtype* cpu_data() const;   // 只读获取cpu的data_的指针  void set_cpu_data(Dtype* data);  // 设置cpu的data_指针,修改指针仅  const int* gpu_shape() const;    // 只读获取gpu上数据的形状信息  const Dtype* gpu_data() const;   // 只读获取gpu上的data_的指针  const Dtype* cpu_diff() const;   // 只读获取cpu的diff_的指针  const Dtype* gpu_diff() const;   // 只读获取gpu的diff_的指针  Dtype* mutable_cpu_data();       // 读写访问cpu data  Dtype* mutable_gpu_data();       // 读写访问gpu data  Dtype* mutable_cpu_diff();       // 读写访问cpu diff  Dtype* mutable_gpu_diff();       // 读写访问cpu diff  void Update();                   // 数据更新,即减去当前计算出来的梯度  void FromProto(const BlobProto& proto, bool reshape = true);   // 将数据进行反序列化,从磁盘导入之前存储的blob  void ToProto(BlobProto* proto, bool write_diff = false) const; // 将数据进行序列化,便于存储  Dtype asum_data() const;         // 计算data的L1范数  Dtype asum_diff() const;         // 计算diff的L1范数  Dtype sumsq_data() const;        // 计算data的L2范数  Dtype sumsq_diff() const;        // 计算diff的L2范数  void scale_data(Dtype scale_factor);   // 按照一个标量进行伸缩data_  void scale_diff(Dtype scale_factor);   // 按照一个标量进行伸缩diff_  void ShareData(const Blob& other);     // 只是拷贝过来other的data  void ShareDiff(const Blob& other);     // 只是拷贝过来other的diff
//看名字就知道了一个是共享data,一个是共享diff,具体就是将别的blob的data和响应的diff指针给这个Blob,实现数据的共享。这个操作会引起这个Blob里面的SyncedMemory被释放,因为shared_ptr指针被用=重置的时候回调用响应的析构器bool ShapeEquals(const BlobProto& other);  // 判断两个blob的形状是否一致  protected:  shared_ptr<SyncedMemory> data_;            // 类的属性---数据  shared_ptr<SyncedMemory> diff_;            // 类的属性---梯度  shared_ptr<SyncedMemory> shape_data_;         vector<int> shape_;                        // 类的属性---形状信息  int count_;                                // 有效元素总的个数  int capacity_;                             // 存放bolb容器的容量信息,大于等于count_  DISABLE_COPY_AND_ASSIGN(Blob);
};  // class Blob  }  // namespace caffe  #endif  // CAFFE_BLOB_HPP_  

参考 
http://blog.csdn.net/leibaojiangjun1/article/details/53586700 
http://www.cnblogs.com/louyihang-loves-baiyan/p/5149628.html 
http://www.jianshu.com/p/0ac09c3ffec0 
Caffe官方教程中译本_CaffeCN社区翻译(caffecn.cn)

Caffe学习2:Blob相关推荐

  1. caffe学习日记--lesson5: VS下新建工程,探究Blob

    caffe学习日记--lesson5: VS下新建工程,探究Blob 在VS2013下新建工程,探究caffe的数据结构Blob,并使用.熟悉caffe 1.新建空白的控制台应用程序,添加main.c ...

  2. Caffe学习系列(17):模型各层特征和过滤器可视化

    转载自: Caffe学习系列(17):模型各层特征和过滤器可视化 - denny402 - 博客园 http://www.cnblogs.com/denny402/p/5105911.html cif ...

  3. Caffe学习笔记4图像特征进行可视化

    Caffe学习笔记4图像特征进行可视化 本文为原创作品,未经本人同意,禁止转载,禁止用于商业用途!本人对博客使用拥有最终解释权 欢迎关注我的博客:http://blog.csdn.net/hit201 ...

  4. Caffe 学习系列

    学习列表: Google protocol buffer在windows下的编译 caffe windows 学习第一步:编译和安装(vs2012+win 64) caffe windows学习:第一 ...

  5. Caffe学习笔记2--Ubuntu 14.04 64bit 安装Caffe(GPU版本)

    0.检查配置 1. VMWare上运行的Ubuntu,并不能支持真实的GPU(除了特定版本的VMWare和特定的GPU,要求条件严格,所以我在VMWare上搭建好了Caffe环境后,又重新在Windo ...

  6. 深度学习21天实战caffe学习笔记《3 :准备Caffe环境》

    准备Caffe环境 [如果是其他环境下的配置就请绕道喽,我也没有专门去试一试各个环境下的配置,请谅解~] 官网 http://caffe.berkeleyvision.org/installation ...

  7. caffe中loss函数代码分析--caffe学习(16)

    接上篇:caffe中样本的label一定要从序号0开始标注吗?–caffe学习(15) A: 1:数学上来说,损失函数loss值和label从0开始还是从1或者100开始是没有直接联系的,以欧式距离损 ...

  8. caffe学习(4)数据层

    数据是学习的原料,参考官网和网友的资料,来看一下数据与数据层. Data:Ins and Outs Caffe学习系列(2):数据层及参数,denny402 数据:输入与输出 在Caffe中,数据是以 ...

  9. Caffe学习笔记(二):Caffe前传与反传、损失函数、调优

    Caffe学习笔记(二):Caffe前传与反传.损失函数.调优 在caffe框架中,前传/反传(forward and backward)是一个网络中最重要的计算过程:损失函数(loss)是学习的驱动 ...

  10. caffe学习(9)LeNet在Caffe上的使用

    使用官网例程训练LeNet. Training LeNet on MNIST with Caffe 准备数据 Caffe程序的运行要注意需命令行要在Caffe的根目录下. cd $CAFFE_ROOT ...

最新文章

  1. 修改sms_def的MOF文件收集网络共享信息
  2. 016_泛型常见通配符
  3. 计算机视觉算法——目标检测网络总结
  4. 电脑手机wifi互传文件_手机之间怎么互传文件?几则小技巧了解下
  5. python定义一个圆类_(python)创建一个可以比较的自定义类
  6. cocos2d-x 学习资料(很全)
  7. 软件测试黑马程序员课后答案_软件测试教程课后答案
  8. C++开源矩阵计算工具——Eigen的简单用法(一)
  9. g2 折线图点与点之间直线_g2曲线图 每条曲线有单独的选中效果和tooltip
  10. mysql从一个表查询插入另一个表存在时更新_漫谈MySQL的锁机制
  11. RPG Maker MZ如何导入dlc素材?
  12. 中国裁判文书网爬虫分析
  13. c语言for死循环的作用,for循环死循环语句
  14. python中oserror_[python] 解决OSError: Address already in use
  15. 谈谈层次分析法和熵权法以及Topsis
  16. 简述利用PE系统破解Windows密码
  17. java字符串in.next_java中 nextString()怎么用
  18. 序列化-Kryo的使用详解
  19. C语言入门习题系列三(含答案)
  20. 透明遮罩图层VS高斯模糊滤镜 效果分析

热门文章

  1. 大数据架构方案总结-ljt(转载)
  2. Java基础知识2(字符串)
  3. LInux终端中Ctrl+S卡死
  4. Java多线程-新特征-锁(下)
  5. 学习笔记 : 表达式目录树相关问题参照该demo expression拼接与拆解 expression转sql...
  6. Mysql几种索引类型的区别及适用情况
  7. 新手指引,php什么是常量、变量、数组、类和对象及方法?
  8. 从头认识java-16.4 nio的读与写(ByteBuffer的使用)
  9. memcache使用方法测试 # 转自 简单--生活 #
  10. Java和JavaScript中使用Json方法大全