繁体   English   中英

如何丢弃神经网络中的整个隐藏层?

[英]How to dropout entire hidden layer in a neural network?

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

使用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)

如果您在 model 中使用它,只需删除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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM