caffe+python+mnist从图片训练到测试单张图片

原文:https://blog.csdn.net/jingkebiao4847/article/details/53925652

[html] view plain copy
  1. 环境:caffe已经装好,GPU训练模式,ubuntu14,  

1.从图片格式的数据集开始,下载了mnist图片格式的数据集,下载地址:http://download.csdn.net/download/magicarcher/9529956 

解压以后放在caffe-master/data/Mnist_image中,MNIST是一个手写数字数据库,它有60000个训练样本集和10000个测试样本集。

2.数据准备,转换成lmdb格式

首先是在caffe-master/data/Mnist_image中新建一个create_filelist.sh脚本来生成训练和测试数据的标签文件(就是指定什么图片是什么类别的txt):

[python] view plain copy
  1. # !/usr/bin/env sh  
  2. DATA_TRAIN=../../data/Mnist_image/train #../使得能直接在这个目录运行create_filelist.sh  
  3. DATA_TEST=../../data/Mnist_image/test  
  4. MY=../../data/Mnist_image  
  5.   
  6. echo "Create train.txt..."  
  7. rm -rf $MY/train.txt #删除原有的train.txt,在重复生成train.txt的时候用到  
  8. for i in 0 1 2 3 4 5 6 7 8 9   
  9. do  
  10. find $DATA_TRAIN/$i/ -name *.png | cut -d '/' -f6-7 | sed "s/$/ $i/">>$MY/train.txt #以/为分隔符,截取第6-7段作为图片在train.txt中的名称,后面加上标签0~9中一个  
  11. done  
  12. echo "Create test.txt..."  
  13. rm -rf $MY/test.txt  
  14. for i in 0 1 2 3 4 5 6 7 8 9   
  15. do  
  16. find $DATA_TEST/$i/ -name *.png | cut -d '/' -f6-7 | sed "s/$/ $i/">>$MY/test.txt  
  17. done  
  18. echo "All done"  

解释-f6-7:

比如路径$DATA_TRAIN/$i/ -name *.png  = ../../data/Mnist_image/train/0/0_1.png,f6-7就是被/分隔开的第6段和第7段的内容:0/0_1.png

在此路径caffe-master/data/Mnist_image中运行:

[html] view plain copy
  1. create_filelist.sh  
就得到train.txt和test.txt文件:


下面是我的设置


#!/usr/bin/env sh
DATA=data/mnist/
MY=examples/myfile

echo "Create train.txt..."
rm -rf $MY/train.txt
for i in 0 1 2 3 4 5 6 7 8 9
do
find $DATA/train/$i/ -name *.png | cut -d '/' -f4-6 | sed "s/$/ $i/">>$MY/train.txt
done

echo "Create test.txt..."
rm -rf $MY/test.txt
for i in 0 1 2 3 4 5 6 7 8 9
do
find $DATA/test/$i/ -name *.png | cut -d '/' -f4-6 | sed "s/$/ $i/">>$MY/test.txt
done
echo "All done"

执行命令 一定要在data之前的文件夹执行,sudo sh 到createfile.sh


