如何使用pycaffe重建caffe net [英] How reconstruct the caffe net by using pycaffe

查看:49
本文介绍了如何使用pycaffe重建caffe net的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要的是,在加载网络后,我将分解某些层并保存新的网络.例如

What I want is, After loading a net, I will decompose some certain layers and save the new net. For example

原始网:

数据-> conv1-> conv2-> fc1-> fc2-> softmax;

data -> conv1 -> conv2 -> fc1 -> fc2 -> softmax;

新网:

数据-> conv1_1-> conv1_2-> conv2_1-> conv2_2-> fc1-> fc2-> softmax

data -> conv1_1 -> conv1_2 -> conv2_1 -> conv2_2 -> fc1 -> fc2 -> softmax

因此,在此过程中,我陷入了以下情况:
1.如何在pycaffe中使用指定的图层参数新建某个图层?
2.如何从现有图层(例如上面的fc1fc2)复制图层参数?

Therefore, during this process, I stuck in the following situation:
1. How to new a certain layer with specified layer parameters in pycaffe?
2. How to copy the layer parameters from existing layers(such as fc1 and fc2 above)?

我知道通过使用caffe::net_spec,我们可以手动定义一个新的网络.但是caffe::net_spec无法从现有的图层中指定图层(例如:fc1).

I know by using caffe::net_spec, we can define a new net manually. But caffe::net_spec can not specify a layer from a existing one(e.g: fc1).

推荐答案

我没有看到如何使用net_spec在以前的网络中加载,但是您始终可以直接使用protobuf对象. (我以您的网络结构为例)

I didn't see how to load in previous nets with net_spec but you can always use the protobuf objects directly. (I use your network structure as an example)

import caffe.proto.caffe_pb2 as caffe_pb2
import google.protobuf as pb
from caffe import layers as L

net = caffe_pb2.NetParameter()
with open('net.prototxt', 'r') as f:
    pb.text_format.Merge(f.read(), net)

#example of modifing the network:
net.layer[1].name = 'conv1_1'
net.layer[1].top[0] = 'conv1_1'
net.layer[2].name = 'conv1_2'
net.layer[2].top[0] = 'conv1_2'
net.layer[2].bottom[0] = 'conv1_1'

net.layer[3].bottom[0] = 'conv2_2'

#example of adding new layers (using net_spec):
conv2_1 = net.layer.add()
conv2_1.CopyFrom(L.Convolution(kernel_size=7, stride=1, num_output=48, pad=0).to_proto().layer[0])
conv2_1.name = 'conv2_1'
conv2_1.top[0] = 'conv2_1'
conv2_1.bottom.add('conv1_2')

conv2_2 = net.layer.add()
conv2_2.CopyFrom(L.Convolution(kernel_size=7, stride=1, num_output=48, pad=0).to_proto().layer[0])
conv2_2.name = 'conv2_2'
conv2_2.top[0] = 'conv2_2'
conv2_2.bottom.add('conv2_1')

# then write back out:
with open('net2.prototxt, 'w') as f:
    f.write(pb.text_format.MessageToString(net))

另请参见此处,以了解有关python和此处了解当前的caffe消息格式

Also see here as a guide on protocol buffers in python and here for the current caffe message formats.

这篇关于如何使用pycaffe重建caffe net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