【问题标题】:What is the proper way to implement a dropout layer in a CNN?在 CNN 中实现 dropout 层的正确方法是什么?
【发布时间】:2022-01-19 15:45:03
【问题描述】:

这个过程正确吗?

我的意图是在连接后添加一个 dropout 层,但为此我需要将 concat 层的输出调整为适当的shape (样本、时间步长、通道),从而扩展来自(None, 4096) to (None, 1, 4096) 的维度,因此在输出后撤消操作。

【问题讨论】:

    标签: python tensorflow keras dropout


    【解决方案1】:

    如果您计划使用SpatialDropout1D 层,它必须接收一个 3D 张量 (batch_size, time_steps, features),因此在将其馈送到 dropout 层之前,向您的张量添加一个额外的维度是一种完全合法的选择。 但请注意,在您的情况下,您可以同时使用 SpatialDropout1DDropout

    import tensorflow as tf
    
    samples = 2
    timesteps = 1
    features = 5
    x = tf.random.normal((samples, timesteps, features))
    s = tf.keras.layers.SpatialDropout1D(0.5)
    d = tf.keras.layers.Dropout(0.5)
    
    print(s(x, training=True))
    print(d(x, training=True))
    
    tf.Tensor(
    [[[-0.5976591  1.481788   0.         0.         0.       ]]
    
     [[ 0.        -4.6607018 -0.         0.7036132  0.       ]]], shape=(2, 1, 5), dtype=float32)
    tf.Tensor(
    [[[-0.5976591  1.481788   0.5662646  2.8400114  0.9111476]]
    
     [[ 0.        -0.        -0.         0.7036132  0.       ]]], shape=(2, 1, 5), dtype=float32)
    

    我认为SpatialDropout1D层在CNN层之后最合适。

    【讨论】:

    • 非常感谢,我会多研究一下它们之间的区别。这里的事情是,我在特征提取模型和正在通过考虑来自预训练模型(两个 resnet)的这些附加特征进行训练的模型之间存在连接。在这种情况下,我还不知道哪个更适合这个应用程序。
    • 除此之外我已经搜索过但没有太多成功。你知道 arg time_steps 是什么意思吗?
    • 它只是一个空间/时间维度。检查此帖子,例如 stackoverflow.com/questions/69591717/…
    【解决方案2】:

    在 tensorflow 2.7.0 中,您可以只使用 keepdims=True 作为 GlobalAveragePooling2D 层的参数,而不是显式添加新维度。

    例子:

    def TestModel():
      # specify the input shape
      in_1 = tf.keras.layers.Input(shape = (256,256,3))
      in_2 = tf.keras.layers.Input(shape = (256,256,3))
    
      x1 = tf.keras.layers.Conv2D(64, (3,3))(in_1)
      x1 = tf.keras.layers.LeakyReLU()(x1)
      x1 = tf.keras.layers.GlobalAveragePooling2D(keepdims = True)(x1)
    
      x2 = tf.keras.layers.Conv2D(64, (3,3))(in_2)
      x2 = tf.keras.layers.LeakyReLU()(x2)
      x2 = tf.keras.layers.GlobalAveragePooling2D(keepdims = True)(x2)
     
      x = tf.keras.layers.concatenate([x1,x2])
      x = tf.keras.layers.SpatialDropout2D(0.2)(x)
      x = tf.keras.layers.Dense(1000)(x)
    
      # create the model
      model = tf.keras.Model(inputs=(in_1,in_2), outputs=x)
    
      return model
    
    #Testcode
    model = TestModel()
    model.summary()
    tf.keras.utils.plot_model(model, show_shapes=True, expand_nested=False, show_dtype=True, to_file="model.png")
    

    如果最后需要挤,还是可以挤的。

    【讨论】:

    • 非常感谢。问题是我的平均池层的输出具有形状(无,2048),这样我看不到保留暗淡如何帮助我,因为我必须扩展它。不管怎样,谢谢你的提示,我不知道这个。
    猜你喜欢
    • 2011-11-06
    • 2018-08-12
    • 1970-01-01
    • 2014-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-18
    • 1970-01-01
    相关资源
    最近更新 更多