然后在caffe-master/examples中新建一个文件夹Mnist_image,在Mnist_image中新建脚本文件create_lmdb.sh:
[python] view plain copy
  1. #!/usr/bin/env sh  
  2. # Create the imagenet lmdb inputs  
  3. # N.B. set the path to the imagenet train + val data dirs  
  4. set -e  
  5.   
  6. EXAMPLE=../../examples/Mnist_image        #放得到的lmdb、训练得到的模型的路径  
  7. DATA=../../data/Mnist_image               #获取数据的路径,注意我们的mnist数据集中的图片都是单通道的(可以用python命令shape来看图片形状是(20,20),证明是单通道)  
  8. TOOLS=../..ild/tools                      #使用caffe的工具进行转换格式的路径  
  9.   
  10. TRAIN_DATA_ROOT=$DATA/train/              #根目录  
  11. TEST_DATA_ROOT=$DATA/test/  
  12.   
  13. rm $EXAMPLE/number_train_lmdb -rf  
  14. rm  $EXAMPLE/number_test_lmdb -rf  
  15.   
  16. # 这个不用了,数据集中的图像都是20*20  
  17. #Set RESIZE=true to resize the images to 256x256. Leave as false if images have  
  18. # already been resized using another tool.  
  19. RESIZE=true  
  20. if $RESIZE; then  
  21.   RESIZE_HEIGHT=20  
  22.   RESIZE_WIDTH=20  
  23. else  
  24.   RESIZE_HEIGHT=0  
  25.   RESIZE_WIDTH=0  
  26. fi  
  27.   
  28. if [ ! -d "$TRAIN_DATA_ROOT" ]; then  
  29.   echo "Error: TRAIN_DATA_ROOT is not a path to a directory: $TRAIN_DATA_ROOT"  
  30.   echo "Set the TRAIN_DATA_ROOT variable in create_imagenet.sh to the path" \  
  31.        "where the ImageNet training data is stored."  
  32.   exit 1  
  33. fi  
  34.   
  35. if [ ! -d "$TEST_DATA_ROOT" ]; then  
  36.   echo "Error: TEST_DATA_ROOT is not a path to a directory: $TEST_DATA_ROOT"  
  37.   echo "Set the TEST_DATA_ROOT variable in create_imagenet.sh to the path" \  
  38.        "where the ImageNet validation data is stored."  
  39.   exit 1  
  40. fi  
  41.   
  42. echo "Creating train lmdb..."  
  43.   
  44. GLOG_logtostderr=1 $TOOLS/convert_imageset \   #convert_imageaet的用法  
  45.     --resize_height=$RESIZE_HEIGHT \  
  46.     --resize_width=$RESIZE_WIDTH \  
  47.     --shuffle \  
  48.     --gray=true \                               #注意因为训练数据是灰度图,所以这里要令gray=true,默认是false,就会导致训练得到的lmdb是3通道的  
  49.     $TRAIN_DATA_ROOT \                          #根目录  
  50.     $DATA/train.txt \                           #train.txt的路径  
  51.     $EXAMPLE/number_train_lmdb                  #放生成的lmdb的路径  
  52.   
  53. echo "Creating val lmdb..."  
  54.   
  55. GLOG_logtostderr=1 $TOOLS/convert_imageset \  
  56.     --resize_height=$RESIZE_HEIGHT \  
  57.     --resize_width=$RESIZE_WIDTH \  
  58.     --shuffle \  
  59.     --gray=true \  
  60.     $TEST_DATA_ROOT\  
  61.     $DATA/test.txt \  
  62.     $EXAMPLE/number_test_lmdb  
  63.   
  64. echo "Done."  
然后在caffe-master/examples中新建一个文件夹Mnist_image,在Mnist_image中新建脚本文件create_lmdb.sh:


于是生成如上两个lmdb文件夹。

下面是我的设置

生成lmdb的代码,我调用的caffe里的convert_imageset区裁剪

MY=examples/myfile

echo "Create train lmdb.."
rm -rf $MY/img_train_lmdb
/home/hp/caffe/build/tools/convert_imageset \
--shuffle \
--resize_height=20 \
--resize_width=20 \
/home/hp/mytest/data/mnist/ \
$MY/train.txt \
$MY/img_train_lmdb

echo "Create test lmdb.."
rm -rf $MY/img_test_lmdb
/home/hp/caffe/build/tools/convert_imageset \
--shuffle \
--resize_width=20 \
--resize_height=20 \
/home/hp/mytest/data/mnist/ \
$MY/test.txt \
$MY/img_test_lmdb

echo "All Done.."

然后在mytest路径夏运行sh




3.计算均值并保存

图片减去均值再训练,会提高训练速度和精度。因此,一般都会有这个操作。 
caffe程序提供了一个计算均值的文件compute_image_mean.cpp,我们直接使用就可以了:

sudo build/tools/compute_image_mean examples/Mnist_image/number_train_lmdb examples/Mnist_image/mean.binaryproto
  • 1

生成均值文件 mean.binaryproto,但是好像默认的生成路径在根目录下。
下面是我的操作
sudo ../caffe/build/tools/compute_image_mean examples/myfile/img_train_lmdb examples/myfile/mean.binaryproto


4.创建模型并修改配置文件

这里为了统一我改了一下

