让我们通过一个实际的例子来体验一下如何在windows环境下使用caffe进行自定义网络层的开发。
首先,我们需要设置环境变量$PYTHONPATH。我在Windows开发环境中使用的是Windows PowerShell。如果您还没有编译Windows版本的Caffe,请自行解决。
添加环境变量的代码如下:
$env:PYTHONPATH="F:\caffe-python\python\;F:\caffe-windows\windows\install\python"
这里,F:\caffe-python\python 是我的新Layer的路径,而 F:\caffe-windows\windows\install\python 是我编译后的Caffe的安装路径。
接下来,我们编写自己的自定义Layer,称为TestLayer:
立即学习“Python免费学习笔记(深入)”;
import caffe import numpy as npclass TestLayer(caffe.Layer): def setup(self, bottom, top): if len(bottom) != 1: raise Exception("Need one input to process.")
def reshape(self, bottom, top): print("-----------------1---------------------") top[0].reshape(1) def forward(self, bottom, top): top[0].data[...] = bottom[0].data print("-----------------2---------------------") def backward(self, top, propagate_down, bottom): bottom[0].diff[...] = top[0].data pass接下来,我们看一个官方提供的示例层,即
EuclideanLossLayer,以便进行比较:import caffeimport numpy as np
class EuclideanLossLayer(caffe.Layer): def setup(self, bottom, top): if len(bottom) != 2: raise Exception("Need two inputs to compute distance.")
def reshape(self, bottom, top): if bottom[0].count != bottom[1].count: raise Exception("Inputs must have the same dimension.") self.diff = np.zeros_like(bottom[0].data, dtype=np.float32) top[0].reshape(1) def forward(self, bottom, top): self.diff[...] = bottom[0].data - bottom[1].data top[0].data[...] = np.sum(self.diff**2) / bottom[0].num / 2. def backward(self, top, propagate_down, bottom): for i in range(2): if not propagate_down[i]: continue if i == 0: sign = 1 else: sign = -1 bottom[i].diff[...] = sign * self.diff / bottom[i].num完成Layer的编写后,我们需要定义网络结构:
name: "TEST"layer { name: "cifar" type: "Data" top: "data" top: "label" include { phase: TRAIN } transform_param { mean_file: "examples/cifar10/Release/cifar10/mean.binaryproto" } data_param { source: "examples/cifar10/Release/cifar10/cifar10_train_lmdb" batch_size: 100 backend: LMDB } } layer { name: "cifar" type: "Data" top: "data" top: "label" include { phase: TEST } transform_param { mean_file: "examples/cifar10/Release/cifar10/mean.binaryproto" } data_param { source: "examples/cifar10/Release/cifar10/cifar10_test_lmdb" batch_size: 100 backend: LMDB } } layer { name: "test1" type: "Python" bottom: "data" top: "test1" python_param { module: "test_layer" layer: "Test_Layer" } }
可视化后的网络结构如下图所示:
多奥淘宝客程序API免费版 F8.0下载多奥淘宝客程序免费版拥有淘宝客站点的基本功能,手动更新少,管理简单等优点,适合刚接触网站的淘客们,或者是兼职做淘客们。同样拥有VIP版的模板引擎技 术、强大的文件缓存机制,但没有VIP版的伪原创跟自定义URL等多项创新的搜索引擎优化技术,除此之外也是一款高效的API数据系统实现无人值守全自动 化运行的淘宝客网站程序。4月3日淘宝联盟重新开放淘宝API申请,新用户也可使用了
接下来,我们编写solver文件:
net: "F:/caffe-python/python/test_layer.prototxt" base_lr: 0.001 lr_policy: "fixed" max_iter: 10 solver_mode: CPU然后,我们在PowerShell中启动Caffe。首先,切换到Caffe所在的目录,我的目录是这样的:
cd F:\Smart_Classroom\3rdparty\ALLPLATHFORM\caffe-windows\windows\examples\cifar10\Release然后执行Caffe:
./caffe.exe train --solver=F:/caffe-python/python/test_python_layer_solver.prototxt执行结果如下图所示:
在前向和后向传播过程中,我们成功调用了两个
注意:编写时请严格注意路径,否则可能会出现如下错误:













