问题描述
我正在尝试具体实施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 (将#修改为@)