怎样移除OSXRESERVED分区(如果BootCamp Assistant在安装之后没有成功删除这个分区)

  1. 打开磁盘工具
  2. 点击主物理磁盘(不是下边的分区)
  3. 点击分区按钮
  4. When you see the pie chart, click on the OSXRESERVED partition in the pie chart
  5. 点击-标志
  6. click apply

Thats it!

DON'T use the ERASE Button in Disk Utility! That will cause problems and it won't reallocate space back.

2017/6/14 posted in  MAC OS

重新利用boot camp安装win10

由于原来给win10分的磁盘容量太小,而mac又不能在后续动态给win分区增加磁盘容量,所以只能重新安装分区了.

  1. 打开mac系统工具中的磁盘磁盘工具选择总的磁盘,点击上方的分区按钮,将系统中其它分区删掉(通过点击饼图中的对应区域,点击下方的-号),就可以将分区删掉,合并到mac系统磁盘.其他分区比如之前安装win产生的OSXRESERVED Partition
  2. 打开bootcamp,点击恢复按钮,将之前的win系统抹掉,之后就会发现,你的mac系统磁盘变回来了.
  3. 重启一下,之后打开bootcamp,点击下方的继续按钮,选择系统iso镜像,为win系统选择分区大小(这回分多些😓).
  4. 点击确定,等待下载Windows支持软件.
  5. 安装之后,在OSRESEVER分区中,的bootcamp文件夹中打开安装驱动的程序.

到此win10 应该就安装好了~

注意

由于apple公司更新了最新的文件系统APFS,导致bootcamp并没有很好的支持。现在,win下是不能识别到mac系统启动程序的。

2017/6/14 posted in  MAC OS

caffe数据结构描述

打开caffe目录下的src/caffe/proto/caffe.proto文件,首先讲的就是Blob的描述.

// 该结构描述了 Blob的形状信息
message BlobShape {
  repeated int64 dim = 1 [packed = true];  //只包括若干int64类型值,分别表示Blob每个维度的大小。packed表示这些值在内存中紧密排布,没有空洞
}

//该结构描述Blob在磁盘中序列化后的形态
message BlobProto {
  optional BlobShape shape = 7;    //可选,包括一个BlobShape对象
  repeated float data = 5 [packed = true]; // //包括若千浮点元素,存储数据或权值,元素数目由shape或(num, channels, height, width)确定,这些元素在内存中紧密排布.
  repeated float diff = 6 [packed = true];  ////包括若干浮点元素,用于存储增量信息,维度与data 数组一致
  repeated double double_data = 8 [packed = true];  // 与 data并列,只是类型为double
  repeated double double_diff = 9 [packed = true];  // 与 diff 并列,只是类型为 double

  // 4D dimensions -- deprecated.  Use "shape" instead.
  optional int32 num = 1 [default = 0];
  optional int32 channels = 2 [default = 0];
  optional int32 height = 3 [default = 0];
  optional int32 width = 4 [default = 0];
}

// The BlobProtoVector is simply a way to pass multiple blobproto instances
// around.
message BlobProtoVector {
  repeated BlobProto blobs = 1;
}

这里我们使用protobuffer主要是因为它具有很好的健壮性,将编程最容易出问题的地方加以隐藏,让机器自动处理.

Blob的构成

Blob是一个模板类,声明在include/caffe/blob.hpp中,里面封装了一些基本的Layer,Net,Solver等,还有syncedmem类:


#include <algorithm>
#include <string>
#include <vector>

#include "caffe/common.hpp"
#include "caffe/proto/caffe.pb.h"//由protoc生成的头文件,声明了 BlobProto、BlobShape等遵循caffe.proto协议的数据结构 可以在src/caffe/proto文件下运行protoc caffe.proto --cpp_out=./命令生成该头文件.
#include "caffe/syncedmem.hpp"  //CPU/GPU共享内存类,用于数据同步

const int kMaxBlobAxes = 32;    //Blob最大维数目
template <typename Dtype>
class Blob {    //类声明
 public:
    //默认构造函数
  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);

 //变形函数,报据输入参数重新设置当前Blob形状,必要时重新分配内存
  void Reshape(const int num, const int channels, const int height,
      const int width);
  
  void Reshape(const vector<int>& shape);
  void Reshape(const BlobShape& shape);
  void ReshapeLike(const Blob& other);
  //得到Blob形状字符串用于打印log,见Caffe运行log,类似"Top shape: 100 1 28 28 (78400)"
  inline string shape_string() const {
    ostringstream stream;
    for (int i = 0; i < shape_.size(); ++i) {
      stream << shape_[i] << " ";
    }
    stream << "(" << count_ << ")";
    return stream.str();
  }
  //返回Blob形状
  inline const vector<int>& shape() const { return shape_; }
    //返回某1维度的尺寸
  inline int shape(int index) const {
    return shape_[CanonicalAxisIndex(index)];
  }
  //返回维度数目
  inline int num_axes() const { return shape_.size(); }
  //返回Blob中元素总数
  inline int count() const { return count_; }
    //返回Blob中某几维子集的元素总数
    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 >= 0
    CHECK_GE(end_axis, 0);      // 保证 end_axis >= 0
    CHECK_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;
  }
  //计算从某一维度开始的元素总数
  inline int count(int start_axis) const {
    return count(start_axis, num_axes());
  }
  //转换坐标轴索引[-N,N)为普通索引[0,N)
  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) {
    //负索引表示从后向前访问,-1表示最后一个个元素,普通索引值为 N-1:同理,-2 => N-2, -3 => N-3,…
      return axis_index + num_axes();
    }
    return axis_index;
  }
  //获取某一维的尺寸
  /// @brief Deprecated legacy shape accessor num: use shape(0) instead.
  inline int num() const { return LegacyShape(0); }
  /// @brief Deprecated legacy shape accessor channels: use shape(1) instead.
  inline int channels() const { return LegacyShape(1); }
  /// @brief Deprecated legacy shape accessor height: use shape(2) instead.
  inline int height() const { return LegacyShape(2); }
  /// @brief Deprecated legacy shape accessor width: use shape(3) instead.
  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
  void CopyFrom(const Blob<Dtype>& source, bool copy_diff = false, bool reshape = false);
  
  //下面几个函数是存取器(getter/setter)
  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_;
  }
  
  //只读访问cpu_date
  const Dtype* cpu_data() const;
  //设置cpu_date
  void set_cpu_data(Dtype* data);
  const int* gpu_shape() const;
  //只读访问gpu_date
  const Dtype* gpu_data() const;
  //设置gpu_date
  void set_gpu_data(Dtype* data);
  //只读访问cpu_diff
  const Dtype* cpu_diff() const;
  //只读访问gpu_diff
  const Dtype* gpu_diff() const;
  //下面四个是读写访问数据
  Dtype* mutable_cpu_data();
  Dtype* mutable_gpu_data();
  Dtype* mutable_cpu_diff();
  Dtype* mutable_gpu_diff();
  void Update();    //Blob更新运算,可简单理解为data与diff的merge过程
  //反序列化函数,从BlobProto中恢复个Blob对象
  void FromProto(const BlobProto& proto, bool reshape = true);
  //序列化函数,将内存中的Blob对象保存到BlobProto中
  void ToProto(BlobProto* proto, bool write_diff = false) const;

  /// @brief Compute the sum of absolute values (L1 norm) of the data.
  Dtype asum_data() const;
  /// @brief Compute the sum of absolute values (L1 norm) of the diff.
  Dtype asum_diff() const;
  /// @brief Compute the sum of squares (L2 norm squared) of the data.
  Dtype sumsq_data() const;
  /// @brief Compute the sum of squares (L2 norm squared) of the diff.
  Dtype sumsq_diff() const;

