在开始Caffe的学习之前,希望你已经准备好了caffe环境,并且学习了Pytorch系列。CNN对我们来说不再是一个黑匣子,我们可以用自己的数据训练一个diy模型,但在实际生产中考虑到嵌入式应用和测试需要,通常将pth模型转成caffe.model进行集成,接下来我会通过Pytorch和Caffe的对比,来介绍Caffe的细节。
在Pytorch中我们可以定义一个自己的类,继承并实现nn.Module,在caffe中我们可以讲这些过程写在描述文件*.prototxt 中,其中包含了常见的预处理层(Data layer),卷积层(Conv layer),池化层(Pool),归一化(BN)等,各层之间的数据流动是blob,Pytorch中各层之间的数据是以tensor格式流动的,今天我们来讲述数据层也可以叫预处理层的主要实现细节及参数。
layer { name: "cifar" type: "Data" top: "data" #一般用bottom表示输入,top表示输出,多个top代表有多个输出 top: "label" include { phase: TRAIN #训练网络分为训练阶段和自测试阶段,如果没写include则表示该层即在测试中,又在训练中 } transform_param { mean_file: "examples/cifar10/mean.binaryproto" #用一个配置文件来进行均值的操作 transform_param { scale: 0.00390625 mirror: 1 # 1表示开启镜像,0表示关闭,也可用ture和false来表示 # 剪裁一个 227*227的图块,在训练阶段随机剪裁,在测试阶段从中间裁剪 crop_size: 227 } } data_param { source: "examples/cifar10/cifar10_train_lmdb" #数据库来源 batch_size: 64 #每次批处理的个数 backend: LMDB #选用数据的名称 } }参数详解:
name:表示该层的name,没有明确规定,可根据个人习惯,但建议取比较有训练集代表性的名字。 type:表示该层的类型,如果value是Data表示数据层,数据类型为LevelDB或者LMDB两种数据库。 top或bottom: 每一层用bottom来输入数据,用top来输出数据。如果只有top没有bottom,则此层只有输出,没有输入。如果有多个 top或多个bottom,表示有多个blobs数据的输入和输出。 data:数据实体 label:上述data的标签分类,在Pytorch中重写DataSet完成这个过程 include: 一般训练的时候和测试的时候,模型的层是不一样的。该层(layer)是属于训练阶段的层,还是属于测试阶段的层,需要用include来指定。如果没有include参数,则表示该层既在训练模型中,又在测试模型中。在Pytorch中通过定义net.train()和net.eval()来标记当前数据输入所执行的train或者val操作。 transforms:是数据的预处理,包含flip、rotate、crop等操作,也可以进行归一化操作,将数据变换到定义的范围内。如设置scale为0.00390625,实际上就是1/255, 即将输入数据由0-255归一化到0-1之间不同数据源加载方法:通常我们的数据可以来源于LMDB/LEVELDB、HDF5、IMAGE、MEMORY等,下面我们详细说一下不同数据源的加载方法:
出了上述两种方法,数据也可以直接来源于图片,假设图片列表如下格式
/path/to/images/img3423.jpg 2 /path/to/images/img3424.jpg 13 /path/to/images/img3425.jpg 8
示例:
layer { name: "data" type: "ImageData" #类型 top: "data" top: "label" transform_param { mirror: false crop_size: 227 mean_file: "data/ilsvrc12/imagenet_mean.binaryproto" } image_data_param { source: "examples/_temp/file_list.txt" batch_size: 50 new_height: 256 #如果设置就对图片进行resize操作 new_width: 256 } }出了上述的常见,datatype外还有Memory和WindowData,并没有过多的了解,下面是网友的实例,可以参考下。
示例:
layer { name: "data" type: "ImageData" top: "data" top: "label" transform_param { mirror: false crop_size: 227 mean_file: "data/ilsvrc12/imagenet_mean.binaryproto" } image_data_param { source: "examples/_temp/file_list.txt" batch_size: 50 new_height: 256 new_width: 256 } }示例:
layer { name: "data" type: "WindowData" top: "data" top: "label" include { phase: TRAIN } transform_param { mirror: true crop_size: 227 mean_file: "data/ilsvrc12/imagenet_mean.binaryproto" } window_data_param { source: "examples/finetune_pascal_detection/window_file_2007_trainval.txt" batch_size: 128 fg_threshold: 0.5 bg_threshold: 0.5 fg_fraction: 0.25 context_pad: 16 crop_mode: "warp" } }