深度學習框架Caffe學習筆記(6)-測試自己的手寫數字圖片
阿新 • • 發佈:2019-02-15
在之前的實驗中我們使用過
$ ./build/tools/caffe.bin test \
-model examples/mnist/lenet_train_test.prototxt \
-weights examples/mnist/lenet_iter_10000.caffemodel \
-iterations 100
命令來測試訓練好的網路。這主要用於測試網路的準確率。
但如想用自己的手寫數字,通過訓練好的模型來識別這個數字,怎麼做呢?
可以使用Caffe中build/examples/cpp_classification/classification.bin這個程式來實現。
$ ./build/examples/cpp_classification/classification.bin
Usage: ./build/examples/cpp_classification/classification.bin
deploy.prototxt // 模型描述檔案
network.caffemodel // 模型權值檔案
mean.binaryproto // 影象均值檔案
labels.txt // 影象類別標籤資訊
img.jpg // 輸入待分類影象
接下來開始準備這幾個檔案
模型描述檔案
將lenet_train_test.prototxt複製一份修改如下
// 將訓練和測試用的mnist層刪除,新增以下層
name: "LeNet"
layer {
name: "data"
type: "Input"
top: "data"
input_param { shape: { dim: 1 dim: 1 dim: 28 dim: 28 } }
}
......
// 中間的模型不改動,省略
......
// 將accuracy層和loss層刪除,新增以下層
layer {
name: "prob"
type: "Softmax"
bottom: "ip2"
top: "prob"
}
權值描述檔案
訓練好網路後examples/mnist/目錄下就會會有lenet_iter_10000.caffemodel這個檔案。
影象均值檔案
Caffe框架為我們提供了一個計算均值的檔案compute_image_mean.cpp,放在caffe根目錄下的tools資料夾裡面。編譯後的可執行體放在 build/tools/ 下面,我們直接呼叫就可以了
$ sudo build/tools/compute_image_mean examples/mnist/mnist_train_lmdb examples/mnist/mean.binaryproto
帶兩個引數:
第一個引數:examples/mnist/mnist_train_lmdb, 表示需要計算均值的資料,格式為lmdb的訓練資料。
第二個引數:examples/mnist/mean.binaryproto, 計算出來的結果儲存檔案。
標籤檔案
新建label.txt,每行一個數字,0到9。
0
1
2
3
4
5
6
7
8
9
輸入待分類影象
這個自己拿畫圖工具畫一個就好。由於訓練集中的資料都是黑底白字的,所以如果自己寫是是白底黑字的圖片可能識別不準確。
開始測試
$ ./build/examples/cpp_classification/classification.bin \
examples/mnist/classificat_net.prototxt \
examples/mnist/lenet_iter_10000.caffemodel \
examples/mnist/mean.binaryproto examples/mnist/label.txt \
examples/mnist/0.png
---------- Prediction for examples/mnist/0.png ----------
1.0000 - "0"
0.0000 - "1"
0.0000 - "3"
0.0000 - "4"
0.0000 - "2"
結果顯示圖片中的數字為0。