我们知道,解码器将编码器的隐藏状态作为初始状态...
encoder_output , state_h, state_c = LSTM(cellsize, return_state=True)(embedded_encoder_input)
encoder_states = [state_h, state_c]
decoder_lstm = LSTM(cellsize, return_state=True, return_sequences=True)
decoder_outputs, state_dh, state_dc = decoder_lstm(embedded_decoder_inputs, initial_state=encoder_states)
假设我想将解码器的初始状态替换为encoder_output和其他资源中的功能
encoder_states = [encoder_output , my_state]
但是我遇到以下错误:
ValueError:RNN层的初始状态或常量不能为 指定混合使用Keras张量和非Keras张量(“ 张量”是Keras层或
Input
)返回的张量
尽管我打印state_h&stat_c&encoder_output&my_state,但它们都具有相同的类型和形状,例如:
state_h: Tensor("lstm_57/while/Exit_2:0", shape=(?, 128), dtype=float32) my_state: Tensor("Reshape_17:0", shape=(?, 128), dtype=float32)
我了解什么,它将不接受不是从上一层产生的输入以及Keras张量?
更新
将张量转换为Keras张量后,出现新错误:
ValueError:模型的输入张量必须来自
keras.layers.Input
。收到:Tensor(“ Reshape_18:0”,shape =(?, 128), dtype = float32)(缺少上一层元数据)。
答案 0 :(得分:1)
我猜你混合了张量流张量和keras张量。尽管state_h
和my_state
的结果是张量,但它们实际上是不同的。您可以使用K.is_keras_tensor()
来区分它们。一个例子:
import tensorflow as tf
import keras.backend as K
from keras.layers import LSTM,Input,Lambda
my_state = Input(shape=(128,))
print('keras input layer type:')
print(my_state)
print(K.is_keras_tensor(my_state))
my_state = tf.placeholder(shape=(None,128),dtype=tf.float32)
print('\ntensorflow tensor type:')
print(my_state)
print(K.is_keras_tensor(my_state))
# you may need it
my_state = Lambda(lambda x:x)(my_state)
print('\nconvert tensorflow to keras tensor:')
print(my_state)
print(K.is_keras_tensor(my_state))
# print
keras input layer type:
Tensor("input_3:0", shape=(?, 128), dtype=float32)
True
tensorflow tensor type:
Tensor("Placeholder:0", shape=(?, 128), dtype=float32)
False
convert tensorflow to keras tensor:
Tensor("lambda_1/Identity:0", shape=(?, 128), dtype=float32)
True