模型就用caffe自带的caffenet模型,位置在 models/bvlc_reference_caffenet/文件夹下, 将需要的两个配置文件,复制到myfile文件夹内

# sudo cp ../caffe/models/bvlc_reference_caffenet/solver.prototxt examples/myfile/
# sudo cp ../caffe/models/bvlc_reference_caffenet/train_val.prototxt examples/myfile/
但是后来发现solver里面配置更改需要匹配,具体可参见我的solver及其配置讲解,这里暂时用下面的设置,后期我在完善其他命令。命令根据自己稍微修改,主要是路径问题

模型就用examples中自带的模型,位置在examples/mnist目录下, 将需要的两个配置文件lenet_solver.prototxt和lenet_train_val.prototxt,复制到examples/Mnist_image/目录下,更名为solver.prototxt和train_val.prototxt,打开solver.prototxt,只需修改两个路径,其他参数不用修改:?????????test?那train呢?

[html] view plain copy
  1. # The train/test net protocol buffer definition  
  2. net: "examples/Mnist_image/train_test.prototxt"                            #指定训练模型文件的位置  
  3. # test_iter specifies how many forward passes the test should carry out.  
  4. # In the case of MNIST, we have test batch size 100 and 100 test iterations,  
  5. # covering the full 10,000 testing images.  
  6. test_iter: 100  
  7. # Carry out testing every 500 training iterations.  
  8. test_interval: 500  
  9. # The base learning rate, momentum and the weight decay of the network.  
  10. base_lr: 0.01  
  11. momentum: 0.9  
  12. weight_decay: 0.0005  
  13. # The learning rate policy  
  14. lr_policy: "inv"  
  15. gamma: 0.0001  
  16. power: 0.75  
  17. # Display every 100 iterations  
  18. display: 100  
  19. # The maximum number of iterations  
  20. max_iter: 10000  
  21. # snapshot intermediate results  
  22. snapshot: 5000  
  23. snapshot_prefix: "examples/Mnist_image/caffenet_train"  
  24. # solver mode: CPU or GPU  
  25. solver_mode: GPU  
然后train_val.prototxt也只用修改一下路径,参数什么的都不用改。
根据自己不同路径修改,注意路径名和文件名不要写错。

