Caffe 深度学习模型训练全过程

经过一星期的折腾,终于搞明白大致怎么使用caffe了,一下按序罗列下训练过程以及期间使用的某些技巧

未完成,有待继续学习

数据准备与处理

数据文件

lmdb 数据库 mnist_train_lmdb & mnist_test_lmdb

均值文件 imagenet_mean.binaryproto 生成均值文件命令 compute_image_mean [train_lmdb] [mean.binaryproto]

Data层

参考:caffe | Layers

caffe 主要是讲一下caffe对不同的数据类型的处理(二)

从图像转换为数据库

参考:Caffe 入门- caffe数据准备,格式转换

深度学习(十三)caffe之训练数据格式

采用 examples 中 imagenet 的方式

在存放data的文件夹下需要文件夹 ‘./train’ ‘./test’ 以及 ‘./train.txt’ ‘./test.txt’

可以通过python脚本生成两个 txt 文件

import os

ROOT_DIR='.'

OUTPUT_DIR='./pair.txt'

FORMAT='png'  

if __name__=='__main__':  

    if(ROOT_DIR.endswith('/') is not True):  
        ROOT_DIR+='/'  

    file=os.listdir(ROOT_DIR)  
    label=0  
    with open(OUTPUT_DIR,'w') as f:   
        for sub_file in file:
            #if sub_file[0]=='.' or sub_file=='maker.py' or sub_file=='pair.txt':
            if not os.path.isdir(sub_file):
                continue
            imglist=os.listdir(ROOT_DIR+sub_file)
            for img in imglist:  
                if(img.endswith(FORMAT) is not True):  
                    continue  
                str_tmp=str(sub_file)+'/'+img+' '+str(label)  
                f.write(str_tmp+'\n')  
            label+=1  
    print('Finish Processing')

根据需要可稍微改动下

然后就是修改下 create_imagenet.sh 中的路径就能输出lmdb

从数据库读取图像

参考:Caffe的深度学习训练全过程

从lmdb读入

import numpy as np
import lmdb
import sys
import caffe
from caffe.proto import caffe_pb2

def lmdb_process(db_path):
    env=lmdb.open(db_path)
    datum=caffe_pb2.Datum()
    item_id=0
    with env.begin() as txn:
        cursor=txn.cursor()
        for key,value in cursor:
            datum.ParseFromString(value)
            label=datum.label
            img=caffe.io.datum_to_array(datum)
            # do something here
            item_id+=1
    print item_id

if __name__=='__main__':
    db_path=sys.argv[1]
    lmdb_process(db_path)

从leveldb读入

import sys
import caffe
from caffe.proto import caffe_pb2
import leveldb
import numpy as np
from skimage import io

def leveldb_process(path):
    db=leveldb.LevelDB(path)
    datum=caffe_pb2.Datum()

    item_id=0
    for key,value in db.RangeIter():
        datum.ParseFromString(value)
        label=datum.label
        data=caffe.io.datum_to_array(datum)
        # do something here
        item_id+=1
    print item_id

if __name__=='__main__':
    path=sys.argv[1]
    leveldb_process(path)


从原始图片读入

from skimage import io
import sys
import os

folder=sys.argv[1]

l=os.listdir(folder)

item_id=0
for item in l:
    img=io.imread(folder+item,as_gray=True)
    item_id +=1
print item_id

在参考链接中可见从数据库读入明显快于读入原始数据

MNIST 数据集的可视化

参考:深度学习框架Caffe学习笔记(4)-MNIST数据集转换成可视化图片

在训练网络前我们使用create_mnist.sh脚本将MNIST数据集转换成lmdb格式,在该脚本中调用了convert_mnist_data.bin,这个可执行文件的源代码在examples/mnist/convert_mnist_data.cpp中。通过修改convert_mnist_data.cpp中的代码,可以将MNIST数据集转换成图片。在examples/mnist/目录下新建convert_mnist_image.cpp文件,内容如下:

