Hello World based on caffe之LeNet详解

MNIST数据集是纽约大学Yann LeCun教授整理的一个大型的手写体数字数据库,包括6万个训练集和1万个测试集,尺寸都进行了归一化,尺寸为28x28.
下载链接为 http://yann.lecun.com/exdb/mnist/ caffe中也提供了脚本来下载,在caffe/data/mnist中
MNIST原始数据为4个文件:
train-images-idx3-ubyte 训练集,图片
train-labels-idx1-ubyte 训练集 标签
t10k-images-idx3-ubyte 测试集, 图片
t10k-labels-idx1-ubyte 测试集 , 标签
各个文件的存储格式大家可以自行搜索了解。该数据集为二进制文件,需要转换为LEVELDB或者LMDB才能被caffe识别,caffe中提供了脚本来转换: caffe/examples/mnist/create_mnist.sh 直接执行这个脚本就可以,里面已经写了mnist data的路径. 转换好的文件就放置在examples/mnist/目录下。默认是lmdb格式,分为两个文件夹,一个用于train,一个用于test

我们可以在源码中添加log的方式来分析源码
LOG(INFO) << "GPU " << gpus[i] << ": " << device_prop.name; 就想std::cout一样使用

下面我们来看LeNet的网络结构, 在example/mnist/lenet_train_test.prototxt.在下面的结构中,我们可以看到,这里面定义了有train的layer和test的layer. 所以train net和test net都用这个prototxt文件,等创建net的时候,net会根据创建时传入的是train还是test来选择所对应的layer.没有标注是train还是test的layer为两种网络共用的layer. 所以使用这一个prototxt文件就可以在solver中创建了一个train net和一个test net.

name: "LeNet"
//这是training网络的数据输入层,输出两个blob, 一个是数据,一个是标签,标签是直接给到最后算loss用的
layer {
  name: "mnist"
  type: "Data"
  top: "data"
  top: "label"
  include {
    phase: TRAIN 
  }
  transform_param {
  /*这里是数据层的预处理,scale就是将输入图片的每个像素值都乘以scale, 这里看到是个小数,其实就是1/256,也就是将图片的像素值都归一化到[0-1]之间*/
    scale: 0.00390625  
  }
  data_param {
    source: "examples/mnist/mnist_train_lmdb"
    batch_size: 64 //批处理,每次处理64张图片
    backend: LMDB
  }
}
/*test网络的数据输入层*/
layer {
  name: "mnist"
  type: "Data"
  top: "data"
  top: "label"
  include {
    phase: TEST
  }
  transform_param {
    scale: 0.00390625
  }
  data_param {
    source: "examples/mnist/mnist_test_lmdb"
    batch_size: 100
    backend: LMDB
  }
}
layer {
  name: "conv1"
  type: "Convolution"
  bottom: "data"
  top: "conv1"
  param {
    lr_mult: 1//权重学习率,在solver中会定义一个base学习率(base_lr),然后权重lr = base_lr * lr_mult
  }
  param {
    lr_mult: 2 //偏置bias学习率= base_lr * lr_mult
  }
  convolution_param {
    num_output: 20  //卷积核的个数
    kernel_size: 5  //卷积核大小
    stride: 1 //滑动步长
    //权重参数初始值的填充方法,也就是初始值设置为多少,是随机,还是填一个统一的值,还是其他方法。这里的xavier是从[-scale,scale]中进行均匀采样
    weight_filler { 
      type: "xavier"
    }
    bias_filler {
      type: "constant"
    }
  }
}
/*pooling 层的参数*/
layer {
  name: "pool1"
  type: "Pooling"
  bottom: "conv1"
  top: "pool1"
  pooling_param {
    pool: MAX //最大值方法pooling
    kernel_size: 2
    stride: 2
  }
}
layer {
  name: "conv2"
  type: "Convolution"
  bottom: "pool1"
  top: "conv2"
  param {
    lr_mult: 1
  }
  param {
    lr_mult: 2
  }
  convolution_param {
    num_output: 50
    kernel_size: 5
    stride: 1
    weight_filler {
      type: "xavier"
    }
    bias_filler {
      type: "constant"
    }
  }
}
layer {
  name: "pool2"
  type: "Pooling"
  bottom: "conv2"
  top: "pool2"
  pooling_param {
    pool: MAX
    kernel_size: 2
    stride: 2
  }
}
/*全连接层*/
layer {
  name: "ip1"
  type: "InnerProduct"
  bottom: "pool2"
  top: "ip1"
  param {
    lr_mult: 1
  }
  param {
    lr_mult: 2
  }
  inner_product_param {
    num_output: 500
    weight_filler {
      type: "xavier"
    }
    bias_filler {
      type: "constant"
    }
  }
}
layer {
  name: "relu1"
  type: "ReLU"
  bottom: "ip1"
  top: "ip1"
}
layer {
  name: "ip2"
  type: "InnerProduct"
  bottom: "ip1"
  top: "ip2"
  param {
    lr_mult: 1
  }
  param {
    lr_mult: 2
  }
  inner_product_param {
    num_output: 10
    weight_filler {
      type: "xavier"
    }
    bias_filler {
      type: "constant"
    }
  }
}
/*精度层,用于test网络*/
layer {
  name: "accuracy"
  type: "Accuracy"
  bottom: "ip2"
  bottom: "label"
  top: "accuracy"
  include {
    phase: TEST
  }
}
/*损失层,用于training网络*/
layer {
  name: "loss"
  type: "SoftmaxWithLoss"
  bottom: "ip2"
  bottom: "label"
  top: "loss"
}