[html] view plain copy
  1. name: "LeNet"  
  2. layer {  
  3.   name: "mnist"  
  4.   type: "Data"  
  5.   top: "data"  
  6.   top: "label"  
  7.   include {  
  8.     phase: TRAIN  
  9.   }  
  10.   transform_param {  
  11.     scale: 0.00390625  
  12.   }  
  13.   data_param {  
  14.     source: "examples/mnist/mnist_train_lmdb"  
  15.     batch_size: 64  
  16.     backend: LMDB  
  17.   }  
  18. }  
  19. layer {  
  20.   name: "mnist"  
  21.   type: "Data"  
  22.   top: "data"  
  23.   top: "label"  
  24.   include {  
  25.     phase: TEST  
  26.   }  
  27.   transform_param {  
  28.     scale: 0.00390625  
  29.   }  
  30.   data_param {  
  31.     source: "examples/mnist/mnist_test_lmdb"  
  32.     batch_size: 100  
  33.     backend: LMDB  
  34.   }  
  35. }  
  36. layer {  
  37.   name: "conv1"  
  38.   type: "Convolution"  
  39.   bottom: "data"  
  40.   top: "conv1"  
  41.   param {  
  42.     lr_mult: 1  
  43.   }  
  44.   param {  
  45.     lr_mult: 2  
  46.   }  
  47.   convolution_param {  
  48.     num_output: 20  
  49.     kernel_size: 5  
  50.     stride: 1  
  51.     weight_filler {  
  52.       type: "xavier"  
  53.     }  
  54.     bias_filler {  
  55.       type: "constant"  
  56.     }  
  57.   }  
  58. }  
  59. layer {  
  60.   name: "pool1"  
  61.   type: "Pooling"  
  62.   bottom: "conv1"  
  63.   top: "pool1"  
  64.   pooling_param {  
  65.     pool: MAX  
  66.     kernel_size: 2  
  67.     stride: 2  
  68.   }  
  69. }  
  70. layer {  
  71.   name: "conv2"  
  72.   type: "Convolution"  
  73.   bottom: "pool1"  
  74.   top: "conv2"  
  75.   param {  
  76.     lr_mult: 1  
  77.   }  
  78.   param {  
  79.     lr_mult: 2  
  80.   }  
  81.   convolution_param {  
  82.     num_output: 50  
  83.     kernel_size: 5  
  84.     stride: 1  
  85.     weight_filler {  
  86.       type: "xavier"  
  87.     }  
  88.     bias_filler {  
  89.       type: "constant"  
  90.     }  
  91.   }  
  92. }  
  93. layer {  
  94.   name: "pool2"  
  95.   type: "Pooling"  
  96.   bottom: "conv2"  
  97.   top: "pool2"  
  98.   pooling_param {  
  99.     pool: MAX  
  100.     kernel_size: 2  
  101.     stride: 2  
  102.   }  
  103. }  
  104. layer {  
  105.   name: "ip1"  
  106.   type: "InnerProduct"  
  107.   bottom: "pool2"  
  108.   top: "ip1"  
  109.   param {  
  110.     lr_mult: 1  
  111.   }  
  112.   param {  
  113.     lr_mult: 2  
  114.   }  
  115.   inner_product_param {  
  116.     num_output: 500  
  117.     weight_filler {  
  118.       type: "xavier"  
  119.     }  
  120.     bias_filler {  
  121.       type: "constant"  
  122.     }  
  123.   }  
  124. }  
  125. layer {  
  126.   name: "relu1"  
  127.   type: "ReLU"  
  128.   bottom: "ip1"  
  129.   top: "ip1"  
  130. }  
  131. layer {  
  132.   name: "ip2"  
  133.   type: "InnerProduct"  
  134.   bottom: "ip1"  
  135.   top: "ip2"  
  136.   param {  
  137.     lr_mult: 1  
  138.   }  
  139.   param {  
  140.     lr_mult: 2  
  141.   }  
  142.   inner_product_param {  
  143.     num_output: 10  
  144.     weight_filler {  
  145.       type: "xavier"  
  146.     }  
  147.     bias_filler {  
  148.       type: "constant"  
  149.     }  
  150.   }  
  151. }  
  152. layer {  
  153.   name: "accuracy"  
  154.   type: "Accuracy"  
  155.   bottom: "ip2"  
  156.   bottom: "label"  
  157.   top: "accuracy"  
  158.   include {  
  159.     phase: TEST  
  160.   }  
  161. }  
  162. layer {  
  163.   name: "loss"  
  164.   type: "SoftmaxWithLoss"  
  165.   bottom: "ip2"  
  166.   bottom: "label"  
  167.   top: "loss"  
  168. }  
5.训练

同样从位置在examples/mnist目录下, 复制lenet_train.sh到examples/Mnist_image目录,并更名为train.sh,修改路径:

[html] view plain copy
  1.  #!/usr/bin/env sh  
  2. set -e  
  3.   
  4. .build/tools/caffe train --solver=examples/Mnist_image/solver.prototxt $@ 
训练方法修改,用我的方法,调用caffe的可执行文件训练
sudo ../caffe/build/tools/caffe train -solver examples/myfile/solver.prototxt


然后在caffe-master目录运行 examples/Mnist_image/train_lenet.sh ,就会开始训练得到caffenet_train_iter_10000.caffemodel。整个训练过程就完了,最后就是为了得到这个caffemodel模型。下面尝试对任意一张图片使用这个caffemodel进行测试,看是否准确。
6.使用deploy.py生成deploy.prototxt
examples/Mnist_image目录下新建deploy.py:
设置不同,命令不同,下面是我的层序

# -*- coding: utf-8 -*-
caffe_root = '/home/hp/mytest/examples/myfile/'    
import sys    
sys.path.insert(0, caffe_root + 'python')    
from caffe  import layers as L,params as P,to_proto  
root='/home/hp/mytest/examples/myfile/'  
deploy='/home/hp/mytest/examples/myfile/deploy.prototxt'    #文件保存路径  
      
