caffe 10 win10 使用python自定义层

01 python自定义层

可以通过caffe的python接口实现自定义层。需要实现setup、reshape、forward、backward四个接口。python的类名作为层定义。python的文件名称作为模块定义

# customlayer.py # 自定义层python实现
import sys
# 因为用到了caffe.Layer,所以要引入caffe接口
caffe_root='D:/git/DeepLearning/caffe/build/x64/install/'
sys.path.insert(0, caffe_root+'python')
import caffe
import yaml

# 类名称MyLayer就是网络定义文件需要的layer: 'MyLayer'名字
# 自定义layer需要实现 setup reshape forward backward四个接口
class MyLayer(caffe.Layer):

  def setup(self, bottom, top):
    self.num = yaml.load(self.param_str)["num"]
    #print("parameter num: ", self.num)

  def reshape(self, bottom, top):
    pass

  def forward(self, bottom, top):
    top[0].reshape(*bottom[0].shape)
    print(bottom[0].data.shape)
    print(bottom[0].data)
    top[0].data[...] = bottom[0].data + self.num
    print(top[0].data[...])

  def backward(self, top, propagate_down, bottom):
    pass

02 使用自定义层定义网络文件

网络定义文件:cus_layer.prototxt

# cus_layer.prototxt 该网络定义文件使用了自定义的MyLayer层
# 网络定义文件,使用了自定义层customlayer的MyLayer
# module: 'customlayer'对应customlayer.py文件名
# layer: 'MyLayer'对应customlayer.py中的 MyLayer python类
name: "convolution"
input: "data"
input_dim: 1
input_dim: 3
input_dim: 100
input_dim: 100
layer {
  name: "conv"
  type: "Convolution"
  bottom: "data"
  top: "conv"
  convolution_param {
    num_output: 3
    kernel_size: 5
    stride: 1
    weight_filler {
      type: "gaussian"
      std: 0.01
    }
    bias_filler {
      type: "constant"
      value: 0
    }
  }
}
layer {
  name: 'CustomLayer'
  type: 'Python'
  top: 'output'
  bottom: 'conv'
  python_param {
    module: 'customlayer'
    layer: 'MyLayer'
    param_str: "'num': 21"
  }
}

03 测试数据

使用examples\images\cat.jpg。拷贝到当前目录。

04 测试自定义层

python脚本:test_custom_layer.py

# 本实验的四个文件在同一个目录
# 自定义层python脚本文件:customlayer.py
# 网络定义文件:cus_layer.prototxt
# 数据文件:cat.jpg #cat.jpg从examples\images\cat.jpg拷贝而来
# 测试运行自定义层python脚本:test_custom_layer.py
import sys, io
caffe_root='D:/git/DeepLearning/caffe/build/x64/install/'
sys.path.insert(0, caffe_root+'python')
import caffe
import numpy as np
import yaml

net = caffe.Net('cus_layer.prototxt', caffe.TEST)
im = np.array(caffe.io.load_image('cat.jpg'))
im_input = im[np.newaxis, :, :]
print(im_input.shape)
im_input = im_input.transpose((0, 3, 1, 2))
print(im_input.shape)
net.blobs['data'].reshape(*im_input.shape)
net.blobs['data'].data[...] = im_input
net.forward()

05 运行结果

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值