/// @brief Scale the blob data by a constant factor.
  void scale_data(Dtype scale_factor);
  /// @brief Scale the blob diff by a constant factor.
  void scale_diff(Dtype scale_factor);
 // 共享另一个 Blob 的 diff
  void ShareData(const Blob& other);
  void ShareDiff(const Blob& other);
  
  protected:
  shared_ptr<SyncedMemory> data_;   //存放指向data的指针
  shared_ptr<SyncedMemory> diff_;   //存放指向diff的指针
  shared_ptr<SyncedMemory> shape_data_; 
  vector<int> shape_;   //形状信息
  int count_;   //存放有效元素数目信息
  int capacity_;    //存放Blob容器的容量信息

  DISABLE_COPY_AND_ASSIGN(Blob);    //禁用拷贝构造函数、陚值运算符重载
};  // class Blob

注意到Caffe类中成员变量名都带有后缀,这样在函数实现中容易区分临时变量和类成员变量。

打幵include/caffe/syncedmem.hpp,査看该类的用法:

#ifndef CAFFE_SYNCEDMEM_HPP_
#define CAFFE_SYNCEDMEM_HPP_

#include <cstdlib>

#ifdef USE_MKL
  #include "mkl.h"
#endif

#include "caffe/common.hpp"

namespace caffe {

//如果在GPU模式,且CUDA使能,那么主机内存会以页锁定内存方式分配(使用cudaMallocHostU函数。对f-单GPU的性能提升不明显,但多GPU会非常明显)
inline void CaffeMallocHost(void** ptr, size_t size, bool* use_cuda) {
#ifndef CPU_ONLY
  if (Caffe::mode() == Caffe::GPU) {
    CUDA_CHECK(cudaMallocHost(ptr, size));
    *use_cuda = true;
    return;
  }
#endif
#ifdef USE_MKL
  *ptr = mkl_malloc(size ? size:1, 64);
#else
  *ptr = malloc(size);
#endif
  *use_cuda = false;
  CHECK(*ptr) << "host allocation of size " << size << " failed";
}
// 与CaffeMallocHost对应
inline void CaffeFreeHost(void* ptr, bool use_cuda) {
#ifndef CPU_ONLY
  if (use_cuda) {
    CUDA_CHECK(cudaFreeHost(ptr));
    return;
  }
#endif
#ifdef USE_MKL
  mkl_free(ptr);
#else
  free(ptr);
#endif
}

//该类负责存储分配以及主机和设备间同步
class SyncedMemory {
 public:
 //构造函数
  SyncedMemory();
  //显式构造函数
  explicit SyncedMemory(size_t size);
  //析构函数
  ~SyncedMemory();
  const void* cpu_data();       //只读获取cpu data
  void set_cpu_data(void* data);    //设置cpu data
  const void* gpu_data();       //只读获取gpu data
  void set_gpu_data(void* data);    //设置gpu data
  void* mutable_cpu_data();     // 读写获取 cpu data
  void* mutable_gpu_data();     // 读写获取 gpu data
  //状态机变量,表示4种状态:术初始化、CPU数据奋效、GPU数据有效、己同步
  enum SyncedHead { UNINITIALIZED, HEAD_AT_CPU, HEAD_AT_GPU, SYNCED };
  //获得当前状态机变量值
  SyncedHead head() { return head_; }
  //获得当前存储空间尺寸
  size_t size() { return size_; }

#ifndef CPU_ONLY
  void async_gpu_push(const cudaStream_t& stream);
#endif

 private:
  void check_device();

  void to_cpu();    //数据同步至CPU
  void to_gpu();    //数据同步至GPU
  void* cpu_ptr_;   //位于CPU的数据指针
  void* gpu_ptr_;   //位于GPU的数据指针
  size_t size_;     //存储空间大小
  SyncedHead head_; //状态机变量
  bool own_cpu_data_;   //标志是否拥有CPU数据所有权(否,即从别的对象共享)
  bool cpu_malloc_use_cuda_;
  bool own_gpu_data_;   ////标志是否拥有GPU数据所有权
  int device_;      //设备号

  DISABLE_COPY_AND_ASSIGN(SyncedMemory);
};  // class SyncedMemory

}  // namespace caffe

#endif  // CAFFE_SYNCEDMEM_HPP_

Blob类实现的源码位于src/caffe/blob.cpp中,内容如下:


#include <climits>
#include <vector>

#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/syncedmem.hpp"
#include "caffe/util/math_functions.hpp"

