【问题标题】:How to dropout entire hidden layer in a neural network?如何丢弃神经网络中的整个隐藏层?
【发布时间】:2020-12-30 16:02:14
【问题描述】:

我正在尝试在 tensorflow 2.0 中构建神经网络。在那里我想退出整个隐藏层 一个概率不是任何单个节点具有一定的概率。谁能告诉我如何在 tensorflow 2.0 中退出整个层?

【问题讨论】:

    标签: python tensorflow keras deep-learning neural-network


    【解决方案1】:

    使用Dropout 层的noise_shape 参数作为输入的[1] * n_dim。假设输入张量是 2D:

    import tensorflow as tf
    
    x = tf.ones([3,5])
    
    <tf.Tensor: shape=(3, 5), dtype=float32, numpy=
    array([[1., 1., 1., 1., 1.],
           [1., 1., 1., 1., 1.],
           [1., 1., 1., 1., 1.]], dtype=float32)>
    

    noise_shape 应该是[1, 1]

    tf.nn.dropout(x, rate=.5, noise_shape=[1, 1])
    

    然后它会随机给出这些作为权重:

    <tf.Tensor: shape=(3, 5), dtype=float32, numpy=
    array([[2., 2., 2., 2., 2.],
           [2., 2., 2., 2., 2.],
           [2., 2., 2., 2., 2.]], dtype=float32)>
    
    <tf.Tensor: shape=(3, 5), dtype=float32, numpy=
    array([[0., 0., 0., 0., 0.],
           [0., 0., 0., 0., 0.],
           [0., 0., 0., 0., 0.]], dtype=float32)>
    

    您可以像这样使用 Keras 层对其进行测试:

    tf.keras.layers.Dropout(rate=.5, noise_shape=[1, 1])(x, training=True)
    

    如果您在模型中使用它,只需删除 training 参数,并确保您手动指定 noise_shape

    这样的东西应该可以工作,虽然我还没有测试过:

    class SubclassedModel(tf.keras.Model):
        def __init__(self):
            super(SubclassedModel, self).__init__()
            self.dense = tf.keras.layers.Dense(4)
    
        def call(self, inputs, training=None, mask=None):
            noise_shape = tf.ones(tf.rank(inputs))
            x = tf.keras.layers.Dropout(rate=.5, 
                                        noise_shape=noise_shape)(inputs, training=training)
            x = self.dense(x)
            return x
    

    【讨论】:

    • training=True 是什么意思?我为什么要删除培训论点?你能解释一下吗?
    • Dropout 将权重的百分比设置为零,因此在训练期间,网络用于测试时将获得的输入的一半。因此,dropout 层在训练和测试期间具有不同的行为。 Training=False 使其输出在测试期间有用的权重,因此我必须将其设置为 True 以在此处进行演示。否则,它只输出一个。根据您使用的是函数式、顺序式还是子类化模型,您可能必须以不同的方式处理此参数。我建议使用子类化方法,因为您需要 noise_shape 的输入形状。
    • 我有一个 4 维输入(批量大小、帧数、关节、关节维度)。现在我应该使用噪声形状 = [1,1,1,1] 吗?
    • 这正是我的建议
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-21
    • 2017-12-20
    • 2017-09-19
    • 2014-07-24
    相关资源
    最近更新 更多