【问题标题】:How to perform convolution with constant filter in tensorflow/keras如何在 tensorflow/keras 中使用常量滤波器执行卷积
【发布时间】:2020-07-02 11:58:45
【问题描述】:

在 resnet 的某个阶段,我每张图像有 6 个特征,即每个示例的形状为 1X8X8X6,我想将每个特征与 4 个大小为 1X2X2X1 的常量过滤器 (DWT) 相关,步长为 2,以获得 24 个特征在下一层,图像变为 1X4X4X24。但是,我无法为此目的使用 tf.nn.conv2d 或 tf.nn.convolution,conv2d 表示输入的第四维等于过滤器的第三维,但是我该怎么做,我尝试了第一个过滤器,但即使这样也不起作用:

x_in = np.random.randn(1,8,8,6)
kernel_in = np.array([[[[1],[1]],[[1],[1]]]])
kernel_in.shape
x = tf.constant(x_in, dtype=tf.float32)
kernel = tf.constant(kernel_in, dtype=tf.float32)
tf.nn.convolution(x, kernel, strides=[1, 1, 1, 1], padding='VALID')

【问题讨论】:

    标签: python tensorflow machine-learning keras deep-learning


    【解决方案1】:

    这样试试

    x_in = np.random.randn(1,8,8,6) # [batch, in_height, in_width, in_channels]
    kernel_in = np.ones((2,2,6,24)) # [filter_height, filter_width, in_channels, out_channels]
    
    x = tf.constant(x_in, dtype=tf.float32)
    kernel = tf.constant(kernel_in, dtype=tf.float32)
    
    tf.nn.conv2d(x, kernel, strides=[1, 2, 2, 1], padding='VALID')
    # <tf.Tensor: shape=(1, 4, 4, 24), dtype=float32, numpy=....>
    

    【讨论】:

      【解决方案2】:

      一个简单的例子,说明如何将预定义值填充到 TF2 中 Keras.conv2d 层中的过滤器:

      model = models.Sequential()
      # one 3x3 filter
      model.add(layers.Conv2D(1, (3, 3), input_shape=(None, None, 1)))
      # access to the target layer
      layer = model.layers[0]
      current_w, current_bias = layer.get_weights()  # see the current weights
      new_w = tf.constant([[1,2, 3],
                           [4, 5, 6],
                           [7, 8, 9]])
      new_w = tf.reshape(new_w, custom_w.shape)  # fix the shape
      new_bias = tf.constant([0])
      layer.set_weights([new_w, new_bias])
      model.summary()
      # let's see ..
      tf.print(model.layers[0].get_weights())
      

      【讨论】:

        猜你喜欢
        • 2019-11-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-07
        • 2018-02-19
        • 2017-11-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多