Search code examples
pythoncaffepycaffe

Dynamically modify layer's parameters in Caffe


I use the follwoing code to load the net and set up it, the parameters of layers are stored in deploy.prototxt.

net = caffe.Net(deploy.prototxt, caffemodel, caffe.TEST)

However, what I want to do is to modify the parameters (e.g. kernel_size, or pad, etc.) of layers dynamically instead of modifying the prototxt file and reload it. Is there any way to do so?


Solution

  • You can write your own get/set methods and expose them to python. In layer.hpp:

    virtual float GetParameter(const std::string param_name) {return -1;}
    virtual void SetParameter(const std::string param_name, float val) {}
    

    Then redefine these methods in layers where you would like to get/set parameters dynamically.

    The last step is to expose the methods to python. In _caffe.cpp add this for bp::class_<Layer...:

    .def("get_parameter", &Layer<Dtype>::GetParameter)
    .def("set_parameter", &Layer<Dtype>::SetParameter)