參考
- 官方關(guān)于PythonLayer的使用示例
- 關(guān)于PythonLayer的說明
- 關(guān)于如何添加自定義
Module到PYTHONPATH - Caffe(二)使用Python運(yùn)用caffemodel進(jìn)行mnist數(shù)據(jù)集預(yù)測(cè)
識(shí)別效果

遮擋識(shí)別效果
左側(cè)為輸入圖像,其中隨機(jī)1/4被遮擋,右側(cè)圖形為對(duì)應(yīng)的原圖像。
訓(xùn)練過程
參考官方關(guān)于PythonLayer的使用示例,首先創(chuàng)建PythonLayer腳本,代碼為 :
# -*- coding:utf-8 -*-
# Modified: NoneLand
import caffe
import random
class BlankSquareLayer(caffe.Layer):
def setup(self, bottom, top):
assert len(bottom) == 1, "Requires a single layer.bottom"
assert bottom[0].data.ndim >= 3, "Requires image data"
assert len(top) == 1, "Requires a single layer.top"
def reshape(self, bottom, top):
top[0].reshape(*bottom[0].data.shape)
def forward(self, bottom, top):
top[0].data[...] = bottom[0].data[...]
height, width = top[0].data.shape[-2], top[0].data.shape[-1]
h_offset, w_offset = random.randrange(height/2), random.randrange(width/2)
top[0].data[..., h_offset:h_offset+height, w_offset:width+w_offset] = 0
def backward(self, top, propagate_down, bottom):
pass
理解以上代碼除了需要對(duì)caffe的結(jié)構(gòu)有一定了解,關(guān)于numpy的用法如下:

numpy dots usage

np.zeros_like() func
然后修改CAFFEROOT/examples/mnist目錄下的lenet_train_test.prototxt文件,在mnist和conv1兩層之間加入以下
layer {
name: "blank_square"
type: "Python"
bottom: "data"
top: "data"
python_param{
module: "pythonLayerTest" # 上述PythonLayer的文件名,其所在路徑需添加到PYTHONPATH中
layer: "BlankSquareLayer" # 定義的PythonLayer類
}
# 以下三行用于控制該層的使用情況
#include {
# phase: TRAIN
#}
}
其中,添加到PYTHONPATH參考參考部分鏈接3。修改之后的網(wǎng)絡(luò)結(jié)構(gòu)如下圖所示

lenetOclude網(wǎng)絡(luò)結(jié)構(gòu)
然后使用./examples/mnist/train_lenet.sh就可以進(jìn)行訓(xùn)練了。
注意:以上直接修改文件的做法會(huì)影響原來
lenet的網(wǎng)絡(luò)結(jié)構(gòu),建議復(fù)制文檔,然后再修改。修改完之后,再復(fù)制一份lenet_solver.prototxt并重命名,并將net:參數(shù)指向修改的網(wǎng)絡(luò)模型文件。在CAFFEROOT目錄下使用./build/tools//caffe train --solver=examples/mnist/lenetOclude_solver.prototxt $@進(jìn)行訓(xùn)練。
訓(xùn)練結(jié)果顯示,不使用遮擋的測(cè)試準(zhǔn)確率在95%左右,而使用遮擋的測(cè)試準(zhǔn)確率為60%左右,這與隨機(jī)有關(guān)。這從之前的識(shí)別效果圖中也可以看出。