def create_deploy():  
        #少了第一层,data层  
        conv1=L.Convolution(name='conv1',bottom='data', kernel_size=5, stride=1,num_output=20, pad=0,weight_filler=dict(type='xavier'))  
        pool1=L.Pooling(conv1,name='pool1',pool=P.Pooling.MAX, kernel_size=2, stride=2)  
        conv2=L.Convolution(pool1, name='conv2',kernel_size=5, stride=1,num_output=50, pad=0,weight_filler=dict(type='xavier'))  
        pool2=L.Pooling(conv2, name='pool2',top='pool2', pool=P.Pooling.MAX, kernel_size=2, stride=2)  
        fc3=L.InnerProduct(pool2, name='ip1',num_output=500,weight_filler=dict(type='xavier'))  
        relu3=L.ReLU(fc3, name='relu1',in_place=True)  
        fc4 = L.InnerProduct(relu3, name='ip2',num_output=10,weight_filler=dict(type='xavier'))  
        #最后没有accuracy层,但有一个Softmax层  
        prob=L.Softmax(fc4, name='prob')  
        return to_proto(prob)  
def write_deploy():   
        with open(deploy, 'w') as f:  
            f.write('name:"LeNet"\n')  
            f.write('layer {\n')  
            f.write('name:"data"\n')  
            f.write('type:"Input"\n')  
            f.write('input_param { shape : {')  
            f.write('dim:1 ')  
            f.write('dim:3 ')  
            f.write('dim:28 ')  
            f.write('dim:28 ')  
            f.write('} }\n\n')  
            f.write(str(create_deploy()))  
if __name__ == '__main__':  
        write_deploy() 

注意python一定要对其阿,缩进,不然报错


改完错误之后生成了deploy.prototxt


[html] view plain copy
  1. # -*- coding: utf-8 -*-  
  2. caffe_root = '/home/cvlab01/2016liulu/caffe-master/'    
  3. import sys    
  4. sys.path.insert(0, caffe_root + 'python')    
  5. from caffe  import layers as L,params as P,to_proto  
  6. root='/home/cvlab01/2016liulu/caffe-master/'  
  7. deploy='/home/cvlab01/2016liulu/caffe-master/examples/Mnist_image/deploy.prototxt'    #文件保存路径  
  8.   
  9. def create_deploy():  
  10.     #少了第一层,data层  
  11.     conv1=L.Convolution(name='conv1',bottom='data'kernel_size=5stride=1,num_output=20pad=0,weight_filler=dict(type='xavier'))  
  12.     pool1=L.Pooling(conv1,name='pool1',pool=P.Pooling.MAX, kernel_size=2stride=2)  
  13.     conv2=L.Convolution(pool1, name='conv2',kernel_size=5stride=1,num_output=50pad=0,weight_filler=dict(type='xavier'))  
  14.     pool2=L.Pooling(conv2, name='pool2',top='pool2'pool=P.Pooling.MAX, kernel_size=2stride=2)  
  15.     fc3=L.InnerProduct(pool2, name='ip1',num_output=500,weight_filler=dict(type='xavier'))  
  16.     relu3=L.ReLU(fc3, name='relu1',in_place=True)  
  17.     fc4 = L.InnerProduct(relu3, name='ip2',num_output=10,weight_filler=dict(type='xavier'))  
  18.     #最后没有accuracy层,但有一个Softmax层  
  19.     prob=L.Softmax(fc4, name='prob')  
  20.     return to_proto(prob)  
  21. def write_deploy():   
  22.     with open(deploy, 'w') as f:  
  23.         f.write('name:"LeNet"\n')  
  24.         f.write('layer {\n')  
  25.         f.write('name:"data"\n')  
  26.         f.write('type:"Input"\n')  
  27.         f.write('input_param { shape : {')  
  28.         f.write('dim:1 ')  
  29.         f.write('dim:3 ')  
  30.         f.write('dim:28 ')  
  31.         f.write('dim:28 ')  
  32.         f.write('} }\n\n')  
  33.         f.write(str(create_deploy()))  
  34. if __name__ == '__main__':  
  35.     write_deploy()  