// This script converts the MNIST dataset to image (png) format
// Usage:
//    convert_mnist_image [FLAGS] input_image_file output_png_file
// The MNIST dataset could be downloaded at
//    http://yann.lecun.com/exdb/mnist/

#include <gflags/gflags.h>
#include <glog/logging.h>

#include <stdint.h>
#include <sys/stat.h>

#include <fstream>  // NOLINT(readability/streams)
#include <string>

#include "opencv2/core/core.hpp"  
#include "opencv2/highgui/highgui.hpp"  
#include "opencv2/imgproc/imgproc.hpp" 

using std::string;

DEFINE_int32(rows, 25, "The rows of index in image");
DEFINE_int32(cols, 40, "The cols of index in image");
DEFINE_int32(offset, 0, "The offset of index in raw image");

//大端模式小端模式转换
uint32_t swap_endian(uint32_t val) {
    val = ((val << 8) & 0xFF00FF00) | ((val >> 8) & 0xFF00FF);
    return (val << 16) | (val >> 16);
}

//数据集转换函数,输入参数:MNIST数据集文件,图片文件
void convert_image(const char* image_filename, const char* png_filename) {
  // Open files
  std::ifstream image_file(image_filename, std::ios::in | std::ios::binary);
  CHECK(image_file) << "Unable to open file " << image_filename;
  // Read the magic and the meta data
  uint32_t magic;
  uint32_t num_items;
  uint32_t rows;
  uint32_t cols;

  //读取魔数
  image_file.read(reinterpret_cast<char*>(&magic), 4);
  magic = swap_endian(magic);
  CHECK_EQ(magic, 2051) << "Incorrect image file magic.";
  //读取数据条目总数
  image_file.read(reinterpret_cast<char*>(&num_items), 4);
  num_items = swap_endian(num_items);
  //读取行数
  image_file.read(reinterpret_cast<char*>(&rows), 4);
  rows = swap_endian(rows);
  //读取列数
  image_file.read(reinterpret_cast<char*>(&cols), 4);
  cols = swap_endian(cols);

  //命令行参数读取
  const int flag_rows = FLAGS_rows;
  const int flag_cols = FLAGS_cols;
  const int offset = FLAGS_offset;
  const int width = flag_cols*cols;
  const int height = flag_rows*rows;

  char* pixels = new char[rows * cols];
  cv::Mat tp = cv::Mat::zeros(height, width, CV_8UC1);
  //使用读取MINST数据,写入到opencv中的Mat类对象中
  image_file.seekg(offset*rows*cols, std::ios::cur);
  for(int i=0; i<flag_rows; i++) {
    for(int j=0; j<flag_cols; j++) {
      if(!image_file.eof()) {
        image_file.read(pixels, rows * cols);
        for(int k=0; k<rows; k++) {
          for(int l=0; l<cols; l++) {
            tp.at<uchar>(k + i*rows, j*cols + l) = (int)pixels[k*cols+l]; 
          }
        }
      }
      else {
        for(int k=0; k<rows; k++) {
          for(int l=0; l<cols; l++) {
            tp.at<uchar>(k + i*rows, j*cols + l) = 0; 
          }
        }
      }
    }
  }
  //调用opencv中的函数保存图片
  cv::imwrite(png_filename, tp); 
}

int main(int argc, char** argv) {
#ifndef GFLAGS_GFLAGS_H_
  namespace gflags = google;
#endif

  FLAGS_alsologtostderr = 1;
  // 设设置命令行参数帮助信息
  gflags::SetUsageMessage("This script converts the MNIST dataset ton"
        "image(png) format.n"
        "Usage:n"
        "    convert_mnist_data [FLAGS] input_image_file "
        "output_png_filen"
        "The MNIST dataset could be downloaded atn"
        "    http://yann.lecun.com/exdb/mnist/n"
        "You should gunzip them after downloading,"
        "or directly use data/mnist/get_mnist.shn");
  gflags::ParseCommandLineFlags(&argc, &argv, true);

  if (argc != 3) {
    gflags::ShowUsageWithFlagsRestrict(argv[0],
        "examples/mnist/convert_mnist_data");
  } else {
    google::InitGoogleLogging(argv[0]);
    //转换图片
    convert_image(argv[1], argv[2]);
  }
  return 0;
}

