Skip to content

Use the weights available at https://lmb.informatik.uni-freiburg.de/resources/opensource/unet/ for Tensorflow 2 (Keras) #78

Open
@ghost

Description

Hi everyone!

I am trying to use the Caffe weights available at https://lmb.informatik.uni-freiburg.de/resources/opensource/unet/ for a model implemented in Tensorflow.

To be more specific, I read the 2d_cell_net_v0.modeldef.h5 file in order to get the layer names in the right order:

layer_names=[]
mod=h5py.File('2d_cell_net_v0.modeldef.h5', 'r')
for line in mod['model_prototxt'].value.decode('utf8').split('\n'):
    if line.startswith('layer'):
        name=line.split('name:')[1].split(' ')[1].replace('\'','')
        layer_names.append(name) 

Then, I loop through the layers available in the 2d_cell_net_v0.caffemodel.h5 file and try to find the corresponding layers in TensorFlow Keras. Doing this, I saw that the shape of the layers were different and I corrected this. In the end, I extract the weights from the Caffe layer and set the Tensorflow layer with them.

size_image=512
unet = networks.UNet_Freiburg((size_image,size_image,1))
caffe_weights=[]
unet_weights=h5py.File('2d_cell_net_v0.caffemodel.h5', 'r')
data=unet_weights['data']

for layer_name in layer_names:
    for layer in data:        
        l=unet_weights['/data/'+layer]  
        name=l.name.split('/')[-1]
        if name==layer_name:
            if '0' in l:
                weight_array=np.array(l['0']).T
                bias_array=np.array(l['1']).T
                if 'up' in name:
                    weight_array=np.swapaxes(weight_array,2,3)
                shape_weights=weight_array.shape    
                shape_bias=bias_array.shape

                for ul in unet.layers:
                    if ul.name==name:
                        ul.set_weights([weight_array,bias_array])

The results are not what I expected:

caffe_tf

Could anyone help me with this? What am I missing?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions