网上关于caffe的python layer基本是基于ubuntu系统下的,因此特意写一篇关于WINDOWS系统下添加python layer的blog。
- 电脑配置
系统:WIN7
caffe版本:happynear的caffe-windows-ms
visual studio:2015
以caffe中自带的文件作为例子,这个是Python layer的python文件,文件路径:
- Python layer的python文件内容
- 文件名:ployss.py
- 类名:EuclideanLossLayer
import caffe
import numpy as np
#EuclideanLossLayer是定义的一个类名
class EuclideanLossLayer(caffe.Layer):
"""
Compute the Euclidean Loss in the same manner as the C++ EuclideanLossLayer
to demonstrate the class interface for developing layers in Python.
"""
def setup(self, bottom, top):
# check input pair
if len(bottom) != 2:
raise Exception("Need two inputs to compute distance.")
def reshape(self, bottom, top):
# check input dimensions match
if bottom[0].count != bottom[1].count:
raise Exception("Inputs must have the same dimension.")
# difference is shape of inputs
self.diff = np.zeros_like(bottom[0].data, dtype=np.float32)
# loss output is scalar
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
注意:在这个python文件中
setup( ): 用于检查输入的参数是否存在异常,初始化的功能.
reshape( ): 也是初始化,设定一下参数的size
forward( ): 前向传播
backward( ): 反向传播
是需要重新定义,若有除这个以外的其他部分也可以自行定义。
- python文件存放在哪?
打开网络结构prototxt文件
文件路径:
在里面找到python层
其中
module:“pyloss”就是python的文件名(pyloss.py),只要写名字,不要加‘.py’或文件路径
layer:“EuclideanLossLayer”是python文件中的类名
在这里可以看到明确显示刚刚写的python文件要放在哪里:that needs to be in $PYTHONPATH
也就是要放在PYTHON的路径下面,接着可以利用CMD->输入where python的到python的路径,然后把python文件放到该路径下就可以了。
写好相对应的solver.prototxt文件,运行.bat文件就完成了!