Caffe通过Boost中的Boost.Python模块来支持使用Python定义Layer:
- 使用C++增加新的Layer繁琐、耗时而且很容易出错
- 开发速度与执行速度之间的trade-off
编译支持Python Layer的Caffe
进入caffe 的root路径
1.修改Caffe根目录下的Makefile.cinfig
uncomment
WITH_PYTHON_LAYER:=1
2.编译
如果没有编译过:
mkdir build
cd build
cmake ..
make all & make pycaffe
如果已经编译过:
make clean
mkdir build
cd build
cmake ..
make all & make pycaffe
例如现在需要编译以下的tripletloss:
#add activation layer may increase the feature's expression
layer {
name: "triplet_select"
type: "Python"
bottom: "fc9_1"
bottom: "labels"
top: "archor"
top: "positive"
top: "negative"
python_param {
module: "tripletselectlayer"
layer: "TripletSelectLayer"
}
}
layer {
name: "tripletloss"
type: "Python"
bottom: "archor"
bottom: "positive"
bottom: "negative"
top: "loss"
python_param {
module: "tripletlosslayer"
layer: "TripletLayer"
param_str: "'margin': 0.2"
}
loss_weight: 1
}
需要将tripletloss 对应的py文件(https://github.com/lemonaha/tripletloss/tree/master/tripletloss)放到 $PYTHONPATH 对应的目录下
原理浅析
阅读caffe源码pythonlayer.hpp可以知道,类PythonLayer继承自Layer,并且新增私有变量boost::python::object self来表示我们自己定义的python layer的内存对象。
类PythonLayer类的成员函数LayerSetUP, Reshape, Forward_cpu和Backward_cpu分别是对我们自己定义的python layer中成员函数setup, reshape, forward和backward的封装调用。
参考链接:http://withwsf.github.io/2016/04/14/Caffe-with-Python-Layer/
进一步了解使用C++创建新的layer:
https://chrischoy.github.io/research/making-caffe-layer/
tripletloss 原理以及梯度推导
triplet是一个三元组,这个三元组是这样构成的:从训练数据集中随机选一个样本,该样本称为Anchor,然后再随机选取一个和Anchor (记为x_a)属于同一类的样本和不同类的样本,这两个样本对应的称为Positive (记为x_p)和Negative (记为x_n),由此构成一个(Anchor,Positive,Negative)三元组。
具体推导过程:http://www.voidcn.com/blog/tangwei2014/article/p-4415770.html
caffe中增加layer 的c++实现:
http://www.voidcn.com/blog/mao_kun/article/p-6246924.html