1. 前言
由于Python的灵活性,我们在caffe中添加自己定义的层时使用python层会更加方便,开发速速也会比C++更快,要使用python层需要编译caffe的时候打开python接口:
WITH_PYTHON_LAYER:=1
这里使用一个实现一个简单caffe python module:Data_Process作为实验,其添加过程在后面的内容中介绍。
2. 实现
2.1 module Python脚本
编写module的python脚本,其格式如下:
# -*- coding=utf-8 -*-
# add caffe python layer demo
import numpy as np
import yaml
import sys
sys.path.insert(0, '../codes/caffe/python')
import caffe
# model class
class Data_Process(caffe.Layer):
def setup(self, bottom, top):
# parse the layer parameter string, which must be valid YAML
layer_params = yaml.load(self.param_str)
# two method get params
self.alpha = layer_params['alpha']
self.beta = layer_params.get('beta', 0)
print('Data_process Layer param:\n alpha:{}, beta:{}'.format(self.alpha, self.beta))
def reshape(self, bottom, top):
top[0].reshape(*bottom[0].shape)
def forward(self, bottom, top):
top[0].data[...] = self.alpha*bottom[0].data[...] + self.beta
def backward(self, bottom, top):
pass
2.2 网络定义
# add python layer
layer {
name: "python_layer_demo"
type: "Python"
bottom: "Data1"
top: "Data1_process"
python_param {
module: 'python_module.python_module_demo'
layer: 'Data_Process'
param_str: "{'alpha': 1.01, 'beta': 0.5}"
}
}