namespace caffe {
//变维函数,将(num, channels, height, width}参数转换为vector<int>,然后调用重载的变维函数void Blob<Dtype>::Reshape(const BlobShape& shape)
template <typename Dtype>
void Blob<Dtype>::Reshape(const int num, const int channels, const int height,
    const int width) {
  vector<int> shape(4);
  shape[0] = num;
  shape[1] = channels;
  shape[2] = height;
  shape[3] = width;
  Reshape(shape);
}
//真正变维函数
template <typename Dtype>
void Blob<Dtype>::Reshape(const vector<int>& shape) {
  CHECK_LE(shape.size(), kMaxBlobAxes); //保证vector维度<=kMaxBlobAxes
  count_ = 1;   //用于计算元素总数=num * channels * height * width 
  shape_.resize(shape.size());  //成员变量维度也被重罝
  if (!shape_data_ || shape_data_->size() < shape.size() * sizeof(int)) {
    shape_data_.reset(new SyncedMemory(shape.size() * sizeof(int)));
  }
  int* shape_data = static_cast<int*>(shape_data_->mutable_cpu_data());
  for (int i = 0; i < shape.size(); ++i) {
    CHECK_GE(shape[i], 0);  // 保证每维度尺寸都>=0
    if (count_ != 0) {
    //证count_不溢出
      CHECK_LE(shape[i], INT_MAX / count_) << "blob size exceeds INT_MAX";
    }
    count_ *= shape[i];     //count_累乘
    shape_[i] = shape[i];   //为成员变量赋值
    shape_data[i] = shape[i];
  }
  if (count_ > capacity_) {     //如果新的count_大于当前己分f配空间容量
    capacity_ = count_;         //扩容,重新分配data_和dif f_空间
    data_.reset(new SyncedMemory(capacity_ * sizeof(Dtype)));
    diff_.reset(new SyncedMemory(capacity_ * sizeof(Dtype)));
  }
}

//void Blob<Dtype>::Reshape(const BlobShape& shape) 和void Blob<Dtype>::ReshapeLike(const Blob<Dtype>& other)与上面类似. 

//构造函数
template <typename Dtype>
Blob<Dtype>::Blob(const int num, const int channels, const int height,
    const int width)
  // 调用Reshape之前必须初始化capacity_,否则会导致不可预期结果
  : capacity_(0) {
  Reshape(num, channels, height, width);
}

template <typename Dtype>
Blob<Dtype>::Blob(const vector<int>& shape)
  // capacity_ must be initialized before calling Reshape
  : capacity_(0) {
  Reshape(shape);
}

template <typename Dtype>
const int* Blob<Dtype>::gpu_shape() const {
  CHECK(shape_data_);
  return (const int*)shape_data_->gpu_data();
}
//只读获取cpu date指针
template <typename Dtype>
const Dtype* Blob<Dtype>::cpu_data() const {
  CHECK(data_);     //保证data_不为 NULL
  return (const Dtype*)data_->cpu_data();
}
//修改cpu data指针
template <typename Dtype>
void Blob<Dtype>::set_cpu_data(Dtype* data) {
  CHECK(data);
  // Make sure CPU and GPU sizes remain equal
  size_t size = count_ * sizeof(Dtype);
  if (data_->size() != size) {
    data_.reset(new SyncedMemory(size));
    diff_.reset(new SyncedMemory(size));
  }
  data_->set_cpu_data(data);
}

template <typename Dtype>
const Dtype* Blob<Dtype>::gpu_data() const {
  CHECK(data_);
  return (const Dtype*)data_->gpu_data();
}

template <typename Dtype>
void Blob<Dtype>::set_gpu_data(Dtype* data) {
  CHECK(data);
  // Make sure CPU and GPU sizes remain equal
  size_t size = count_ * sizeof(Dtype);
  if (data_->size() != size) {
    data_.reset(new SyncedMemory(size));
    diff_.reset(new SyncedMemory(size));
  }
  data_->set_gpu_data(data);
}
//只读获取cpu_diff指针
template <typename Dtype>
const Dtype* Blob<Dtype>::cpu_diff() const {
  CHECK(diff_);
  return (const Dtype*)diff_->cpu_data();
}
//只读获取gpu_diff指针
template <typename Dtype>
const Dtype* Blob<Dtype>::gpu_diff() const {
  CHECK(diff_);
  return (const Dtype*)diff_->gpu_data();
}
//读写访问cpu data指针
template <typename Dtype>
Dtype* Blob<Dtype>::mutable_cpu_data() {
  CHECK(data_);
  return static_cast<Dtype*>(data_->mutable_cpu_data());
}
//读写访问gpu data指针
template <typename Dtype>
Dtype* Blob<Dtype>::mutable_gpu_data() {
  CHECK(data_);
  return static_cast<Dtype*>(data_->mutable_gpu_data());
}
//与上面相同
template <typename Dtype>
Dtype* Blob<Dtype>::mutable_cpu_diff() {
  CHECK(diff_);
  return static_cast<Dtype*>(diff_->mutable_cpu_data());
}

template <typename Dtype>
Dtype* Blob<Dtype>::mutable_gpu_diff() {
  CHECK(diff_);
  return static_cast<Dtype*>(diff_->mutable_gpu_data());
}
//共享另一个Blob的data指针
template <typename Dtype>
void Blob<Dtype>::ShareData(const Blob& other) {
  CHECK_EQ(count_, other.count());
  data_ = other.data();
}
//共享另一个Blob的diff指针
template <typename Dtype>
void Blob<Dtype>::ShareDiff(const Blob& other) {
  CHECK_EQ(count_, other.count());
  diff_ = other.diff();
}
//Update()函数用于网络参数Blob的更新。其中int和unsigned int类型处理并未实现
template <> void Blob<unsigned int>::Update() { NOT_IMPLEMENTED; }
template <> void Blob<int>::Update() { NOT_IMPLEMENTED; }
template <typename Dtype>
void Blob<Dtype>::Update() {
  // We will perform update based on where the data is located.data在哪里我们就在那里更新
  switch (data_->head()) {
  case SyncedMemory::HEAD_AT_CPU:       //data位于cpu端
    // 执行CPU计算
        caffe_axpy<Dtype>(count_, Dtype(-1),
        static_cast<const Dtype*>(diff_->cpu_data()),
        static_cast<Dtype*>(data_->mutable_cpu_data()));
    break;
  case SyncedMemory::HEAD_AT_GPU:   //data位于GPU端,或者CPU/GPU已经同步
  case SyncedMemory::SYNCED:
#ifndef CPU_ONLY
    // 执行 CPU 上的计算,data_[i】=data_[i] - diff_[i], i = 0,1,2,…,count_-1
    caffe_gpu_axpy<Dtype>(count_, Dtype(-1),
        static_cast<const Dtype*>(diff_->gpu_data()),
        static_cast<Dtype*>(data_->mutable_gpu_data()));
#else
    NO_GPU;     //编泽时打开了CPU_ONLY选项,那么GPU模式禁用
#endif
    break;
  default:
    LOG(FATAL) << "Syncedmem not initialized.";
  }
}
//计算data_的L1-范数,其中int和unsigned int类型处理并未实现
template <> unsigned int Blob<unsigned int>::asum_data() const {
  NOT_IMPLEMENTED;
  return 0;
}
template <> int Blob<int>::asum_data() const {
  NOT_IMPLEMENTED;
  return 0;
}

template <typename Dtype>
Dtype Blob<Dtype>::asum_data() const {
  if (!data_) { return 0; }
  switch (data_->head()) {
  case SyncedMemory::HEAD_AT_CPU:
    return caffe_cpu_asum(count_, cpu_data());  //执行CPU上的asum计算
  case SyncedMemory::HEAD_AT_GPU:
  case SyncedMemory::SYNCED:
#ifndef CPU_ONLY
  {
    Dtype asum;
    caffe_gpu_asum(count_, gpu_data(), &asum);
    return asum;
  }
#else
    NO_GPU;
#endif
  case SyncedMemory::UNINITIALIZED:
    return 0;
  default:
    LOG(FATAL) << "Unknown SyncedMemory head state: " << data_->head();
  }
  return 0;
}

template <> unsigned int Blob<unsigned int>::asum_diff() const {
  NOT_IMPLEMENTED;
  return 0;
}

template <> int Blob<int>::asum_diff() const {
  NOT_IMPLEMENTED;
  return 0;
}
//同上,计算diff_的L1范数
template <typename Dtype>
Dtype Blob<Dtype>::asum_diff() const {
  if (!diff_) { return 0; }
  switch (diff_->head()) {
  case SyncedMemory::HEAD_AT_CPU:
    return caffe_cpu_asum(count_, cpu_diff());
  case SyncedMemory::HEAD_AT_GPU:
  case SyncedMemory::SYNCED:
#ifndef CPU_ONLY
  {
    Dtype asum;
    caffe_gpu_asum(count_, gpu_diff(), &asum);
    return asum;
  }
#else
    NO_GPU;
#endif
  case SyncedMemory::UNINITIALIZED:
    return 0;
  default:
    LOG(FATAL) << "Unknown SyncedMemory head state: " << diff_->head();
  }
  return 0;
}
//计算data_的L2-范数
template <> unsigned int Blob<unsigned int>::sumsq_data() const {
  NOT_IMPLEMENTED;
  return 0;
}
template <> int Blob<int>::sumsq_data() const {
  NOT_IMPLEMENTED;
  return 0;
}

template <typename Dtype>
Dtype Blob<Dtype>::sumsq_data() const {
  Dtype sumsq;
  const Dtype* data;
  if (!data_) { return 0; }
  switch (data_->head()) {
  case SyncedMemory::HEAD_AT_CPU:
    data = cpu_data();
    sumsq = caffe_cpu_dot(count_, data, data);  //执行 CPU上的dot计算
    break;
  case SyncedMemory::HEAD_AT_GPU:
  case SyncedMemory::SYNCED:
#ifndef CPU_ONLY
    data = gpu_data();
    caffe_gpu_dot(count_, data, data, &sumsq);
#else
    NO_GPU;
#endif
    break;
  case SyncedMemory::UNINITIALIZED:
    return 0;
  default:
    LOG(FATAL) << "Unknown SyncedMemory head state: " << data_->head();
  }
  return sumsq;
}
//同上,计算diff_的L2-范数
template <> unsigned int Blob<unsigned int>::sumsq_diff() const {
  NOT_IMPLEMENTED;
  return 0;
}
template <> int Blob<int>::sumsq_diff() const {
  NOT_IMPLEMENTED;
  return 0;
}
template <typename Dtype>
Dtype Blob<Dtype>::sumsq_diff() const {
  Dtype sumsq;
  const Dtype* diff;
  if (!diff_) { return 0; }
  switch (diff_->head()) {
  case SyncedMemory::HEAD_AT_CPU:
    diff = cpu_diff();
    sumsq = caffe_cpu_dot(count_, diff, diff);
    break;
  case SyncedMemory::HEAD_AT_GPU:
  case SyncedMemory::SYNCED:
#ifndef CPU_ONLY
    diff = gpu_diff();
    caffe_gpu_dot(count_, diff, diff, &sumsq);
    break;
#else
    NO_GPU;
#endif
  case SyncedMemory::UNINITIALIZED:
    return 0;
  default:
    LOG(FATAL) << "Unknown SyncedMemory head state: " << data_->head();
  }
  return sumsq;
}
//对data_进行幅度缩放
template <> void Blob<unsigned int>::scale_data(unsigned int scale_factor) {
  NOT_IMPLEMENTED;
}

template <> void Blob<int>::scale_data(int scale_factor) {
  NOT_IMPLEMENTED;
}

template <typename Dtype>
void Blob<Dtype>::scale_data(Dtype scale_factor) {
  Dtype* data;
  if (!data_) { return; }
  switch (data_->head()) {
  case SyncedMemory::HEAD_AT_CPU:   //执行CPU上的计算
    data = mutable_cpu_data();
    caffe_scal(count_, scale_factor, data);
    return;
  case SyncedMemory::HEAD_AT_GPU:
  case SyncedMemory::SYNCED:
#ifndef CPU_ONLY
    data = mutable_gpu_data();
    caffe_gpu_scal(count_, scale_factor, data);
    return;
#else
    NO_GPU;
#endif
  case SyncedMemory::UNINITIALIZED:
    return;
  default:
    LOG(FATAL) << "Unknown SyncedMemory head state: " << data_->head();
  }
}

template <> void Blob<unsigned int>::scale_diff(unsigned int scale_factor) {
  NOT_IMPLEMENTED;
}

template <> void Blob<int>::scale_diff(int scale_factor) {
  NOT_IMPLEMENTED;
}
//对diff_进行缩放,同理
template <typename Dtype>
void Blob<Dtype>::scale_diff(Dtype scale_factor) {
  Dtype* diff;
  if (!diff_) { return; }
  switch (diff_->head()) {
  case SyncedMemory::HEAD_AT_CPU:
    diff = mutable_cpu_diff();
    caffe_scal(count_, scale_factor, diff);
    return;
  case SyncedMemory::HEAD_AT_GPU:
  case SyncedMemory::SYNCED:
#ifndef CPU_ONLY
    diff = mutable_gpu_diff();
    caffe_gpu_scal(count_, scale_factor, diff);
    return;
#else
    NO_GPU;
#endif
  case SyncedMemory::UNINITIALIZED:
    return;
  default:
    LOG(FATAL) << "Unknown SyncedMemory head state: " << diff_->head();
  }
}
//判断形状是否相同
template <typename Dtype>
bool Blob<Dtype>::ShapeEquals(const BlobProto& other) {
  if (other.has_num() || other.has_channels() ||
      other.has_height() || other.has_width()) {
    // Using deprecated 4D Blob dimensions --
    // shape is (num, channels, height, width).
    // Note: we do not use the normal Blob::num(), Blob::channels(), etc.
    // methods as these index from the beginning of the blob shape, where legacy parameter blobs were indexed from the end of the blob shape (e.g., bias Blob shape (1 x 1 x 1 x N), IP layer weight Blob shape (1 x 1 x M x N)).
    //输入的维度若使用过时的维度信息(num, channels,height, width),则需要转换为新的vector参数,代码使用了C++中的“懒”逻辑
    return shape_.size() <= 4 &&
           LegacyShape(-4) == other.num() &&
           LegacyShape(-3) == other.channels() &&
           LegacyShape(-2) == other.height() &&
           LegacyShape(-1) == other.width();
  }
  //直接对比
  vector<int> other_shape(other.shape().dim_size());
  for (int i = 0; i < other.shape().dim_size(); ++i) {
    other_shape[i] = other.shape().dim(i);
  }
  return shape_ == other_shape;
}
//从另一个Blob对象拷贝data (可选diff),必要时进行变维
template <typename Dtype>
void Blob<Dtype>::CopyFrom(const Blob& source, bool copy_diff, bool reshape) {
  if (source.count() != count_ || source.shape() != shape_) {
    if (reshape) {
      ReshapeLike(source);      //如果要变维,则执行这个
    } else {    //两个blob形状不同,则报错
      LOG(FATAL) << "Trying to copy blobs of different sizes.";
    }
  }
  switch (Caffe::mode()) {
  case Caffe::GPU:      //GPU模式
    if (copy_diff) {
      caffe_copy(count_, source.gpu_diff(),
          static_cast<Dtype*>(diff_->mutable_gpu_data()));
    } else {
      caffe_copy(count_, source.gpu_data(),
          static_cast<Dtype*>(data_->mutable_gpu_data()));
    }
    break;
  case Caffe::CPU:      //CPU模式
    if (copy_diff) {
      caffe_copy(count_, source.cpu_diff(),
          static_cast<Dtype*>(diff_->mutable_cpu_data()));
    } else {
      caffe_copy(count_, source.cpu_data(),
          static_cast<Dtype*>(data_->mutable_cpu_data()));
    }
    break;
  default:
    LOG(FATAL) << "Unknown caffe mode.";
  }
}

//从BlobProto中加载一个Blob,适用于从磁盘载入之前导出的Blob
template <typename Dtype>
void Blob<Dtype>::FromProto(const BlobProto& proto, bool reshape) {
  if (reshape) {        //从BlobProto对象中获得所需各个维度信息
    vector<int> shape;
    if (proto.has_num() || proto.has_channels() ||
        proto.has_height() || proto.has_width()) {
      // Using deprecated 4D Blob dimensions --
      // shape is (num, channels, height, width).
      shape.resize(4);
      shape[0] = proto.num();
      shape[1] = proto.channels();
      shape[2] = proto.height();
      shape[3] = proto.width();
    } else {
      shape.resize(proto.shape().dim_size());
      for (int i = 0; i < proto.shape().dim_size(); ++i) {
        shape[i] = proto.shape().dim(i);
      }
    }
    Reshape(shape);     //Blob按照维度信息进行变维
  } else {
    CHECK(ShapeEquals(proto)) << "shape mismatch (reshape not set)";
  }
  // copy data 加载数据
  Dtype* data_vec = mutable_cpu_data();
  if (proto.double_data_size() > 0) {   // 如果之前保存的是double类型 data
    CHECK_EQ(count_, proto.double_data_size());
    for (int i = 0; i < count_; ++i) {
      data_vec[i] = proto.double_data(i);   //加载double date
    }
  } else {
    CHECK_EQ(count_, proto.data_size());
    for (int i = 0; i < count_; ++i) {
      data_vec[i] = proto.data(i);  //否则加载float data
    }
  }
  if (proto.double_diff_size() > 0) {   // 如果之前保存的是 double 类型 diff
    CHECK_EQ(count_, proto.double_diff_size());
    Dtype* diff_vec = mutable_cpu_diff();
    for (int i = 0; i < count_; ++i) {
      diff_vec[i] = proto.double_diff(i);
    }
  } else if (proto.diff_size() > 0) {
    CHECK_EQ(count_, proto.diff_size());
    Dtype* diff_vec = mutable_cpu_diff();
    for (int i = 0; i < count_; ++i) {
      diff_vec[i] = proto.diff(i);
    }
  }
}
//将Blob中的data(可选diff)导出到BlobProto结构体.便于存储到磁盘文件中
template <>
void Blob<double>::ToProto(BlobProto* proto, bool write_diff) const {
  proto->clear_shape();     //重置proto的维度,保证与blob相同
  for (int i = 0; i < shape_.size(); ++i) {
    proto->mutable_shape()->add_dim(shape_[i]);
  }
  proto->clear_double_data();   //清除data
  proto->clear_double_diff();   //清除diff
  const double* data_vec = cpu_data();  //将data导出到proto
  for (int i = 0; i < count_; ++i) {
    proto->add_double_data(data_vec[i]);
  }
  if (write_diff) {         //  若有write_diff的需求
    const double* diff_vec = cpu_diff();    //将diff导出到proto
    for (int i = 0; i < count_; ++i) {
      proto->add_double_diff(diff_vec[i]);
    }
  }
}
//同上,只不过类型为float
template <>
void Blob<float>::ToProto(BlobProto* proto, bool write_diff) const {
  proto->clear_shape();
  for (int i = 0; i < shape_.size(); ++i) {
    proto->mutable_shape()->add_dim(shape_[i]);
  }
  proto->clear_data();
  proto->clear_diff();
  const float* data_vec = cpu_data();
  for (int i = 0; i < count_; ++i) {
    proto->add_data(data_vec[i]);
  }
  if (write_diff) {
    const float* diff_vec = cpu_diff();
    for (int i = 0; i < count_; ++i) {
      proto->add_diff(diff_vec[i]);
    }
  }
}
//实例化Blob   类模板(float, double)
INSTANTIATE_CLASS(Blob);
template class Blob<int>;
template class Blob<unsigned int>;

}  // namespace caffe

