【问题标题】:Unexpected result with Conv2D layer in KerasKeras 中 Conv2D 层的意外结果
【发布时间】:2022-12-03 11:02:17
【问题描述】:

我正在 Keras 的 Conv2D 层上运行一些测试,但我不明白我得到的结果之一。

我正在运行一个简单的示例来了解正在发生的事情。我采用一个测试数组并创建一个具有 2 个过滤器输出的 Conv2D 层。我使用 1 的简单 3*3 内核。 我希望 2 个过滤器具有相同的输出。

这是我的最小代码示例:

    import tensorflow.keras as keras
    import functools
    from keras import layers


    import tensorflow as tf
    import tensorflow.keras as keras
    import keras.layers as layers
    import numpy as np

    ###define a simple test array
    test_array = np.array([[2,2,2,1],[2,1,2,2],[2,2,2,2],[2,2,1,2]],dtype=np.float32)

    ###reshape to simulate a filter entry of a one channel conv2D layer
    test_array = test_array.reshape((1,4,4,1))

    ###Create conv2Dlayer and initialize
    standardConv = layers.Conv2D(filters=2,kernel_size=[3,3])
    standardConv(np.ones([1,4,4,1],dtype=np.float32))

    ###set simple weights for testing
    standardConv.set_weights([ np.ones([3,3,1,2]) , np.zeros([2]) ])

    ###apply convolution layer to test_array
    standardConv(test_array)

我得到的结果如下:

Out[46]: 
    <tf.Tensor: shape=(1, 2, 2, 2), dtype=float32, numpy=
    array([[[[17., 17.],
             [16., 16.]],

            [[16., 16.],
             [16., 16.]]]], dtype=float32)>

我不明白第二个过滤结果 [[16., 16.], [16., 16.]] 我所期望的是看到两个过滤器具有相同的结果 [[17,17],[16,16]],这对应于我的 test_array 与 1 的 3x3 内核的卷积。

两个过滤器的卷积权重相同,只有一个 (np.ones([3,3,1,2])),据我所知,它们应该应用于相同的输入数组,所以我可能遗漏了一些东西.

有人能解释一下我们如何获得第二个过滤结果以及为什么在这种情况下它与第一个不一样吗?

【问题讨论】:

    标签: python-3.x tensorflow keras deep-learning conv-neural-network


    【解决方案1】:

    布局有点误导;两个过滤器给出相同的正确结果。

    第一个过滤器:

    print(standardConv(test_array)[:, :, :, 0])
    

    输出:

    tf.Tensor(
    [[[17. 16.]
      [16. 16.]]], shape=(1, 2, 2), dtype=float32)
    

    第二个过滤器:

    print(standardConv(test_array)[:, :, :, 1])
    

    输出:

    tf.Tensor(
    [[[17. 16.]
      [16. 16.]]], shape=(1, 2, 2), dtype=float32)
    

    当您使用更多过滤器时,例如 5,您将得到以下输出:

    tf.Tensor(
    [[[[17. 17. 17. 17. 17.]
       [16. 16. 16. 16. 16.]]
    
      [[16. 16. 16. 16. 16.]
       [16. 16. 16. 16. 16.]]]], shape=(1, 2, 2, 5), dtype=float32)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-29
      • 1970-01-01
      • 1970-01-01
      • 2019-02-25
      相关资源
      最近更新 更多