【发布时间】:2020-12-30 16:02:14
【问题描述】:
我正在尝试在 tensorflow 2.0 中构建神经网络。在那里我想退出整个隐藏层 一个概率不是任何单个节点具有一定的概率。谁能告诉我如何在 tensorflow 2.0 中退出整个层?
【问题讨论】:
标签: python tensorflow keras deep-learning neural-network
我正在尝试在 tensorflow 2.0 中构建神经网络。在那里我想退出整个隐藏层 一个概率不是任何单个节点具有一定的概率。谁能告诉我如何在 tensorflow 2.0 中退出整个层?
【问题讨论】:
标签: python tensorflow keras deep-learning neural-network
使用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=False 使其输出在测试期间有用的权重,因此我必须将其设置为 True 以在此处进行演示。否则,它只输出一个。根据您使用的是函数式、顺序式还是子类化模型,您可能必须以不同的方式处理此参数。我建议使用子类化方法,因为您需要 noise_shape 的输入形状。