命令 ./build/examples/mnist/convert_mnist_image.bin data/mnist/train-images-idx3-ubyte examples/mnist/image.png

输出如下

稍作改动即可获得每一张数据

//命令行参数读取
  const int flag_numout = FLAGS_numout;
  const int offset = FLAGS_offset;

  char* pixels = new char[rows * cols];
  cv::Mat tp = cv::Mat::zeros(rows, cols, CV_8UC1);
  //使用读取MINST数据,写入到opencv中的Mat类对象中
  image_file.seekg(offset*rows*cols, std::ios::cur);
  for(int i=0; i<flag_numout; i++) {
    if(!image_file.eof()) {
      image_file.read(pixels, rows * cols);
      for(int k=0; k<rows; k++) {
    for(int l=0; l<cols; l++) {
      tp.at<uchar>(k, l) = (int)pixels[k*cols+l]; 
    }
      }
    }
    else {
      for(int k=0; k<rows; k++) {
    for(int l=0; l<cols; l++) {
      tp.at<uchar>(k, l) = 0; 
    }
      }
    }
    char buf[100];
    sprintf(buf,"%s/image%d.png",png_filename,i);
    fprintf(stderr,"%sn",buf);
    //调用opencv中的函数保存图片
    cv::imwrite(buf, tp); 
  }

模型训练

文件类型

Net配置 lenet_train_test.prototxt (-model)

Solver配置 lenet_solver.prototxt (-solver)

Snapshot lenet_iter_10000.caffemodel (-weights) & lenet_iter_10000.solverstate

使用pycaffe生成prototxt文件

参考:Caffe学习笔记(四):使用pycaffe生成train.prototxt、test.prototxt文件

import caffe
from caffe import layers as L
from caffe import params as P

caffe_root="examples/mnist/" 
train_lmdb="examples/mnist/mnist_train_lmdb"
test_lmdb="examples/mnist/mnist_test_lmdb"

net=caffe.NetSpec()

net.data,net.label=L.Data(source=train_lmdb,batch_size=64,backend=P.Data.LMDB,ntop=2\
                          ,transform_param={"scale":0.00390625})

net.conv1=L.Convolution(net.data,num_output=20,kernel_size=5,stride=1,\
                        weight_filler={"type":"xavier"},bias_filler={"type":"constant"}\
                        ,param=[{"lr_mult":1},{"lr_mult":2}])

net.pool1=L.Pooling(net.conv1,pool=P.Pooling.MAX,kernel_size=2,stride=2)

net.conv2=L.Convolution(net.pool1,num_output=50,kernel_size=5,stride=1,\
                        weight_filler={"type":"xavier"},bias_filler={"type":"constant"}\
                        ,param=[{"lr_mult":1},{"lr_mult":2}])

net.pool2=L.Pooling(net.conv2,pool=P.Pooling.MAX,kernel_size=2,stride=2)

net.ip1=L.InnerProduct(net.pool2,num_output=500,weight_filler={"type":"xavier"},bias_filler={"type":"constant"}\
                        ,param=[{"lr_mult":1},{"lr_mult":2}])

net.relu1=L.ReLU(net.ip1,in_place=True)


net.ip2=L.InnerProduct(net.relu1,num_output=10,weight_filler={"type":"xavier"},bias_filler={"type":"constant"}\
                        ,param=[{"lr_mult":1},{"lr_mult":2}])

net.accuracy=L.Accuracy(net.ip2,net.label)

net.loss=L.SoftmaxWithLoss(net.ip2,net.label)

print str(net.to_proto())

运行输出

