user4911648
user4911648

Reputation:

How to remove layers by name from .prototxt in caffe using Python

I have a train.prototxt create with Python code and would like to remove the loss layers to create the deploy.prototxt automatically. However, I know only the method to remove a layer by an integer like this:

net_param = deploy_net.to_proto()
del net_param.layer[0]

Is there any possibility to remove a layer by its name? Where is the documentation for the Python API? I cannot really find it. Do I just have to look at the C++ code and try to convert it into Python code?

EDIT

I am initialising the net with.

net = caffe.NetSpec()

Upvotes: 1

Views: 1931

Answers (2)

doplano
doplano

Reputation: 1581

As an alternative to this answer, you can also do the following to add force_backward=true and remove any layer from deploy.prototxt file without modifying a original file:

from caffe.proto import caffe_pb2
from google.protobuf import text_format

model = caffe.io.caffe_pb2.NetParameter()
text_format.Merge(open(model_path + 'deploy.prototxt').read(), model)
model.force_backward = True
model.layer.remove(model.layer[-1]) # remove the last layer 'prob' for example
open(model_path + 'tmp.prototxt', 'w').write(str(model))
net = caffe.Net(model_path + 'tmp.prototxt', model_path + 'model.caffemodel', caffe.TEST)

Upvotes: 0

nomem
nomem

Reputation: 1588

net.layer_dict is a dictionary of all the layer. So to delete you can do:

del net.layer_dict['layer_name'];

You can look into pycaffe.py for details of Python Api.

Upvotes: 2

Related Questions