如何解决初始化为零时的LSTM + Keras错误注意
我正在尝试具体实施this paper,即注意输入的编码器部分。本质上,这是在将输入序列传递到每个LSTM
时间步之前,要格外小心。这要求每个lstm时间步长计算都必须手动完成,以便提供以前的隐藏状态和单元格状态。
为了说明背景,这是正常的lstm编码器层:
input = layers.Input(shape=(time_window,features),dtype='float32')
lstm,state_h,state_c = layers.LSTM(units=45,activation='tanh',return_state=True return_sequences=True)(input)
这是手动执行的操作,注意原始输入:
input = layers.Input(shape=(time_window,dtype='float32')
# Initialise the first hidden state and cell state to zeros
hidden_state = tf.zeros_like(tf.keras.backend.placeholder(shape=(None,45)))
cell_state = tf.zeros_like(tf.keras.backend.placeholder(shape=(None,45)))
lstm = layers.LSTM(units=45,return_state=True)
# loop over the time windows
for i in range(time_window):
# get all the input features (and samples) of the current time step
input_t = input[:,i,:]
input_t = tf.expand_dims(input_t,1)
query = tf.concat([hidden_state,cell_state],axis=-1)
# get context vector from bahdanau attention
attention_result,attention_weights = BahdanauAttention(45)([query,input_t])
attention_result = tf.expand_dims(attention_result,1)
# pass the new inputs with attention to the encoder lstm
out,state_c = lstm(attention_result,initial_state=[hidden_state,cell_state])
# update the hidden state and cell state
hidden_state,cell_state = state_h,state_c
h.append(state_h)
c.append(state_c)
outputs.append(out)
...
# pass the above outputs to the decoder
我遇到了一个我不知道如何解决的错误:
ValueError: Graph disconnected: cannot obtain value for tensor Tensor("Placeholder:0",shape=(None,45),dtype=float32) at layer "tf_op_layer_ZerosLike". The following previous layers were accessed without issue: []
其他StackOverflow answers表示该问题可能是由于变量冲突(在这种情况下,可能是重新分配了hidden_state
和cell_state
变量)。
我不确定该如何解决以及错误的真正含义。
更新
此问题与我正在初始化hidden_state
和cell_state
的事实有关。我可能将它们初始化为错误。底线是我需要获取lstm
的初始隐藏状态(或自行创建它们)。正确解决此问题将解决错误。
如果keras提供了一种在时间表内工作的方式,这可能会更容易。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。