到此,我们就了解了Caffe一些基本的数据结构.后面就应该学习Layer层中对数据的一些处理.

2017/6/10 posted in  Caffe 数据结构

caffe数据结构

一个CNN网络是由多个Layer堆叠而成的.如图所示:

caffe按照我们设计的图纸(prototxt),用Blob这些砖块建成一层层(Layer)楼房,最后通过方法SGD方法(Solver)进行简装修(Train),精装修(Finetune)实现的.我们这里就是学习这些基本概念.

Blob

Caffe使用称为Blob的4维数组用于存储和交换数据.Blob提供了统一的存储器接口,持有一批图像或其它数据,权值,权值更新值. 其它机器学习框架也有类似的数据结构.

Blob在内存中为4维数组,分别为(width_,height_,channels_,num_),width_和height_表示图像的宽和高,channel_表示颜色通道RGB,num_表示第几帧,用于存储数据或权值(data)和权值增量(diff),在进行网路计算时,每层的输入,输出都需要Blob对象缓冲.Blob是Caffe的基本存储单元.

Blob的基本用法

Blob是一个模板类,所以创建对象时需要制定模板参数.我们这里写一个简单的测试程序blob_demo.cpp将它放在caffe的安装目录下:

#include<vector>
#include<iostream>
#include<caffe/blob.hpp>
using namespace caffe;
using namespace std;
int main(void)
{
    Blob<float> a;
    cout<<"Size:"<<a.shape_string()<<endl;
    a.Reshape(1,2,3,4);
    cout<<"Size:"<<a.shape_string()<<endl;
    return 0;
}