运行deploy.py生成的deploy.prototxt如下:
[html] view plain copy
  1. name: "LeNet"   
  2. layer {  
  3.   name: "data"  
  4.   type: "Input"  
  5.   top: "data"  
  6.   input_param { shape: { dim: 1 dim: 1 dim: 20 dim: 20 } }#灰度图像,dim为1,不能弄错了  
  7. }  
  8. #/*卷积层与全连接层中的权值学习率,偏移值学习率,偏移值初始化方式,因为这些值在caffemodel文件中已经提供*/  
  9. layer {  
  10.   name: "conv1"  
  11.   type: "Convolution"  
  12.   bottom: "data"  
  13.   top: "conv1"  
  14.   convolution_param {  
  15.     num_output: 20  
  16.     kernel_size: 5  
  17.     stride: 1  
  18.     weight_filler {  
  19.       type: "xavier"  
  20.     }  
  21.   }  
  22. }  
  23. layer {  
  24.   name: "pool1"  
  25.   type: "Pooling"  
  26.   bottom: "conv1"  
  27.   top: "pool1"  
  28.   pooling_param {  
  29.     pool: MAX  
  30.     kernel_size: 2  
  31.     stride: 2  
  32.   }  
  33. }  
  34. layer {  
  35.   name: "conv2"  
  36.   type: "Convolution"  
  37.   bottom: "pool1"  
  38.   top: "conv2"  
  39.   convolution_param {  
  40.     num_output: 50  
  41.     kernel_size: 5  
  42.     stride: 1  
  43.     weight_filler {  
  44.       type: "xavier"  
  45.     }  
  46.   }  
  47. }  
  48. layer {  
  49.   name: "pool2"  
  50.   type: "Pooling"  
  51.   bottom: "conv2"  
  52.   top: "pool2"  
  53.   pooling_param {  
  54.     pool: MAX  
  55.     kernel_size: 2  
  56.     stride: 2  
  57.   }  
  58. }  
  59. layer {  
  60.   name: "ip1"  
  61.   type: "InnerProduct"  
  62.   bottom: "pool2"  
  63.   top: "ip1"  
  64.   inner_product_param {  
  65.     num_output: 500  
  66.     weight_filler {  
  67.       type: "xavier"  
  68.     }  
  69.   }  
  70. }  
  71. layer {  
  72.   name: "relu1"  
  73.   type: "ReLU"  
  74.   bottom: "ip1"  
  75.   top: "ip1"  
  76. }  
  77. layer {  
  78.   name: "ip2"  
  79.   type: "InnerProduct"  
  80.   bottom: "ip1"  
  81.   top: "ip2"  
  82.   inner_product_param {  
  83.     num_output: 10  
  84.     weight_filler {  
  85.       type: "xavier"  
  86.     }  
  87.   }  
  88. }  
  89.   
  90. #/*删除了原有的测试模块的测试精度层*/  
  91.   
  92. #/*输出层的类型由SoftmaxWithLoss变成Softmax,训练是输出时是loss,应用时是prob。*/  
  93. layer {  
  94.   name: "prob"  
  95.   type: "Softmax"  
  96.   bottom: "ip2"  
  97.   top: "prob"  
  98. }  
7.准备均值文件 meanfile.npy和synset_words.txt

因为classify.py中的测试接口caffe.Classifier需要训练图片的均值文件作为输入参数,而实际lenet-5训练时并未计算均值文件,所以这里创建一个全0的均值文件输入。编写一个zeronp.py文件如下 
这里写图片描述
执行

python zeronp.py
  • 1
  • 1

生成均值文件 meanfile.npy。 

在examples/Mnist_image中新建synset_words.txt:

[html] view plain copy
  1. 0 zero  
  2. 1 one  
  3. 2 two  
  4. 3 three  
  5. 4 four  
  6. 5 five  
  7. 6 six  
  8. 7 seven  
  9. 8 eight  
  10. 9 nine  
