注意:包含Python层的网络只支持单个GPU训练!!!!!
Caffe 使得我们有了使用Python自定义层的能力,而不是通常的C++/CUDA。这是一个非常有用的特性,但它的文档记录不足,难以正确实现本演练将向您展示如何使用DIGHT来学习实现Python层。
注意:这个特性(自定义python层)在你是使用Cmake编译Caffe或者使用Deb 包来安装Caffe的时候自动被包含。如果你使用Make,你将需要将你的Makefile.config中的"WITH_PYTHON_LAYER := 1"解注释来启用它。
给MNIST添加遮挡
对于这个例子,我们将在MNIST数据集上训练LeNet,但是我们将建立一个python层,来实现在图片喂进网络之前,截取掉它的四分之一。这模拟遮挡的数据,这样将会训练出一个对遮挡更加鲁棒的模型。
比如
变成
创建数据集
首先,仿照这个教程(https://github.com/NVIDIA/DIGITS/blob/master/docs/GettingStarted.md#creating-a-dataset)来使用DIGITS创建MNIST数据集(假设你还没有创建)
创建Python文件
接下来你将创建一个包含你的Pyhon层定义的Python文件。打开一个文本编辑器,然后创建一个包含如下内容的文件。
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): # Copy shape from bottom top[0].reshape(*bottom[0].data.shape) def forward(self, bottom, top): # Copy all of the data top[0].data[...] = bottom[0].data[...] # Then zero-out one fourth of the image height = top[0].data.shape[-2] width = top[0].data.shape[-1] h_offset = random.randrange(height/2) w_offset = random.randrange(width/2) top[0].data[..., h_offset:(h_offset + height/2), w_offset:(w_offset + width/2), ] = 0 def backward(self, top, propagate_down, bottom): pass
其中,top和bottom是包含一个或者多个blob的列表或者数组,访问其中的每一个blob使用下标index,如top[index],访问其中的数据使用top[index].data,也就是一个四维向量[N,C,H,W]。