上面代码首先创建了整型Blob对象a,打印其维度信息,然后调用其Reshape()方法,再次打印其维度信息.

使用如下命令来编译上面的文件.

g++ -o app blob_demo.cpp -I /usr/local/Cellar/caffe/include/ -D CPU_ONLY -I /usr/local/Cellar/caffe/.build_release/src/ -L /usr/local/Cellar/caffe/.build_release/lib/ -lcaffe

生成了可执行程序app

这个时候运行app的话可能会遇到下面这个错误:

这个因为app没有链接到这个动态库文件,执行下边这个命令链接:

install_name_tool -add_rpath '/usr/local/Cellar/caffe/build/lib/'  /usr/local/Cellar/caffe/./app

/usr/local/Cellar/caffe/build/lib/@rpath/libcaffe.so.1.0.0动态库的路径.

执行后,再次运行会遇到错误:

与上面类似,这是因为没有链接到@rpath/libhdf5_hl.10.dylib
执行下面这个命令:

install_name_tool -add_rpath '/Users/liangzhonghao/anaconda2/lib'  /usr/local/Cellar/caffe/build/lib/libcaffe.so.1.0.0

其中/Users/liangzhonghao/anaconda2/lib包含这个库文件.

再次执行app,终于成功了!

创建了Blob对象之后,我们可以通过mutable_cpu[gpu]_data[diff]函数来修改其内部数值:

代码为:

#include<vector>
#include<iostream>
#include<caffe/blob.hpp>
using namespace caffe;
using namespace std;
int main(void)
{
    Blob<float> a;
    cout<<"Size:"<<a.shape_string()<<endl;
    a.Reshape(1,2,3,4);
    cout<<"Size:"<<a.shape_string()<<endl;
    
    float *p=a.mutable_cpu_data();
    for(int i=0;i<a.count();i++){
        p[i]=i;
    }
    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<<"]["<<w<<"]["<<x<<"]="<<a.data_at(u,v,w,x)<<endl;
                }
            }
        }
    }
    return 0;
}

跟上面一样继续编译和执行,这里按照上面的命令继续来编译的话,遇到了一个错误:

之后换成下边的命令执行后成功:

g++ -o app2 blob_demo.cpp -I /usr/local/Cellar/caffe/include/ -D CPU_ONLY -I /usr/local/Cellar/caffe/.build_release/src/ -L /usr/local/Cellar/caffe/.build_release/lib/ -lcaffe -lglog -lboost_system -lprotobuf

差别在于,后边加上了-lglog -lboost_system -lprotobuf命令,具体作用后续将研究(暂时不理解),继续运行后,又出现了错误:

同样是动态库的连接问题:
运行命令:

install_name_tool -add_rpath '/usr/local/Cellar/caffe/build/lib/'  /usr/local/Cellar/caffe/./app2

执行命令,然后运行app2.得到输出:

可见,Blob下标的访问与c/c++高维数组几乎一致,而Blob好处在于可以直接同步CPU/GPU上的数据.

Blob还支持计算所有元素的绝对值之和(L1-范数),平方和(L2-范数):