8. 修改classify.py保存为classifymnist.py文件
在目录caffe-master/python中有classify.py文件,复制一份并改名为classifymnist.py然后进行如下修改:
[html] view plain copy
  1. #!/usr/bin/env python  
  2. #coding:utf-8  
  3. """  
  4. classify.py is an out-of-the-box image classifer callable from the command line.  
  5.   
  6. By default it configures and runs the Caffe reference ImageNet model.  
  7. """  
  8. caffe_root = '/home/cvlab01/2016liulu/caffe-master/'    
  9. import sys    
  10. sys.path.insert(0, caffe_root + 'python')    
  11.   
  12. import numpy as np  
  13. import os  
  14. import sys  
  15. import argparse  
  16. import glob  
  17. import time  
  18. import pandas as pd #插入数据分析包  
  19.   
  20. import caffe  
  21.   
  22.   
  23. def main(argv):  
  24.     pycaffe_dir = os.path.dirname(__file__)  
  25.   
  26.     parser = argparse.ArgumentParser()  
  27.     # Required arguments: input and output files.  
  28.     parser.add_argument(  
  29.         "input_file",  
  30.         help="Input image, directory, or npy."  
  31.     )  
  32.     parser.add_argument(  
  33.         "output_file",  
  34.         help="Output npy filename."  
  35.     )  
  36.     # Optional arguments.  
  37.     parser.add_argument(  
  38.         "--model_def",  
  39.         default=os.path.join(pycaffe_dir,  
  40.                 "../examples/Mnist_image/deploy.prototxt"), #指定deploy.prototxt的模型位置  
  41.         help="Model definition file."  
  42.     )  
  43.     parser.add_argument(  
  44.         "--pretrained_model",  
  45.         default=os.path.join(pycaffe_dir,  
  46.                 "../examples/Mnist_image/caffenet_train_iter_10000.caffemodel"), #指定caffemodel模型位置,这就是我们前面自己训练得到的模型  
  47.         help="Trained model weights file."  
  48.     )  
  49.     #######新增^^^^^^^^^start^^^^^^^^^^^^^^^^^^^^^^  
  50.     parser.add_argument(  
  51.         "--labels_file",  
  52.         default=os.path.join(pycaffe_dir,  
  53.                 "../examples/Mnist_image/synset_words.txt"), #指定输出结果对应的类别名文件???????????????????????????  
  54.         help="mnist result words file"  
  55.     )  
  56.     parser.add_argument(  
  57.         "--force_grayscale",  
  58.         action='store_true',   #增加一个变量将输入图像强制转化为灰度图,因为lenet-5训练用的就是灰度图  
  59.         help="Converts RGB images down to single-channel grayscale versions," +  
  60.                    "useful for single-channel networks like MNIST."  
  61.     )  
  62.     parser.add_argument(  
  63.         "--print_results",  
  64.         action='store_true', #输入参数要求打印输出结果  
  65.         help="Write output text to stdout rather than serializing to a file."  
  66.     )  
  67.     #######新增^^^^^^^^^end^^^^^^^^^^^^^^^^^^^^^^  
  68.     parser.add_argument(  
  69.         "--gpu",  
  70.         action='store_true',  
  71.         help="Switch for gpu computation."  
  72.     )  
  73.     parser.add_argument(  
  74.         "--center_only",  
  75.         action='store_true',  
  76.         help="Switch for prediction from center crop alone instead of " +  
  77.              "averaging predictions across crops (default)."  
  78.     )  
  79.     parser.add_argument(  
  80.         "--images_dim",  
  81.         default='20,20', #指定图像寬高  
  82.         help="Canonical 'height,width' dimensions of input images."  
  83.     )  
  84.     parser.add_argument(  
  85.         "--mean_file",  
  86.         default=os.path.join(pycaffe_dir,  
  87.                              '../examples/Mnist_image/meanfile.npy'), #指定均值文件  
  88.         help="Data set image mean of [Channels x Height x Width] dimensions " +  
  89.              "(numpy array). Set to '' for no mean subtraction."  
  90.     )  
  91.     parser.add_argument(  
  92.         "--input_scale",  
  93.         type=float,  
  94.         help="Multiply input features by this scale to finish preprocessing."  
  95.     )  
  96.     parser.add_argument(  
  97.         "--raw_scale",  
  98.         type=float,  
  99.         default=255.0,  
  100.         help="Multiply raw input by this scale before preprocessing."  
  101.     )  
  102.     parser.add_argument(  
  103.         "--channel_swap",  
  104.         default='2,1,0',  
  105.         help="Order to permute input channels. The default converts " +  
  106.              "RGB -> BGR since BGR is the Caffe default by way of OpenCV."  
  107.     )  
  108.     parser.add_argument(  
  109.         "--ext",  
  110.         default='jpg',  
  111.         help="Image file extension to take as input when a directory " +  
  112.              "is given as the input file."  
  113.     )  
  114.     args = parser.parse_args()  
  115.   
  116.     image_dims = [int(s) for s in args.images_dim.split(',')]  
  117.   
  118.     mean, channel_swap = None, None  
  119.     if args.mean_file:  
  120.         mean = np.load(args.mean_file).mean(1).mean(1)  
  121.     if args.channel_swap:  
  122.         channel_swap = [int(s) for s in args.channel_swap.split(',')]  
  123.   
  124.     if args.gpu:  
  125.         caffe.set_mode_gpu()  
  126.         print("GPU mode")  
  127.     else:  
  128.         caffe.set_mode_cpu()  
  129.         print("CPU mode")  
  130.   
  131.     # Make classifier.  
  132.     classifier = caffe.Classifier(args.model_def, args.pretrained_model,  
  133.             image_dims=image_dimsmean=mean,  
  134.             input_scale=args.input_scale, raw_scale=args.raw_scale,  
  135.             channel_swap=None)  
  136.   
  137.     # Load numpy array (.npy), directory glob (*.jpg), or image file.  
  138.     args.input_file = os.path.expanduser(args.input_file)  
  139.     if args.input_file.endswith('npy'):  
  140.         print("Loading file: %s" % args.input_file)  
  141.         inputs = np.load(args.input_file)  
  142.     elif os.path.isdir(args.input_file):  
  143.         print("Loading folder: %s" % args.input_file)  
  144.         inputs =[caffe.io.load_image(im_f)  
  145.                  for im_f in glob.glob(args.input_file + '/*.' + args.ext)]  
  146.     else:  
  147.         print("Loading file: %s" % args.input_file)  
  148.         inputs = [caffe.io.load_image(args.input_file,not args.force_grayscale)] #强制图片为灰度图  
  149.   
  150.     print("Classifying %d inputs." % len(inputs))  
  151.   
  152.     # Classify.  
  153.     start = time.time()  
  154.     scores = classifier.predict(inputs, not args.center_only).flatten()  
  155.     print("Done in %.2f s." % (time.time() - start))  
  156.           
  157.     #增加输出结果打印到终端^^^start^^^^^  
  158.     # print  
  159.     if args.print_results:  
  160.         with open(args.labels_file) as f:  
  161.             labels_df = pd.DataFrame([{'synset_id':l.strip().split(' ')[0], 'name': ' '.join(l.strip().split(' ')[1:]).split(',')[0]} for l in f.readlines()])  
  162.             labels = labels_df.sort('synset_id')['name'].values  
  163.   
  164.             indices =(-scores).argsort()[:5]  
  165.             predictions = labels[indices]  
  166.             print predictions  
  167.             print scores  
  168.   
  169.             meta = [(p, '%.5f' % scores[i]) for i,p in zip(indices, predictions)]  
  170.             print meta  
  171.     #增加输出结果打印到终端vvvvendvvvvvvv  
  172.   
  173.               
  174.     # Save  
  175.     print("Saving results into %s" % args.output_file)  
  176.     np.save(args.output_file, predictions)  
  177.   
  178.   
  179. if __name__ == '__main__':  
  180.     main(sys.argv)    
  181.         
8.测试,在classifymnist.py目录下准备一个灰度图像3.jpg,大小和mnist中一样,然后执行:
[html] view plain copy
  1. python classifymnist.py --print_results --force_grayscale --center_only --labels_file ../examples/Mnist_image/synset_words.txt ../examples/Mnist_image/3.jpg resultsfile  

借鉴了http://blog.csdn.net/lanxuecc/article/details/52485077的博主一系列的文章,表示感谢,这里只是自己记录学习过程,如果侵权,很抱歉




  • fafds23
    fafds23 2018-03-01 17:41:44 #2楼
    mnist数据集不是28*28的图片吗,怎么变成20*20了
  • 上一页
  • 1
  • 下一页
27岁银川妹子竟悟出股市投资铁律,爆赚成网红 瓦普 · 顶新
27岁银川妹子竟悟出股市投资铁律,爆赚成网红 铭彪 · 顶新
undefined


  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值