layer {
  name: "data"
  type: "Data"
  top: "data"
  top: "label"
  transform_param {
    scale: 0.00390625
  }
  data_param {
    source: "examples/mnist/mnist_train_lmdb"
    batch_size: 64
    backend: LMDB
  }
}
layer {
  name: "conv1"
  type: "Convolution"
  bottom: "data"
  top: "conv1"
  param {
    lr_mult: 1.0
  }
  param {
    lr_mult: 2.0
  }
  convolution_param {
    num_output: 20
    kernel_size: 5
    stride: 1
    weight_filler {
      type: "xavier"
    }
    bias_filler {
      type: "constant"
    }
  }
}
layer {
  name: "pool1"
  type: "Pooling"
  bottom: "conv1"
  top: "pool1"
  pooling_param {
    pool: MAX
    kernel_size: 2
    stride: 2
  }
}
layer {
  name: "conv2"
  type: "Convolution"
  bottom: "pool1"
  top: "conv2"
  param {
    lr_mult: 1.0
  }
  param {
    lr_mult: 2.0
  }
  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.0
  }
  param {
    lr_mult: 2.0
  }
  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.0
  }
  param {
    lr_mult: 2.0
  }
  inner_product_param {
    num_output: 10
    weight_filler {
      type: "xavier"
    }
    bias_filler {
      type: "constant"
    }
  }
}
layer {
  name: "accuracy"
  type: "Accuracy"
  bottom: "ip2"
  bottom: "label"
  top: "accuracy"
}
layer {
  name: "loss"
  type: "SoftmaxWithLoss"
  bottom: "ip2"
  bottom: "label"
  top: "loss"
}

JialongdeMacBook-Pro:make_proto manchery$ python  maker.py 
layer {
  name: "data"
  type: "Data"
  top: "data"
  top: "label"
  transform_param {
    scale: 0.00390625
  }
  data_param {
    source: "examples/mnist/mnist_train_lmdb"
    batch_size: 64
    backend: LMDB
  }
}
layer {
  name: "conv1"
  type: "Convolution"
  bottom: "data"
  top: "conv1"
  param {
    lr_mult: 1.0
  }
  param {
    lr_mult: 2.0
  }
  convolution_param {
    num_output: 20
    kernel_size: 5
    stride: 1
    weight_filler {
      type: "xavier"
    }
    bias_filler {
      type: "constant"
    }
  }
}
layer {
  name: "pool1"
  type: "Pooling"
  bottom: "conv1"
  top: "pool1"
  pooling_param {
    pool: MAX
    kernel_size: 2
    stride: 2
  }
}
layer {
  name: "conv2"
  type: "Convolution"
  bottom: "pool1"
  top: "conv2"
  param {
    lr_mult: 1.0
  }
  param {
    lr_mult: 2.0
  }
  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.0
  }
  param {
    lr_mult: 2.0
  }
  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.0
  }
  param {
    lr_mult: 2.0
  }
  inner_product_param {
    num_output: 10
    weight_filler {
      type: "xavier"
    }
    bias_filler {
      type: "constant"
    }
  }
}
layer {
  name: "accuracy"
  type: "Accuracy"
  bottom: "ip2"
  bottom: "label"
  top: "accuracy"
}
layer {
  name: "loss"
  type: "SoftmaxWithLoss"
  bottom: "ip2"
  bottom: "label"
  top: "loss"
}

终端命令

./build/tools/caffe train --solver=examples/mnist/lenet_solver.prototxt

从Snapshot继续

参考:Caffe | ImageNet tutorial

命令:

./build/tools/caffe train --solver=models/bvlc_reference_caffenet/solver.prototxt --snapshot=models/bvlc_reference_caffenet/caffenet_train_iter_10000.solverstate

Transfer learning: finetuning

参考:Caffe | Fine-tuning CaffeNet for Style Recognition on “Flickr Style” Data

按照 layer 的 name 对应从 weights 中取值初始化,新建的层没有对应 name 即按照原配置初始化

一般会将solver中的 lr_base 以及 stepsize 等等降低达到freeze参数的目的

然后将新建的层的 lr_mult 提高训练该层

命令:

./build/tools/caffe train -solver models/finetune_flickr_style/solver.prototxt -weights models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel

模型评估

Test

命令:

caffe test -model examples/mnist/lenet_train_test.prototxt -weights examples/mnist/lenet_iter_10000.caffemodel -iterations 100