cout<<"ASUM = "<<a.asum_data()<<endl;
cout<<"SUMSQ = "<<a.sumsq_data()<<endl;

输出结果为:

ASUM = 276
SUMSQ = 4324

除了data,我们还可以改diff部分,与data的操作基本一致:

#include<vector>
#include<iostream>
#include<caffe/blob.hpp>
using namespace caffe;
using namespace std;
int main(void)
{
    Blob<float> a;
    cout<<"Size:"<<a.shape_string()<<endl;
    a.Reshape(1,2,3,4);
    cout<<"Size:"<<a.shape_string()<<endl;
    
    float *p=a.mutable_cpu_data();
    float *q=a.mutable_cpu_diff();
    
    for(int i=0;i<a.count();i++){
        p[i]= i;     //将data初始化为1,2,3....
        q[i]= a.count()-1-i;   //将diff初始化为23,22,21,...
    }
    
    a.Update();         //执行update操作,将diff与data融合,这也是CNN权值更新步骤的最终实施者
   
    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<<"]["<<w<<"]["<<x<<"]="<<a.data_at(u,v,w,x)<<endl;
                }
            }
        }
    }
    
    cout<<"ASUM = "<<a.asum_data()<<endl;
    cout<<"SUMSQ = "<<a.sumsq_data()<<endl;
    
    return 0;
}

然后执行以下命令编译,链接库文件:

g++ -o app blob_demo_diff.cpp -I /usr/local/Cellar/caffe/include/ -D CPU_ONLY -I /usr/local/Cellar/caffe/.build_release/src/ -L /usr/local/Cellar/caffe/.build_release/lib/ -lcaffe  -lglog -lboost_system -lprotobuf

install_name_tool -add_rpath '/usr/local/Cellar/caffe/build/lib/'  /usr/local/Cellar/caffe/LZHcaffe/./app

运行.app,结果为:

上面表明,在Update()函数中,实现了data = data -diff操作,这个主要是在CNN权值更新时会用到,后面继续学习.

将Blob内部值保存到硬盘,或者冲硬盘载入到内存,可以分别通过ToProto(),FromProto()实现:


#include<vector>
#include<iostream>
#include<caffe/blob.hpp>
#include<caffe/util/io.hpp>   //需要包含这个头文件
using namespace caffe;
using namespace std;
int main(void)
{
    Blob<float> a;
    cout<<"Size:"<<a.shape_string()<<endl;
    a.Reshape(1,2,3,4);
    cout<<"Size:"<<a.shape_string()<<endl;
    
    float *p=a.mutable_cpu_data();
    float *q=a.mutable_cpu_diff();
    
    for(int i=0;i<a.count();i++){
        p[i]= i;     //将data初始化为1,2,3....
        q[i]= a.count()-1-i;   //将diff初始化为23,22,21,...
    }
    
    a.Update();         //执行update操作,将diff与data融合,这也是CNN权值更新步骤的最终实施者
   
    BlobProto bp;          //构造一个BlobProto对象
    a.ToProto(&bp,true);    //将a序列化,连同diff(默认不带)
    WriteProtoToBinaryFile(bp,"a.blob");     //写入磁盘文件"a.blob"
    BlobProto bp2;           //构造一个新的BlobProto对象
    ReadProtoFromBinaryFileOrDie("a.blob",&bp2);    //读取磁盘文件
    Blob<float> b;          //新建一个Blob对象b
    b.FromProto(bp2,true);  //从序列化对象bp2中克隆b(连同形状)
    
    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<<"]["<<w<<"]["<<x<<"]="<<b.data_at(u,v,w,x)<<endl;
                }
            }
        }
    }
    
    cout<<"ASUM = "<<b.asum_data()<<endl;
    cout<<"SUMSQ = "<<b.sumsq_data()<<endl;
    
    
    return 0;
}

编译,连接库文件后(注意编译时末尾加入"-lglog -lboost_system -lprotobuf"选项),输出如下:

可以发现与上面没有差别,只是在文件夹中多了一个Blob.a文件,所以BlobProto对象实现了硬盘与内存之间的数据通信.可以帮助保存中间权值和数据

2017/6/9 posted in  caffe框架学习

激活函数

深度神经网络之所以具有丰富的表达能力,除了有深层次的网络之外,还有一个重要因素即非线性处理单元,称为激活函数(Activation Function)或挤压函数(Squashing Function).所以我们必须要关注怎么在caffe中实现这些函数.

下图是一个神经元模型.\(\varphi(.)\)为激活函数.主要作用是将上一层的输入线性组合结果\(u_k\)动态范围压缩到特定值域(例如[-1,1]).一般来说具备非线性处理单元的深度神经网络(大于等于3层),理论上可以逼近任意函数.

其中几个常用的激活函数如下:
1.Sigmoid函数,值域为(0,1)
\[
\varphi(x) = \frac{1}{1+e^{-ax}}
\]

2.tanh函数,值域为(-1,1):
\[
\varphi(x) = \frac{1-e^{-2x}}{1+e^{-2x}}
\]

3.ReLu(Rectified Linear Unit,规整化线性单元)函数,值域为\([0,+ \infty)\),是一种非饱和激活函数.
\[
\varphi(x) = max(0,x)
\]

远不止上面这些激活函数,随着发展,陆续又出现了很多激活函数.这里不多介绍.后面还要自学很多这类相关知识.

