【问题标题】:How can I do indexwise Convolution type operation in Tensorflow using Conv2D?如何使用 Conv2D 在 Tensorflow 中进行索引卷积类型操作?
【发布时间】:2020-07-31 06:32:35
【问题描述】:

所以我有 64 个尺寸为 512x512 的图像/特征图,使其成为 (512x512x64) 的立方体,我想用 64 个内核INDEXWISE 对每个图像进行卷积。

示例 -
第一个图像 ------> 第一个内核
第二个图像 ------> 第二个内核
第三张图片 ------> 第三个内核
.
.
.
第 64 个映像 --------> 第 64 个内核

我想在 tensorflow 中使用 Conv2D 执行此操作,据我所知,Conv2D 将获取单个图像并与每个内核进行卷积,
第一张图片 --> 所有 64 个内核
第二张图片 --> 所有 64 个内核
我不想这样做

【问题讨论】:

    标签: image conv-neural-network tensorflow2.0 convolution


    【解决方案1】:

    一种(低效但相对简单)的方法是使用自定义层:

    class IndexConv(Layer):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            # Define kernel size, strides, padding etc.
    
        def build(self, input_shape):
            # store the input kernels as a static value. This will save having to get the number of kernels at runtime.
            self.num_kernels = input_shape[-1]
    
            # If the input has n channels, you need n separate kernels
            # Since each kernel convolves a single channel, input and output channels for each kernel will be 1
            self.kernels = [self.add_weight(f'k{i}', (kernel_h, kernel_w, 1, 1), other_params) for i in range(input_shape[-1])]
    
        def call(self, inputs, **kwargs):
            # Split input vector into separate vectors, one vector per channel
            inputs = tf.unstack(inputs, axis=-1)
            
            # Convolve each input channel with corresponding kernel
            # This is the "inefficient" part I mentioned
            # Complex but more efficient versions can make use of tf.map_fn
            outputs = [
                tf.nn.conv2d(channel[i][:, :, :, None], self.kernels[i], other_params)
                for i in range(self.num_kernels)
            ]
    
            # return concatenated output
            return tf.concat(outputs, axis=-1)
    

    【讨论】:

    • tensorflow 新手,对我来说理解起来并不复杂,感谢您的帮助,尽管我会尝试理解这一点。
    • 有一个后续问题,我如何在这一层添加正则化,就像我想在添加权重方法中添加正则化一样
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-21
    • 1970-01-01
    • 2021-02-12
    • 2021-04-09
    • 2018-02-15
    • 2018-06-27
    • 2013-06-08
    相关资源
    最近更新 更多