Benchmarking

评估每部分的计算耗时

命令:

caffe time -model examples/mnist/lenet_train_test.prototxt -iterations 10

caffe time -model examples/mnist/lenet_train_test.prototxt -weights examples/mnist/lenet_iter_10000.caffemodel -iterations 10

Plot the Log

输出日志信息

参考:<caffe学习笔记> caffe训练日志输出

将 Log 信息给输出来

./build/tools/caffe train --solver=models/bvlc_reference_caffenet/solver.prototxt
2>&1| tee yourpath/caffe.log

其中

  • tee的意思就是命令行信息重定向的命令

  • 2>&1的意思是错误的信息也当成标准信息输出,这样能够保证输出log信息的完整性

作图

参考:Caffe的深度学习训练全过程

先从log中提取出信息

grep Iteration mnist.log | grep loss | awk '{print $6,$13}' | sed 's/\,//' > loss.data

大概是这样

0 2.30824
100 0.21279
200 0.145315
300 0.166066
400 0.0950914
500 0.0854901
600 0.109592
700 0.127211
800 0.221222
900 0.157291
1000 0.083445

[...]

然后用python plot出来

import matplotlib.pyplot as plt
x=[]
y=[]
with open('loss.data') as f:
    for line in f:
        sps=line.split()
        x.append(int(sps[0]))
        y.append(float(sps[1]))
plt.plot(x,y)
plt.show()

可视化中间结果

参考:Caffe的深度学习训练全过程

import numpy as np
import sys
import caffe
from skimage import io

def vis_square(data):
    data = (data-data.min())/(data.max()-data.min())
    n=int(np.ceil(np.sqrt(data.shape[0])))
    padding=(((0,n**2-data.shape[0]),(0,1),(0,1))+((0,0),)*(data.ndim-3))
    data=np.pad(data,padding,mode='constant',constant_values=1)
    data=data.reshape((n,n)+data.shape[1:]).transpose((0,2,1,3)+tuple(range(4,data.ndim+1)))
    data=data.reshape((n*data.shape[1],n*data.shape[3])+data.shape[4:])
    return data

def predict(net,transformer,img):
    input_data=np.array(img)
    input_data=input_data.reshape(1,28,28,1)
    net.blobs['data'].data[...]=transformer.preprocess('data',input_data[0])
    out=net.forward()

def process(model_path,weight_path,img_path):
    net=caffe.Net(model_path,weight_path,caffe.TEST)
    transformer=caffe.io.Transformer({'data':net.blobs['data'].data.shape})
    transformer.set_transpose('data',(2,0,1))

    img=caffe.io.load_image(img_path,color=False)
    predict(net,transformer,img)
    for key in net.blobs:
        data=net.blobs[key].data
        if data.ndim==4:
            vis=vis_square(data[0])
            io.imsave(key+'.png',vis)

if __name__=='__main__':
    model_path=sys.argv[1]
    weight_path=sys.argv[2]
    img_path=sys.argv[3]
    process(model_path,weight_path,img_path)

在当前目录下输出这样

可以看出,网络第一层成功观察到了某些边缘的特征,符合我对CNN的理解和预期

使用训练完的模型

参考:Caffe源码解读(八):使用训练好的模型

Deploy

首先把训练时的配置 train_val.prototxt 修改成能使用的部署 deploy.prototxt

需要修改输入的data层和输出,详见 ./models/bvlc_reference_caffenet/ 目录下

如输入由