神经网络中最大的问题是梯度消失问题(Gradient Vanishing Problem),这在使用 Sigmoid、tanh等饱和激活函数情况下尤为严重(神经网络进行误差反向传播时,各层都要乘以激活函数的一阶导数\(G=e\cdot \varphi'(x) \cdot x\)),梯度每传递一层都会衰减一次,网络层数较多时,梯度G就会不停的衰减至消失),使得训练网络时收敛极慢,而ReLU这类非饱和激活函数收敛速度就快很多.所以学习网络模型中一般都会选用类似ReLu这种死活函数.

接下来我们学习在caffe用代码实现对应层的计算,包括前向传播计算和反向传播计算.Caffe的所有与激活函数相关的Layer类声明在include/caffe/layers文件夹中分别为sigmoid_layer.hpp,relu_layer.hpp,tanh_layer.hpp,我们将它们统称为非线性层,我们重点关注ReLULayer,SigmoidLayer和TanHLayer这三类.

在前面我们测试的LeNet-5模型中使用了ReLu层,我们在example/mnist/lenet_train_test.prototxt中找到描述:

layer {
  name: "relu1"
  type: "ReLU"
  bottom: "ip1"
  top: "ip1"
}

与卷积层、全连接层最大的不同,就是没有权值相关的参数,描述相对简单。另外两种层没有实际样例,怎么办呢?这时按照我们的Caffe源码阅读方法论.从src/caffe/proto/caffe.proto中获得灵感。

// ReLU层参数
message ReLUParameter {
  // Allow non-zero slope for negative inputs to speed up optimization
  // Described in:
  // Maas, A. L., Hannun, A. Y., & Ng, A. Y. (2013). Rectifier nonlinearities
  // improve neural network acoustic models. In ICML Workshop on Deep Learning
  // for Audio, Speech, and Language Processing.
  // Leaky ReLU参数,我们暂不关心
  optional float negative_slope = 1 [default = 0];
  enum Engine {     //计算引擎选择
    DEFAULT = 0;
    CAFFE = 1;      // Caffe 实现
    CUDNN = 2;      // CUDNN 实现
  }
  optional Engine engine = 2 [default = DEFAULT];
}
// Sigmoid层参数
message SigmoidParameter {
  enum Engine {
    DEFAULT = 0;
    CAFFE = 1;
    CUDNN = 2;
  }
  optional Engine engine = 1 [default = DEFAULT];
}

//  tanh 层参数
message TanHParameter {
  enum Engine {
    DEFAULT = 0;
    CAFFE = 1;
    CUDNN = 2;
  }
  optional Engine engine = 1 [default = DEFAULT];
}

非线性层的共同特点就是对前一层blob中的数值逐一进行非线性变换,并放回原blob中。激活函数的类声明如下:

namespace caffe {
//非线性层的鼻祖NeuronLayer,派生于Layer类,特点是输出blob(y)与输入blob(x)尺寸相同

/**
 * @brief An interface for layers that take one blob as input (@f$ x @f$)
 *        and produce one equally-sized blob as output (@f$ y @f$), where
 *        each element of the output depends only on the corresponding input
 *        element.
 */
template <typename Dtype>
class NeuronLayer : public Layer<Dtype> {
 public:
  explicit NeuronLayer(const LayerParameter& param)
     : Layer<Dtype>(param) {}
  virtual void Reshape(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);

  virtual inline int ExactNumBottomBlobs() const { return 1; }
  virtual inline int ExactNumTopBlobs() const { return 1; }
};

}  // namespace caffe

#endif  // CAFFE_NEURON_LAYER_HPP_
namespace caffe {
// ReLULayer,派生于NeuronLayer,实现了ReLu激活函数计算

/**
 * @brief Rectified Linear Unit non-linearity @f$ y = \max(0, x) @f$.
 *        The simple max is fast to compute, and the function does not saturate.
 */
template <typename Dtype>
class ReLULayer : public NeuronLayer<Dtype> {
 public:
 //显式构造函数
 
  /**
   * @param param provides ReLUParameter relu_param,
   *     with ReLULayer options:
   *   - negative_slope (\b optional, default 0).
   *     the value @f$ \nu @f$ by which negative values are multiplied.
   */
  explicit ReLULayer(const LayerParameter& param)
      : NeuronLayer<Dtype>(param) {}
//返回类名字符串
  virtual inline const char* type() const { return "ReLU"; }

 protected:
  /**
   * @param bottom input Blob vector (length 1)
   *   -# @f$ (N \times C \times H \times W) @f$
   *      the inputs @f$ x @f$
   * @param top output Blob vector (length 1)
   *   -# @f$ (N \times C \times H \times W) @f$
   *      the computed outputs @f$
   *        y = \max(0, x)
   *      @f$ by default.  If a non-zero negative_slope @f$ \nu @f$ is provided,
   *      the computed outputs are @f$ y = \max(0, x) + \nu \min(0, x) @f$.
   */
   //前向传波函数
  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);
  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);

  /**
   * @brief Computes the error gradient w.r.t. the ReLU inputs.
   *
   * @param top output Blob vector (length 1), providing the error gradient with
   *      respect to the outputs
   *   -# @f$ (N \times C \times H \times W) @f$
   *      containing error gradients @f$ \frac{\partial E}{\partial y} @f$
   *      with respect to computed outputs @f$ y @f$
   * @param propagate_down see Layer::Backward.
   * @param bottom input Blob vector (length 1)
   *   -# @f$ (N \times C \times H \times W) @f$
   *      the inputs @f$ x @f$; Backward fills their diff with
   *      gradients @f$
   *        \frac{\partial E}{\partial x} = \left\{
   *        \begin{array}{lr}
   *            0 & \mathrm{if} \; x \le 0 \\
   *            \frac{\partial E}{\partial y} & \mathrm{if} \; x > 0
   *        \end{array} \right.
   *      @f$ if propagate_down[0], by default.
   *      If a non-zero negative_slope @f$ \nu @f$ is provided,
   *      the computed gradients are @f$
   *        \frac{\partial E}{\partial x} = \left\{
   *        \begin{array}{lr}
   *            \nu \frac{\partial E}{\partial y} & \mathrm{if} \; x \le 0 \\
   *            \frac{\partial E}{\partial y} & \mathrm{if} \; x > 0
   *        \end{array} \right.
   *      @f$.
   */
   
   //反向传波函数
  virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
  virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
};

}  // namespace caffe

#endif  // CAFFE_RELU_LAYER_HPP_
namespace caffe {
// SigmoidLayer,派生于NeuronLayer,实现了Sigmoid激活函数的计算
/**
 * @brief Sigmoid function non-linearity @f$
 *         y = (1 + \exp(-x))^{-1}
 *     @f$, a classic choice in neural networks.
 *
 * Note that the gradient vanishes as the values move away from 0.
 * The ReLULayer is often a better choice for this reason.
 */
template <typename Dtype>
class SigmoidLayer : public NeuronLayer<Dtype> {
 public:
 //显式构造函数
  explicit SigmoidLayer(const LayerParameter& param)
      : NeuronLayer<Dtype>(param) {}
//返回类名字符串
  virtual inline const char* type() const { return "Sigmoid"; }

 protected:
  /**
   * @param bottom input Blob vector (length 1)
   *   -# @f$ (N \times C \times H \times W) @f$
   *      the inputs @f$ x @f$
   * @param top output Blob vector (length 1)
   *   -# @f$ (N \times C \times H \times W) @f$
   *      the computed outputs @f$
   *        y = (1 + \exp(-x))^{-1}
   *      @f$
   */
   
   //前向传播函数
  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);
  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);

  /**
   * @brief Computes the error gradient w.r.t. the sigmoid inputs.
   *
   * @param top output Blob vector (length 1), providing the error gradient with
   *      respect to the outputs
   *   -# @f$ (N \times C \times H \times W) @f$
   *      containing error gradients @f$ \frac{\partial E}{\partial y} @f$
   *      with respect to computed outputs @f$ y @f$
   * @param propagate_down see Layer::Backward.
   * @param bottom input Blob vector (length 1)
   *   -# @f$ (N \times C \times H \times W) @f$
   *      the inputs @f$ x @f$; Backward fills their diff with
   *      gradients @f$
   *        \frac{\partial E}{\partial x}
   *            = \frac{\partial E}{\partial y} y (1 - y)
   *      @f$ if propagate_down[0]
   */
   
   //反向传播函数
  virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
  virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
};

}  // namespace caffe

#endif  // CAFFE_SIGMOID_LAYER_HPP_
namespace caffe {
// TanHLayer,派生于NeuronLayer,实现了tanh激活函数计算
/**
 * @brief TanH hyperbolic tangent non-linearity @f$
 *         y = \frac{\exp(2x) - 1}{\exp(2x) + 1}
 *     @f$, popular in auto-encoders.
 *
 * Note that the gradient vanishes as the values move away from 0.
 * The ReLULayer is often a better choice for this reason.
 */
template <typename Dtype>
class TanHLayer : public NeuronLayer<Dtype> {
 public:
 //显式构造函数
  explicit TanHLayer(const LayerParameter& param)
      : NeuronLayer<Dtype>(param) {}
//返回类名字符串
  virtual inline const char* type() const { return "TanH"; }