下面查看solver的参数:lenet_solver.prototxt  在这个配置文件中放置了一些超参数,比如使用哪个网络,学习率等参数.这里可以参考这篇博客:https://blog.csdn.net/qq_26898461/article/details/50445392

 # The train/test net protocol buffer definition
 //使用的网络结构的prototxt, 路径是以caffe目录为基础的相对目录
   net: "examples/mnist/lenet_train_test.prototxt"
   # test_iter specifies how many forward passes the test should carry out.
   # In the case of MNIST, we have test batch size 100 and 100 test iterations,
   # covering the full 10,000 testing images.
   /*这个和batch_size配合使用,batch_size就是一次前向运算输入的图片个数,比如我们设置为100, 
   则一次运算输入100张图片,mnist测试集一共有10000张图片,则要全部测试完需要测试100次,
   所以这里test_iter就是测试的次数。从这里可以看出,每test一次,并不是test一张或者几张图片,
   而是将整个测试集都测试一遍,算出来平均loss。
   */
   test_iter: 100
   # Carry out testing every 500 training iterations.
   /*这里就是每training 500次,就test一次*/
   test_interval: 500
   # The base learning rate, momentum and the weight decay of the network.
   /*基础学习率, 这里要和下面的几个参数配合使用
   lr_policy可以设置为下面这些值,相应的学习率的计算为:
  - fixed:   保持base_lr不变.
  - step:    如果设置为step,则还需要设置一个stepsize,  返回 base_lr * gamma ^ (floor(iter /
        stepsize)),其中iter表示当前的迭代次数
  - exp:     返回base_lr * gamma ^ iter, iter为当前迭代次数
  - inv:      如果设置为inv,还需要设置一个power, 返回base_lr * (1 + gamma * iter) ^ (- power)
  - multistep: 如果设置为multistep,则还需要设置一个stepvalue。这个参数和step很相似,step是均匀
        等间隔变化,而multistep则是根据stepvalue值变化
  - poly:     学习率进行多项式误差, 返回 base_lr (1 - iter/max_iter) ^ (power)
  - sigmoid: 学习率进行sigmod衰减,返回 base_lr ( 1/(1 + exp(-gamma * (iter - stepsize))))
   */
  base_lr: 0.01
   # The learning rate policy
  lr_policy: "inv"
  gamma: 0.0001
  power: 0.75
  momentum: 0.9 //动量,是为了training时冲过鞍区,找到最小值
  weight_decay: 0.0005 //权重衰减项,防止过拟合的一个参数。
  # Display every 100 iterations
  display: 100 //每训练100次,在屏幕上显示一次。如果设置为0,则不显示
  # The maximum number of iterations
  max_iter: 1000  //最大迭代次数。这个数设置太小,会导致没有收敛,精确度很低。设置太大,会导致震荡,浪费时间
  # snapshot intermediate results
  /*
  快照。将训练出来的model和solver状态进行保存,snapshot用于设置训练多少次后进行保存,默认为0,不保存。snapshot_prefix设置保存路径。
还可以设置snapshot_diff,是否保存梯度值,默认为false,不保存。
也可以设置snapshot_format,保存的类型。有两种选择:HDF5 和BINARYPROTO ,默认为BINARYPROTO
  */
  snapshot: 500
  snapshot_prefix: "examples/mnist/lenet"                                                                                                                                                                        
  # solver mode: CPU or GPU
  //设置运行模式。默认为GPU,如果你没有GPU,则需要改成CPU,否则会出错。
  solver_mode: CPU