layer {
  name: "data"
  type: "Data"
  top: "data"
  top: "label"
  include {
    phase: TRAIN
  }
  transform_param {
    mirror: true
    crop_size: 227
    mean_file: "data/ilsvrc12/imagenet_mean.binaryproto"
  }
# mean pixel / channel-wise mean instead of mean image
#  transform_param {
#    crop_size: 227
#    mean_value: 104
#    mean_value: 117
#    mean_value: 123
#    mirror: true
#  }
  data_param {
    source: "examples/imagenet/ilsvrc12_train_lmdb"
    batch_size: 256
    backend: LMDB
  }
}
layer {
  name: "data"
  type: "Data"
  top: "data"
  top: "label"
  include {
    phase: TEST
  }
  transform_param {
    mirror: false
    crop_size: 227
    mean_file: "data/ilsvrc12/imagenet_mean.binaryproto"
  }
# mean pixel / channel-wise mean instead of mean image
#  transform_param {
#    crop_size: 227
#    mean_value: 104
#    mean_value: 117
#    mean_value: 123
#    mirror: false
#  }
  data_param {
    source: "examples/imagenet/ilsvrc12_val_lmdb"
    batch_size: 50
    backend: LMDB
  }
}

改为

layer {
  name: "data"
  type: "Input"
  top: "data"
  input_param { shape: { dim: 10 dim: 3 dim: 227 dim: 227 } }
}

输出由

layer {
  name: "accuracy"
  type: "Accuracy"
  bottom: "fc8"
  bottom: "label"
  top: "accuracy"
  include {
    phase: TEST
  }
}
layer {
  name: "loss"
  type: "SoftmaxWithLoss"
  bottom: "fc8"
  bottom: "label"
  top: "loss"
}

改为

layer {
  name: "prob"
  type: "Softmax"
  bottom: "fc8"
  top: "prob"
}

使用 C++ API 调用训练好的模型

参考:caffe | Classifying ImageNet: using the C++ API

Caffe源码解读(八):使用训练好的模型

现在来稍微修改一下 ./examples/cpp_classification/classification.cpp 来使用已经在MNIST上训练好的 lenet

./examples/cpp_classification/mnist_test.cpp

#include <caffe/caffe.hpp>
#ifdef USE_OPENCV
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#endif  // USE_OPENCV
#include <algorithm>
#include <iosfwd>
#include <memory>
#include <string>
#include <utility>
#include <vector>

#ifdef USE_OPENCV
using namespace caffe;  // NOLINT(build/namespaces)
using std::string;

/* Pair (label, confidence) representing a prediction. */
typedef std::pair<string, float> Prediction;

class Classifier {
 public:
  Classifier(const string& model_file,
             const string& trained_file,
             const string& mean_file,
             const string& label_file);

  std::vector<Prediction> Classify(const cv::Mat& img, int N = 5);

 private:
  void SetMean(const string& mean_file);

  std::vector<float> Predict(const cv::Mat& img);

  void WrapInputLayer(std::vector<cv::Mat>* input_channels);

  void Preprocess(const cv::Mat& img,
                  std::vector<cv::Mat>* input_channels);

 private:
  shared_ptr<Net<float> > net_;
  cv::Size input_geometry_;
  int num_channels_;
  cv::Mat mean_;
  std::vector<string> labels_;
};

Classifier::Classifier(const string& model_file,
                       const string& trained_file,
                       const string& mean_file,
                       const string& label_file) {
#ifdef CPU_ONLY
  Caffe::set_mode(Caffe::CPU);
#else
  Caffe::set_mode(Caffe::GPU);
#endif

  /* Load the network. */
  net_.reset(new Net<float>(model_file, TEST));
  net_->CopyTrainedLayersFrom(trained_file);

  CHECK_EQ(net_->num_inputs(), 1) << "Network should have exactly one input.";
  CHECK_EQ(net_->num_outputs(), 1) << "Network should have exactly one output.";

  Blob<float>* input_layer = net_->input_blobs()[0];
  num_channels_ = input_layer->channels();
  CHECK(num_channels_ == 3 || num_channels_ == 1)
    << "Input layer should have 1 or 3 channels.";
  input_geometry_ = cv::Size(input_layer->width(), input_layer->height());

  /* Load the binaryproto mean file. */
  //SetMean(mean_file);

  /* Load labels. */
  std::ifstream labels(label_file.c_str());
  CHECK(labels) << "Unable to open labels file " << label_file;
  string line;
  while (std::getline(labels, line))
    labels_.push_back(string(line));

  Blob<float>* output_layer = net_->output_blobs()[0];
  CHECK_EQ(labels_.size(), output_layer->channels())
    << "Number of labels is different from the output layer dimension.";
}

