本文主要运行一个手写体数字识别的程序,熟悉一下整体caffe的运行过程。
手写体数字数据库介绍:https://en.wikipedia.org/wiki/MNIST_database。主要就是标注了0~9的数字图片,我们可以运用机器学习的算法完成对图片识别的预测。
主要分为3个步骤:
1、获取数据 2、转换数据格式 3、训练 4、预测
脚本代码如下:
//获取数据
$ ./data/mnist/get_mnist.sh
//转换数据格式
$ ./examples/mnist/create_mnist.sh
//训练模型
$ ./examples/mnist/train_lenet.sh
//预测数据
$ ./build/tools/caffe test -model examples/mnist/lenet_train_test.prototxt -weights examples/mnist/lenet_iter_10000.caffemodel -iterrations 100
注意:
1、获取数据
在caffe的根目录下敲打命令:
$ ./data/mnist/get_mnist.sh
该脚本主要执行了下载数据命令:(https://github.com/BVLC/caffe/blob/master/data/mnist/get_mnist.sh)
#!/usr/bin/env sh
# This scripts downloads the mnist data and unzips it.
DIR="$( cd "$(dirname "$0")" ; pwd -P )"
cd "$DIR"
echo "Downloading..."
for fname in train-images-idx3-ubyte train-labels-idx1-ubyte t10k-images-idx3-ubyte t10k-labels-idx1-ubyte
do
if [ ! -e $fname ]; then
wget --no-check-certificate http://yann.lecun.com/exdb/mnist/${fname}.gz
gunzip ${fname}.gz
fi
done
2、将数据转化为lmdb格式:
$ ./examples/mnist/create_mnist.sh
该脚本主要执行了将下载的数据转换成lmdb格式,图片及标签一一匹配(https://github.com/BVLC/caffe/blob/master/examples/mnist/create_mnist.sh)
#!/usr/bin/env sh
# This script converts the mnist data into lmdb/leveldb format,
# depending on the value assigned to $BACKEND.
set -e
EXAMPLE=examples/mnist
DATA=data/mnist
BUILD=build/examples/mnist
BACKEND="lmdb"
echo "Creating ${BACKEND}..."
rm -rf $EXAMPLE/mnist_train_${BACKEND}
rm -rf $EXAMPLE/mnist_test_${BACKEND}
$BUILD/convert_mnist_data.bin $DATA/train-images-idx3-ubyte \
$DATA/train-labels-idx1-ubyte $EXAMPLE/mnist_train_${BACKEND} --backend=${BACKEND}
$BUILD/convert_mnist_data.bin $DATA/t10k-images-idx3-ubyte \
$DATA/t10k-labels-idx1-ubyte $EXAMPLE/mnist_test_${BACKEND} --backend=${BACKEND}
echo "Done."
我们可以看到转化时,使用了convert_mnist_data.bin 这个工具,如果有兴趣可以看一下源文件(https://github.com/BVLC/caffe/blob/master/examples/mnist/convert_mnist_data.cpp)
3、训练模型
$ ./examples/mnist/train_lenet.sh
该脚本非常简单的一句话:
$ ./build/tools/caffe train --solver=examples/mnist/lenet_solver.prototxt
使用了tools下caffe程序,参数为 训练 和lenet_solver模型参数。进入到lenet_solver.protoxt 我们可以看到以下信息(注意:如果使用CPU请修改最后一行)
caffe模型的定义全部使用了prototxt类型的文件。该文件方便不同平台的调用,对于跨语言的集成有着非常大的优点,关于prototxt日后专门细说。
运行训练时,cpu一般会跑10分钟左右,在屏幕上你可以看到一行行的loss函数在减小的情况。如下图所示:
模型会5000次迭代自动保存(人为可以设置),模型如下:
4、预测
$ ./build/tools/caffe test -model examples/mnist/lenet_train_test.prototxt -weights examples/mnist/lenet_iter_10000.caffemodel -iterrations 100
命令行解释:
./build/tools/caffe test 表示之作预测(前向传播计算),不进行参数更新(后向传播计算)。
-model examples/mnist/lenet_train_test.prototxt,指定模型描述文本文件。
-weights examples/mnist/lenet_iter_10000.caffemodel,指定模型预先训练好的权值文件。
-iterations 100,指定测试迭代次数。参与测试的样例数目为(iterations * batch_size),batch_size 在model prototxt 中设定,为100时刚好覆盖全部10000个测试样本。
参考资料:
dataguru caffe应用与实践课程
《深度学习21天实战caffe》 第6章