先介绍train net的网络结构:

layer name --layer id -------bottom -------------top----------
  mnist      0               no                "data"(blob id 0) : shape : 64x1x28x28 
                                               "label"(blob id 1) : shape : 64
  con1       1               "data"            "conv1"(blob id 2) : shape : 64x20x24x24
  pool1      2               "conv1"           "pool1" (blob id  3) : shape : 64x20x12x12
  conv2      3               "pool1"           "conv2" (blob id 4) : shape : 64x50x8x8
  pool2      4               "conv2"           "pool2" (blob id 5) : shape : 64x50x4x4
  ip1        5               "pool2"           "ip1" (blob id 6) : shape : 64x500
  relu1      6               "ip1"             "ip1"(in-place) : shape : 64x500
  ip2        7               "ip1"             "ip2"(blob id 7) : shape : 64x10
  loss       8               "ip2", "label"    "loss"(blob id 8) : shape : 1

test net 网络结构:
这里caffe自动insert了两个layer, label_mnist_split和ip2_ip2_0_split, 就是因为label blob需要同时传递给
两个layer: accuracy和loss, ip2同样也需要传递给这两个网络,所以caffe就自动insert了这两个layer,来生成两份label blob和ip2 blob. 关于自动insert的内容,可以参考https://www.cnblogs.com/Relu110/p/12008459.html*/

layer name ----------layer id -------bottom -----------------------top----------
  mnist               0               no                           "data"(blob id 0) : shape : 100x1x28x28 
                                                                   "label"(blob id 1) : shape : 100
label_mnist_split     1              "label"                       "label_mnist_1_split_0(blob id 2) : shape : 100"
                                                                   "label_mnist_1_split_1(blob id 3) : shape : 100"
  con1                2               "data"                       "conv1"(blob id 4) : shape : 100x20x24x24
  pool1               3               "conv1"                      "pool1" (blob id  5) : shape : 100x20x12x12
  conv2               4               "pool1"                      "conv2" (blob id 6) : shape : 100x50x8x8
  pool2               5               "conv2"                      "pool2" (blob id 7) : shape : 100x50x4x4
  ip1                 6               "pool2"                      "ip1" (blob id 8) : shape : 100x500
  relu1               7               "ip1"                        "ip1"(in-place) : shape : 100x500
  ip2                 8               "ip1"                        "ip2"(blob id 9) : shape : 100x10
  ip2_ip2_0_split     9               "ip2"                        "ip2_ip2_0_split_0"(blob id 10) : shape : 100x10
                                                                   "ip2_ip2_0_split_1"(blob id 11) : shape : 100x10
  accuracy            10              "ip2_ip2_0_split_0"          "accuracy"(blob id 12) : shape : 1
                                      "label_mnist_1_split_0"
  loss                11              "ip2_ip2_0_split_1"          "loss"(blob_id:13) : shape : 1
                                      "label_mnist_1_split_1"

1.根据solver的配置文件,比如test net的batch size 为100, 也就是一次输入100张图片,test_iter 为100, 也就是每次测试的时候跑100次test net的forward前向计算,这样每次测试总共跑10000张图片。而mnist图库的测试图片就是10000张,也就是每次test的时候把图库中所有图片跑一次,算出来平均的Loss.

2.training的时候,会调用net的ForwardBackward(),在这个函数中,会先跑一次前向计算来计算Loss, 然后跑一次Backward反向计算一次来training。

未完待续…

反向传播算法的几篇播客记录:
https://zhuanlan.zhihu.com/p/40951745
https://blog.csdn.net/l297969586/article/details/79701522
https://blog.csdn.net/lr87v5/article/details/80002374
https://blog.csdn.net/lr87v5/article/details/80082344

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值