static bool PairCompare(const std::pair<float, int>& lhs,
                        const std::pair<float, int>& rhs) {
  return lhs.first > rhs.first;
}

/* Return the indices of the top N values of vector v. */
static std::vector<int> Argmax(const std::vector<float>& v, int N) {
  std::vector<std::pair<float, int> > pairs;
  for (size_t i = 0; i < v.size(); ++i)
    pairs.push_back(std::make_pair(v[i], i));
  std::partial_sort(pairs.begin(), pairs.begin() + N, pairs.end(), PairCompare);

  std::vector<int> result;
  for (int i = 0; i < N; ++i)
    result.push_back(pairs[i].second);
  return result;
}

/* Return the top N predictions. */
std::vector<Prediction> Classifier::Classify(const cv::Mat& img, int N) {
  std::vector<float> output = Predict(img);

  N = std::min<int>(labels_.size(), N);
  std::vector<int> maxN = Argmax(output, N);
  std::vector<Prediction> predictions;
  for (int i = 0; i < N; ++i) {
    int idx = maxN[i];
    predictions.push_back(std::make_pair(labels_[idx], output[idx]));
  }

  return predictions;
}

/* Load the mean file in binaryproto format. */
void Classifier::SetMean(const string& mean_file) {
  BlobProto blob_proto;
  ReadProtoFromBinaryFileOrDie(mean_file.c_str(), &blob_proto);

  /* Convert from BlobProto to Blob<float> */
  Blob<float> mean_blob;
  mean_blob.FromProto(blob_proto);
  CHECK_EQ(mean_blob.channels(), num_channels_)
    << "Number of channels of mean file doesn't match input layer.";

  /* The format of the mean file is planar 32-bit float BGR or grayscale. */
  std::vector<cv::Mat> channels;
  float* data = mean_blob.mutable_cpu_data();
  for (int i = 0; i < num_channels_; ++i) {
    /* Extract an individual channel. */
    cv::Mat channel(mean_blob.height(), mean_blob.width(), CV_32FC1, data);
    channels.push_back(channel);
    data += mean_blob.height() * mean_blob.width();
  }

  /* Merge the separate channels into a single image. */
  cv::Mat mean;
  cv::merge(channels, mean);

  /* Compute the global mean pixel value and create a mean image
   * filled with this value. */
  cv::Scalar channel_mean = cv::mean(mean);
  mean_ = cv::Mat(input_geometry_, mean.type(), channel_mean);
}

std::vector<float> Classifier::Predict(const cv::Mat& img) {
  Blob<float>* input_layer = net_->input_blobs()[0];
  input_layer->Reshape(1, num_channels_,
                       input_geometry_.height, input_geometry_.width);
  /* Forward dimension change to all layers. */
  net_->Reshape();

  std::vector<cv::Mat> input_channels;
  WrapInputLayer(&input_channels);

  Preprocess(img, &input_channels);

  net_->Forward();

  /* Copy the output layer to a std::vector */
  Blob<float>* output_layer = net_->output_blobs()[0];
  const float* begin = output_layer->cpu_data();
  const float* end = begin + output_layer->channels();
  return std::vector<float>(begin, end);
}

/* Wrap the input layer of the network in separate cv::Mat objects
 * (one per channel). This way we save one memcpy operation and we
 * don't need to rely on cudaMemcpy2D. The last preprocessing
 * operation will write the separate channels directly to the input
 * layer. */
void Classifier::WrapInputLayer(std::vector<cv::Mat>* input_channels) {
  Blob<float>* input_layer = net_->input_blobs()[0];

  int width = input_layer->width();
  int height = input_layer->height();
  float* input_data = input_layer->mutable_cpu_data();
  for (int i = 0; i < input_layer->channels(); ++i) {
    cv::Mat channel(height, width, CV_32FC1, input_data);
    input_channels->push_back(channel);
    input_data += width * height;
  }
}

