且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python Keras如何将密集层转换为卷积层

更新时间:2023-12-02 21:17:34

还在寻找解决方案吗?在这里:

Still looking for solution? Here it is:

new_conv_weights = dense_weights.transpose(1,0).reshape(new_conv_shape)[:,:,::-1,::-1]

在您的情况下:

weights[0] = weights[0].transpose(1,0).reshape((4096,512,7,7))[:,:,::-1,::-1]

棘手的部分是转换滤镜[[,,:,::-1,::-1]. Theano确实进行卷积而不是相关(例如与caffe不同).因此,在Keras过滤器中,例如:

The tricky part is conv filters flipping [:,:,::-1,::-1]. Theano does convolution not correlation (unlike caffe e.g.). Hence, in Keras filter like:

1 0
0 0

应用于矩阵:

1 2 3 4 5
6 7 8 9 0
1 2 3 4 5

以矩阵形式得出的结果

7 8 9 0 
2 3 4 5

不是这样,正如人们期望的那样:

not this, as one would expect with correlation:

1 2 3 4
6 7 8 9

为了使事情按预期工作,您需要将滤镜旋转180度.刚刚为自己解决了这个问题,希望对您或其他人有帮助.干杯.

In order to make things working as expected, you need to rotate filters 180 deg. Just solved this problem for myself, hopefully this will be of help for you or for others. Cheers.