 protected:
  /**
   * @param bottom input Blob vector (length 1)
   *   -# @f$ (N \times C \times H \times W) @f$
   *      the inputs @f$ x @f$
   * @param top output Blob vector (length 1)
   *   -# @f$ (N \times C \times H \times W) @f$
   *      the computed outputs @f$
   *        y = \frac{\exp(2x) - 1}{\exp(2x) + 1}
   *      @f$
   */
   
   //前向传播函数
  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);
  virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top);

  /**
   * @brief Computes the error gradient w.r.t. the sigmoid inputs.
   *
   * @param top output Blob vector (length 1), providing the error gradient with
   *      respect to the outputs
   *   -# @f$ (N \times C \times H \times W) @f$
   *      containing error gradients @f$ \frac{\partial E}{\partial y} @f$
   *      with respect to computed outputs @f$ y @f$
   * @param propagate_down see Layer::Backward.
   * @param bottom input Blob vector (length 1)
   *   -# @f$ (N \times C \times H \times W) @f$
   *      the inputs @f$ x @f$; Backward fills their diff with
   *      gradients @f$
   *        \frac{\partial E}{\partial x}
   *            = \frac{\partial E}{\partial y}
   *              \left(1 - \left[\frac{\exp(2x) - 1}{exp(2x) + 1} \right]^2 \right)
   *            = \frac{\partial E}{\partial y} (1 - y^2)
   *      @f$ if propagate_down[0]
   */
   
   //反向传播函数
  virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
  virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
};

}  // namespace caffe

#endif  // CAFFE_TANH_LAYER_HPP_

上面类的声明比较简单,各自声明了Forward和Backward函数.下面对这些函数的实现进行解析.我们首先看下src/caffe/layers/relu_layer.cpp中前向传播函数的实现代码。

template <typename Dtype>
void ReLULayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
    const vector<Blob<Dtype>*>& top) {
    // (只读) 获得输人blob的data指针
  const Dtype* bottom_data = bottom[0]->cpu_data();
  // (读写)获得输出blob的data指针
  Dtype* top_data = top[0]->mutable_cpu_data();
  //获得输入blob元素个数
  const int count = bottom[0]->count();
  // Leaky ReLU参数,从layer_param中获得,默认为0,即普通ReLU
  Dtype negative_slope = this->layer_param_.relu_param().negative_slope();
  //执行ReLU操作我们姑且认为negative_slop值为0,不考虑Leaky ReLU
  for (int i = 0; i < count; ++i) {
    top_data[i] = std::max(bottom_data[i], Dtype(0))
        + negative_slope * std::min(bottom_data[i], Dtype(0));
  }
}

不出所料,用一层for循环就搞定了,下面我们来看反向传播函数的实现代码.

template <typename Dtype>
void ReLULayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
    const vector<bool>& propagate_down,
    const vector<Blob<Dtype>*>& bottom) {
    // 如果需要做反向传播计算
  if (propagate_down[0]) {
    //(只读)获得前一层的data指针
    const Dtype* bottom_data = bottom[0]->cpu_data();
    //(只读) 获得后一层的diff指针
    const Dtype* top_diff = top[0]->cpu_diff();
    //(读写) 获得前一层的diff指针
    Dtype* bottom_diff = bottom[0]->mutable_cpu_diff();
    //获得要参计算的元素总数
    const int count = bottom[0]->count();
    // Leaky ReLU参数,姑且认为是0
    Dtype negative_slope = this->layer_param_.relu_param().negative_slope();
    for (int i = 0; i < count; ++i) {
    // ReLU的导函数就是(bottom_data[i] > 0),根据求导链式法则,后一层的误差乘以导函数得到前一层的误差
      bottom_diff[i] = top_diff[i] * ((bottom_data[i] > 0)
          + negative_slope * (bottom_data[i] <= 0));
    }
  }
}

到这里可以看到ReLu计算非常简单(目前如此)

其它激活函数源码,之后也许用的比较少,这里不做多的介绍.

所以,非线性层虽然公式表示较为复杂,但代码实现都非常简洁、直观,只要掌握了基本求导技巧,同样可以推导出非线性层其他类的反向传播公式.

2017/6/3 posted in  caffe框架学习

HTMLParser

在Pythonz中我们有可能需要去解析一个爬下来的HTML,我们在Python中应该如何去解析呢?

好在Python提供了HTMLParser来非常方便地解析HTML,只需简单几行代码:

# -*- coding: utf-8 -*-
from HTMLParser import HTMLParser
from htmlentitydefs import name2codepoint

class MyHTMLParser(HTMLParser):
    def handle_starttag(self,tag,attrs):
        print ('<%s>' % tag)

    def handle_endtag(self,tag):
        print ('</%s>' % tag)
    
    def handle_startendtag(self, tag, attrs):
        print('<%s/>' % tag)

    def handle_data(self, data):
        print('data')

    def handle_comment(self, data):
        print('<!-- -->')

    def handle_entityref(self, name):
        print('&%s;' % name)

    def handle_charref(self, name):
        print('&#%s;' % name)
parser = MyHTMLParser()
parser.feed('<html><head></head><body><p>Some <a href=\"#\">html</a> tutorial...<br>END</p></body></html>')

feed()方法可以多次调用,也就是不一定一次把整个HTML字符串都塞进去,可以一部分一部分塞进去。

特殊字符有两种,一种是英文表示的&nbsp;,一种是数字表示的&#1234;,这两种字符都可以通过Parser解析出来。

练习

找一个网页,例如https://www.python.org/events/python-events/,用浏览器查看源码并复制,然后尝试解析一下HTML,输出Python官网发布的会议时间、名称和地点。

这里我们要解析HTML之前,肯定要先获取该页面元素的代码.我们这里用到了urllib这个库,具体用法为:

# -*- coding: utf-8 -*-
import urllib

PythonPage = urllib.urlopen('https://www.python.org/events/python-events/')
pyhtml = PythonPage.read()  #读取该页面代码.
print pyhtml


上面为结果,这里只是部分截图.

下面我们来继续研究上面的问题:

# -*- coding: utf-8 -*-
from HTMLParser import HTMLParser
from htmlentitydefs import name2codepoint
import urllib


class PyHTMLParser(HTMLParser):

    def __init__(self):
        HTMLParser.__init__(self)
        self._count = 0
        self._events = dict()
        self._flag = None

    def handle_starttag(self, tag, attrs):
        if tag == 'h3' and attrs.__contains__(('class', 'event-title')):
            self._count += 1
            self._events[self._count] = dict()
            self._flag = 'event-title'
        if tag == 'time':
            self._flag = 'time'
        if tag == 'span' and attrs.__contains__(('class', 'event-location')):
            self._flag = 'event-location'

    def handle_data(self, data):
        if self._flag == 'event-title':
            self._events[self._count][self._flag] = data
        if self._flag == 'time':
            self._events[self._count][self._flag] = data
        if self._flag == 'event-location':
            self._events[self._count][self._flag] = data
        self._flag = None   #一定要设置为None,防止其它data误入

    def event_list(self):
        print self._events
        print '近期关于Python的会议有:', self._count, '个,具体如下:'
        for event in self._events.values():
            print event['event-title'], '\t', event['time'], '\t', event['event-location']

PythonPage = urllib.urlopen('https://www.python.org/events/python-events/')
pyhtml = PythonPage.read()
parser = PyHTMLParser()
parser.feed(pyhtml)
parser.event_list()

这里我们将所遇到的属性,进行人为分类,将包含'event-title','time','event-location'关键字的属性聚类到一起,

2017/5/25