gpt4 book ai didi

tensorflow - conv2d 的任意过滤器(与矩形相反)

转载 作者:行者123 更新时间:2023-12-04 00:05:56 25 4
gpt4 key购买 nike

我在由二维图像组成的数据样本上使用卷积层。滤波器形状的一个选项是 1x2,它作用于两个相邻像素的 1x2 连续 block 。如果我想要一个过滤器,它也作用于 2 个像素,但像素被它们之间的另一个像素隔开,该怎么办?是否可以在神经网络中为卷积编码这样的过滤器?

最佳答案

使其工作的代码

You can also watch a video of how to make it work with Keras

这里是一些示例代码,它为 Conv2d 定义了一个内核和一个 5x5 掩码,只允许中心值和外部值通过。

image = np.array( range(25) ).reshape([1,5,5,1] ).astype( float )

kern = tf.Variable( tf.ones( [5,5,1,1] , dtype=tf.float32) )

mask = np.array([[ 1, 1, 1, 1, 1],
[ 1, 0, 0, 0, 1],
[ 1, 0, 1, 0, 1],
[ 1, 0, 0, 0, 1],
[ 1, 1, 1, 1, 1]]).reshape( [5,5,1,1] )

mask_variable = tf.constant( mask , dtype=tf.float32 )

output = tf.nn.conv2d( image , kern , strides=[1,1,1,1] , padding="VALID" )
output_with_mask = tf.nn.conv2d( image , kern * mask , strides=[1,1,1,1] , padding="VALID" )

print("Using whole kernal :",output.numpy())
print("Using kernal with a mask :",output_with_mask.numpy())

还有输出

Using whole kernal : [[[[ 300.]]]]
Using kernal with a mask : [[[[ 204.]]]]

此外,反向传播不会改变掩码,因为掩码被包裹在 tf.stop_gradient 中。

干杯

关于tensorflow - conv2d 的任意过滤器(与矩形相反),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44915379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com