caffe添加自己编写的Python层

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}"
  }
}

3. 结果

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值