void Classifier::Preprocess(const cv::Mat& img,
                            std::vector<cv::Mat>* input_channels) {
  /* Convert the input image to the input image format of the network. */
  cv::Mat sample;
  if (img.channels() == 3 && num_channels_ == 1)
    cv::cvtColor(img, sample, cv::COLOR_BGR2GRAY);
  else if (img.channels() == 4 && num_channels_ == 1)
    cv::cvtColor(img, sample, cv::COLOR_BGRA2GRAY);
  else if (img.channels() == 4 && num_channels_ == 3)
    cv::cvtColor(img, sample, cv::COLOR_BGRA2BGR);
  else if (img.channels() == 1 && num_channels_ == 3)
    cv::cvtColor(img, sample, cv::COLOR_GRAY2BGR);
  else
    sample = img;

  cv::Mat sample_resized;
  if (sample.size() != input_geometry_)
    cv::resize(sample, sample_resized, input_geometry_);
  else
    sample_resized = sample;

  cv::Mat sample_float;
  if (num_channels_ == 3)
    sample_resized.convertTo(sample_float, CV_32FC3);
  else
    sample_resized.convertTo(sample_float, CV_32FC1);

  cv::Mat sample_normalized;
  //cv::subtract(sample_float, mean_, sample_normalized);
  sample_normalized=sample_float.mul(0.00390625);

  /* This operation will write the separate BGR planes directly to the
   * input layer of the network because it is wrapped by the cv::Mat
   * objects in input_channels. */
  cv::split(sample_normalized, *input_channels);

  CHECK(reinterpret_cast<float*>(input_channels->at(0).data)
        == net_->input_blobs()[0]->cpu_data())
    << "Input channels are not wrapping the input layer of the network.";
}

int main(int argc, char** argv) {
  if (argc != 5) {
    std::cerr << "Usage: " << argv[0]
              << " deploy.prototxt network.caffemodel"
              << " labels.txt img.jpg" << std::endl;
    return 1;
  }

  ::google::InitGoogleLogging(argv[0]);

  string model_file   = argv[1];
  string trained_file = argv[2];
  string mean_file    = "";
  string label_file   = argv[3];
  Classifier classifier(model_file, trained_file, mean_file, label_file);

  string file = argv[4];

  std::cout << "---------- Prediction for "
            << file << " ----------" << std::endl;

  cv::Mat img = cv::imread(file, -1);
  CHECK(!img.empty()) << "Unable to decode image " << file;
  std::vector<Prediction> predictions = classifier.Classify(img);

  /* Print the top N predictions. */
  for (size_t i = 0; i < predictions.size(); ++i) {
    Prediction p = predictions[i];
    std::cout << std::fixed << std::setprecision(4) << p.second << " - \""
              << p.first << "\"" << std::endl;
  }
}
#else
int main(int argc, char** argv) {
  LOG(FATAL) << "This example requires OpenCV; compile with USE_OPENCV.";
}
#endif  // USE_OPENCV

运行命令并输出如下

./build/examples/cpp_classification/mnist_test.bin examples/mnist/lenet.prototxt examples/mnist/lenet_iter_10000.caffemodel examples/mnist/manchery/test/synset_words.txt examples/mnist/manchery/test/test0.png 
---------- Prediction for examples/mnist/manchery/test/test0.png ----------
0.9981 - "3"
0.0010 - "9"
0.0008 - "8"
0.0000 - "2"
0.0000 - "0"

使用 pycaffe 读取修改 caffemodel 文件里的参数

参考:读取和修改caffemodel文件里的参数——by 蠢鱼

import caffe

if __name__ == "__main__":
    root = './examples/mnist/'

    caffe.set_mode_cpu
    net = caffe.Net(root+'lenet.prototxt',root+'lenet_iter_10000.caffemodel',caffe.TEST)

    conv1_w = net.params['conv1'][0].data

    conv1_b = net.params['conv1'][1].data

    print conv1_w,conv1_b
    print conv1_w.size,conv1_b.size


至此应该是完结啦,要开始看paper啦 —— 2018.06.25

发表评论