【问题标题】:How to apply dropout to the outputs of an RNN in TensorFlow Eager using the Keras API?如何使用 Keras API 在 TensorFlow Eager 中将 dropout 应用于 RNN 的输出?
【发布时间】:2018-11-10 21:55:30
【问题描述】:

我想对 RNN 的输出应用 dropout。例如,在 TensorFlow 1.8.0 中,我可以这样做:

import tensorflow as tf
import tensorflow.contrib.eager as tfe

tfe.enable_eager_execution()

x = tf.random_uniform((10, 5, 3))

gru_cell1 = tf.contrib.rnn.GRUCell(2)
gru_cell1 = tf.contrib.rnn.DropoutWrapper(gru_cell1, output_keep_prob=0.5)
cell = tf.contrib.rnn.MultiRNNCell([gru_cell1])
init_state = cell.zero_state(10, tf.float32)

cell_output, _ = tf.nn.dynamic_rnn(cell, x,
                                   initial_state=init_state, time_major=False)
cell_output

如何使用 Keras API 实现相同的目标?

我想过以下两种方法,但都没有成功:

import tensorflow as tf
import tensorflow.contrib.eager as tfe

tfe.enable_eager_execution()

# Attempt 1
x = tf.random_uniform((10, 5, 3))

gru_layer = tf.keras.layers.GRU(2, return_sequences=True, input_shape=(10, 5, 3))
gru_layer = tf.keras.layers.Dropout(0.5)(gru_layer)

# Gives the following error:
# ValueError: Attempt to convert a value (<tensorflow.python.keras._impl.keras.layers.recurrent.GRU object
#  at 0x000001C520681F60>) with an unsupported type (<class 'tensorflow.python.keras._impl.keras.layers.recurrent.GRU'>) 
# to a Tensor.

# Attempt 2
x = tf.random_uniform((10, 5, 3))

gru_layer = tf.keras.layers.GRU(2, return_sequences=True, input_shape=(10, 5, 3))
gru_layer = tf.keras.layers.TimeDistributed(tf.keras.layers.Dropout(0.4))(gru_layer)

# Gives the following error:
# ValueError: as_list() is not defined on an unknown TensorShape.

【问题讨论】:

  • 您可能缺少 keras 图层的输入形状参数
  • @BallpointBent 感谢您的意见。我已经尝试过了,但它仍然给出了同样的错误。
  • 为什么不在 tensorflow 后端使用 keras.layers
  • @BallpointBen 因为我发现在 Eager 模式下调试模型更容易。
  • 从您在此处发布的代码中,看不到 x 与其余部分的联系。根据 Keras Model (functional API) 的说法,神经网络通常从 Input 层开始。你把这些层串联起来。然后从输入和输出创建Model。然后编译模型。然后你在模型上调用fit()。那是你传入xy 的时候。

标签: python tensorflow keras recurrent-neural-network dropout


【解决方案1】:

要获得模型输出,无需训练,就像您在 TF 代码中所做的那样,以下代码应该可以工作。实际上,您需要一个 Input 层,并将每一层与前一层挂钩,还需要一个 Model

import numpy as np
from keras.models import Model
from keras.layers import Dropout, GRU, Input

x = np.random.randn(10, 5, 3)

inputs = Input(shape=(5, 3))
gru_layer = GRU(2, return_sequences=True)(inputs)
gru_layer = Dropout(0.5)(gru_layer)

model = Model(inputs=inputs, outputs=gru_layer)

output = model.predict(x)

【讨论】:

  • 这有一个小问题,这适用于所有时间步的丢失,这意味着可以完全删除一些时间步。要独立退出每个时间步,您需要指定 noise_shape=(batch_size, 1, features) doc
猜你喜欢
  • 2018-10-31
  • 2020-04-21
  • 2019-01-04
  • 1970-01-01
  • 1970-01-01
  • 2021-12-30
  • 2019-04-15
  • 2019-07-31
  • 1970-01-01
相关资源
最近更新 更多