Caffe: How to modify a prototxt programmatically?

Created on 23 Oct 2016  ·  3Comments  ·  Source: BVLC/caffe

I want to modify a prototxt programmatically with python.
I tried caffe.NetSpec and caffe.Net, but don't know how to read a prototxt to a NetSpec, and to convert Net to NetSpec or Net.layers to NetSpec.layers neither.
I googled and googled, but no result.
Obviously I am sticked, for many days.
Please give me a hint or searching keywords or anything.
By the way, I do not want to handle the prototxt just as text strings.
Thank you!

Most helpful comment

Sorry I find the answer by myself.
Forgot Caffe, learn a little protobuf.
So naive but maybe help:

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

net = caffe_pb2.NetParameter()

fn = '/tmp/net.prototxt'
with open(fn) as f:
    s = f.read()
    txtf.Merge(s, net)

net.name = 'my new net'
layerNames = [l.name for l in net.layer]
idx = layerNames.index('fc6')
l = net.layer[idx]
l.param[0].lr_mult = 1.3

outFn = '/tmp/newNet.prototxt'
print 'writing', outFn
with open(outFn, 'w') as f:
    f.write(str(net))

All 3 comments

Sorry I find the answer by myself.
Forgot Caffe, learn a little protobuf.
So naive but maybe help:

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

net = caffe_pb2.NetParameter()

fn = '/tmp/net.prototxt'
with open(fn) as f:
    s = f.read()
    txtf.Merge(s, net)

net.name = 'my new net'
layerNames = [l.name for l in net.layer]
idx = layerNames.index('fc6')
l = net.layer[idx]
l.param[0].lr_mult = 1.3

outFn = '/tmp/newNet.prototxt'
print 'writing', outFn
with open(outFn, 'w') as f:
    f.write(str(net))

Thank you @junglezax for writing such an amazing script !

thank you so much!!!! @junglezax

Was this page helpful?
0 / 5 - 0 ratings