caffe: model definition: write same layer with different phase using caffe.NetSpec()

I assume you mean how to define phase when writing a prototxt using caffe.NetSpec?

from caffe import layers as L, params as P, to_proto
import caffe

ns = caffe.NetSpec()
ns.data = L.Data(name="data", 
                 data_param={'source':'/path/to/lmdb','batch_size':32},
                 include={'phase':caffe.TEST})

If you want to have BOTH train and test layers in the same prototxt, what I usually do is making one ns for train with ALL layers and another ns_test with only the test version of the duplicate layers only. Then, when writing the actual prototxt file:

with open('model.prototxt', 'w') as W:
  W.write('%s\n' % ns_test.to_proto())
  W.write('%s\n' % ns.to_proto())

This way you’ll have BOTH phases in the same prototxt. A bit hacky, I know.

Leave a Comment