caffe 10 win10 使用python自定义层

来源:互联网 发布:oracle数据库简介 编辑:程序博客网 时间:2024/04/28 12:40

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 caffeimport 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: 1input_dim: 3input_dim: 100input_dim: 100layer {  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.pyimport sys, iocaffe_root='D:/git/DeepLearning/caffe/build/x64/install/'sys.path.insert(0, caffe_root+'python')import caffeimport numpy as npimport yamlnet = 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_inputnet.forward()

05 运行结果

0 0
原创粉丝点击