实战Caffe-第三天

主要实现LeNet这个简单的网络,顺便验证一下Caffe是否编译成功。

1.下载数据:在caffe-master根目录下,执行sudo bash ./data/mnist/get_mnist.sh,完毕之后会下载好四个文件。

2.下载好的文件是二进制,caffe不能直接使用,需要转换成LMDB或LEVELDB数据库形式,或者其他形式配合相应的读取方式。执行sudo bash ./example/mnist/create_mnist.sh。该脚本会调用convert_mnist_data.bin转换格式,生成mnist_train_lmdb和mnist_test_lmdb在caffe_master/example/mnist目录下面。如果没有在caffe-master根目录下,可能会报错

create_mnist.sh: 17: create_mnist.sh: build/examples/mnist/convert_mnist_data.bin: not found 

这是因为新版的caffe需要在caffe-mater根目录下执行命令才行。

3.网络配置

这里需要注意source的路径,根据自己的情况修改。

4.训练网络

执行sudo exampes/mnist/train_lenet.sh。实际执行的是lenet_solver.prototxt

注意将lenet_solver.prototxt中GPU改为CPU,我首先用GPU没有跑通,改为CPU就没问题了,不知道是不是自己cudnn没有转好,有点忧桑。

训练好的模型结果存放在example/mnist/lenet_iter_10000.caffemodel。训练状态存放在example/mnist/lenet_iter_10000.solverstate。

5.测试网络

执行sudo ./build/tools/caffe.bin test -model examples/mnist/lenet_train_test.prototxt -weights examples/mnist/lenet_iter_10000.caffemodel -iterations 100

test:表示对训练好的模型进行测试。其他参数有:train,time,device_query。

-model:指定模型prototxt文件,详细描述了网络结构和数据集信息。

6.mnist手写测试

测试图片必须满足:256位黑底白字;大小28*28;数字在图片中间,上下无过多空白。

import os
import sys
import numpy as np
import matplotlib.pyplot as plt
caffe_root='/home/caeluszhao/caffe-master/'  
sys.path.insert(0,caffe_root+'python')
import caffe
MODEL_FILE='/home/caeluszhao/caffe-master/examples/mnist/lenet.prototxt'
PRETRAINED='/home/caeluszhao/caffe-master/examples/mnist/lenet_iter_10000.caffemodel'
IMAGE_FILE='/home/caeluszhao/caffe-master/examples/images/5.png'

input_image=caffe.io.load_image(IMAGE_FILE,color=False)

net = caffe.Classifier(MODEL_FILE, PRETRAINED)

prediction=net.predict([input_image],oversample=False)
caffe.set_mode_cpu()
print 'predicted class: ', prediction[0].argmax()

使用了两张图片:2和5,测试成功。

猜你喜欢

转载自blog.csdn.net/cat1992/article/details/80204339
今日推荐