caffe create networks by python

2019-08-01 17:17发布

问题:

We all know this python code can create caffe networks:

    n = caffe.NetSpec()
    n.data, n.label = L.Data(batch_size=batch_size,
                             backend=P.Data.LMDB, source=lmdb,
                             transform_param=dict(scale=1. / 255), ntop=2)
    n.conv1 = L.Convolution(n.data, kernel_size=5,
                            num_output=20, weight_filler=dict(type='xavier'))
    n.pool1 = L.Pooling(n.conv1, kernel_size=2,
                        stride=2, pool=P.Pooling.MAX)

The layer's name is on the right of n. for example:"n.data",this layer's name is "data".

  1. Write simple code

If I want to create much more layers ,and the layers' name are the same except the number. For example, all layers' names are {conv1,conv2,conv3,...,conv100}. I want to definite a string s_name = conv%s and just loop the number to do the same thing for once ,don't need to write almost the same code 100 times.How should I do?

  1. add '/' in name? The layer's name is "conv1/dw",how could I definite the name ?

回答1:

You can do it either using __setattr__:

s_name = 'conv{:03d}'.format(i)
l = L.Convolution( # ...
n.__setattr__(s_name, l)

An extensive example (unrolling LSTM units) can be found here

Alternatively, you can use the __getitem__ attribute:

n[s_name] = L.Convolution( # ...

See this answer for more information.