【发布时间】:2021-10-13 09:19:28
【问题描述】:
在 keras 中为 RNN 实现自定义单元格时,有没有办法在给定的时间步长内返回多个输出?例如。输出形状: (sequences=[batch, timesteps, hidden_units], other_outputs=[batch, timesteps, absolute_units], last_hidden_states=[batch, hidden_units])
我这样做的动机源于Self Attention in Variational Sequential Learning for Summarization 的算法 1“循环解码器”,它“累积变分目标”,因此必须跟踪给定循环时间步长的多个输出。
使用 keras RNN,如果在实例化层时传递 return_sequences=True 和 return_state=True 参数,则通过 RNN 的前向传递的输出为 ([batch, timesteps, hidden_units], [batch, hidden_units])它们分别是所有时间步的隐藏状态和最后一个隐藏状态。 我想使用 RNN 在每个时间步跟踪其他输出,但我不确定如何。我想我可以更改自定义单元格中的output_size 属性,类但我不确定这是否有效,因为 TensorFlow RNN 文档似乎表明每个时间步只能有一个输出(即,'单个整数或 TensorShape '):
一个 output_size 属性。这可以是单个整数或 TensorShape,表示输出的形状。对于落后 兼容的原因,如果此属性对单元格不可用, 该值将由 state_size 的第一个元素推断。
到目前为止,这是我为自定义实现的“RNN 单元”所拥有的:
class CustomGRUCell(tf.keras.layers.Layer):
def __init__(self, units, arbitrary_units, **kwargs):
super().__init__(**kwargs)
self.units = units
# Custom computation for a timestep t
self.dense = tf.keras.layers.Dense(units=arbitrary_units)
# The RNN cell
self.gru = tf.keras.layers.GRUCell(units=self.units)
# Required for custom cells...
self.state_size = tf.TensorShape([self.units])
# PERHAPS I CHANGE THIS????
self.output_size = tf.TensorShape([self.units])
def call(self, input_at_t, states_at_t):
"""Forward pass that uses a constant to modify the hidden state.
:param inputs_at_t: (batch, features) tensor from (batch, t, features)
inputs
:param states_at_t: <class 'tuple'> Why? Perhaps generically,
this is because an LSTM for example takes two hidden states
instead of just one like the GRU
:param constants: <class 'tuple'> Why? To accomodate multiple
constants
"""
# Standard GRU cell call
output_at_t, states_at_t_plus_1 = self.gru(input_at_t, states_at_t)
# Another output at particular timestep t
special_output_at_t = self.dense(input_at_t)
# The outputs
# 'output_at_t' will be automatically tracked by 'return_sequences'.... how do I track
# other comptuations at each timestep????
return [output_at_t, special_output_at_t], states_at_t_plus_1
然后我希望单元格像这样工作:
# Custom cell and rnn
custom_cell = CustomGRUCell(units=10, arbitrary_units=5)
custom_rnn = tf.keras.layers.RNN(cell=custom_cell, return_sequences=True, return_state=True)
# Arbitrary data
batch = 4
timesteps = 6
features = 8
dummy_data = tf.random.normal(shape=(batch, timesteps, features))
# The output I want
seqs, special_seqs, last_hidden_state = custom_rnn(inputs=dummy_data)
print('batch, timesteps, units):', seqs.shape)
print('batch, timesteps, arbitrary_units:', special_seqs.shape)
print('batch, units:', last_hidden_state.shape)
>>> batch, timesteps, units : (4, 6, 10)
>>> batch, timesteps, arbitrary_units: (4, 6, 5)
>>> batch, units: (4, 10)
【问题讨论】:
标签: python tensorflow keras recurrent-neural-network