Categories
Misc

Converting pytorch weights to tensorflow weights for Conv2d

Converting pytorch weights to tensorflow weights for Conv2d

Hello. I convert weights from a pytorch model to tf2 model. To verify the result, I export the feature maps after the conv2d for both pytorch original model and tf2 model. However, the feature map from tf2 model has black bars on the top and left hand side of the map, whereas the pytorch feature map does not have these black bars.

https://preview.redd.it/hyo378nslxa71.png?width=961&format=png&auto=webp&s=34613e37989d3c13fb2dd2c89d28b45df845b3a1

The pytorch code of conv2d is

nn.Conv2d(1, 56, kernel_size=5, padding=5//2) 

The tensorflow build is

tensorflow.keras.layers.Conv2D(56, 5, padding="same")(inp) 

According to https://stackoverflow.com/questions/68165375/manualy-convert-pytorch-weights-to-tf-keras-weights-for-convolutional-layer# advise, I even add the zeropadding layer to the tensorflow model

x = tensorflow.keras.layers.ZeroPadding2D(padding=((2,2)))(inp) x2 = tensorflow.keras.layers.Conv2D(56, 5, padding="valid")(x) 

However, the black bar is still there. I have no clue for this problem > <. For the converting process for pytorch weights to tensorflow weights is as follow:

onnx_1_w_num = onnx_l.weight.data.permute(2,3,1,0).numpy() onnx_1_b_num = onnx_l.bias.data.numpy() tf_l.set_weights([onnx_1_w_num,onnx_1_b_num]) 

submitted by /u/mrgreen3325
[visit reddit] [comments]

Leave a Reply

Your email address will not be published. Required fields are marked *