如何创建自定义 keras 层 "min pooling" 但忽略零?
How to create a custom keras layer "min pooling" but ignore zeros?
我正在使用 keras 和 tensorflow 后端开发神经网络。
通常它是由卷积层和最大池化层构建的,例如在 vgg16 中所做的那样。对于我的神经网络,我想将最大池化层更改为最小池化层,但该层在池化时应忽略零。
例如:
[[0, 16], [72, 0]] 2x2 池化层应该池化 16 而不是 72(最大池化)。
在keras中有没有简单的方法来编写这个自定义层?
我想通过
可以实现最小池化
min_x = -K.pool2d(-x, pool_size=(2, 2), strides=(2, 2))
现在它应该另外忽略零作为最小值。
感谢您的帮助!
我找到的一种可能的解决方案如下。它是一种使用最小池化的变通方法,在最小池化之前向所有零添加一个高值,并在最小池化之后再次减去该高值。我仍在寻找更好的解决方案来解决这个问题,因为我认为这不是最好的方法,尤其是在性能方面。
def min_pool2d(x):
max_val = K.max(x) + 1 # we gonna replace all zeros with that value
# replace all 0s with very high numbers
is_zero = max_val * K.cast(K.equal(x,0), dtype=K.floatx())
x = is_zero + x
# execute pooling with 0s being replaced by a high number
min_x = -K.pool2d(-x, pool_size=(2, 2), strides=(2, 2))
# depending on the value we either substract the zero replacement or not
is_result_zero = max_val * K.cast(K.equal(min_x, max_val), dtype=K.floatx())
min_x = min_x - is_result_zero
return min_x # concatenate on channel
这将帮助您:
from skimage.measure import block_reduce
min_pool=block_reduce(img, block_size=(9,9,1), func=np.min)
我正在使用 keras 和 tensorflow 后端开发神经网络。 通常它是由卷积层和最大池化层构建的,例如在 vgg16 中所做的那样。对于我的神经网络,我想将最大池化层更改为最小池化层,但该层在池化时应忽略零。
例如:
[[0, 16], [72, 0]] 2x2 池化层应该池化 16 而不是 72(最大池化)。
在keras中有没有简单的方法来编写这个自定义层?
我想通过
可以实现最小池化min_x = -K.pool2d(-x, pool_size=(2, 2), strides=(2, 2))
现在它应该另外忽略零作为最小值。 感谢您的帮助!
我找到的一种可能的解决方案如下。它是一种使用最小池化的变通方法,在最小池化之前向所有零添加一个高值,并在最小池化之后再次减去该高值。我仍在寻找更好的解决方案来解决这个问题,因为我认为这不是最好的方法,尤其是在性能方面。
def min_pool2d(x):
max_val = K.max(x) + 1 # we gonna replace all zeros with that value
# replace all 0s with very high numbers
is_zero = max_val * K.cast(K.equal(x,0), dtype=K.floatx())
x = is_zero + x
# execute pooling with 0s being replaced by a high number
min_x = -K.pool2d(-x, pool_size=(2, 2), strides=(2, 2))
# depending on the value we either substract the zero replacement or not
is_result_zero = max_val * K.cast(K.equal(min_x, max_val), dtype=K.floatx())
min_x = min_x - is_result_zero
return min_x # concatenate on channel
这将帮助您:
from skimage.measure import block_reduce
min_pool=block_reduce(img, block_size=(9,9,1), func=np.min)