问题 如何设置具有Tensorflow张量的Keras层的输入?


在我的 上一个问题,我用过Keras' Layer.set_input() 将我的Tensorflow预处理输出张量连接到我的Keras模型的输入。然而, 此方法已被删除 在Keras版本之后 1.1.1

如何在较新的Keras版本中实现这一目标?

例:

# Tensorflow pre-processing
raw_input = tf.placeholder(tf.string)
### some TF operations on raw_input ###
tf_embedding_input = ...    # pre-processing output tensor

# Keras model
model = Sequential()
e = Embedding(max_features, 128, input_length=maxlen)

### THIS DOESN'T WORK ANYMORE ###
e.set_input(tf_embedding_input)
################################

model.add(e)
model.add(LSTM(128, activation='sigmoid'))
model.add(Dense(num_classes, activation='softmax'))

3813
2018-02-24 14:42


起源



答案:


完成预处理后,可以通过调用将张量作为输入层添加 tensor param of Input

所以在你的情况下:

tf_embedding_input = ...    # pre-processing output tensor

# Keras model
model = Sequential()
model.add(Input(tensor=tf_embedding_input)) 
model.add(Embedding(max_features, 128, input_length=maxlen))

10
2018-02-24 19:23



在这条线上 model.add(Input(tensor=tf_embedding_input)), 下列 提出错误: TypeError: The added layer must be an instance of class Layer. Found: Tensor("tf_embedding_input:0", shape=(?, 23), dtype=int64)。一世 解决了这个 通过将行更改为 model.add(InputLayer(input_tensor=embedding_input))。谢谢你指出我正确的方向! - Qululu
没问题,我通常使用功能 Model 并不是 Sequential 哪里 Input 有效,但很高兴你把它修好了 - indraforyou
是的,我之前使用过功能 Model 并将预处理包装在一个 Lambda 层后面的 Input 层: Lambda(preprocess_func, ...)。我能否认为,实际上,这实现了同样的目的? - Qululu
它应该......事实上,我将在我的答案中提出同样的建议。但后来我发现你正在为字符串创建一个占位符 tf.placeholder(tf.string)。由于我不在NLP上工作,我不确定它是否会与keras一起玩 - indraforyou


答案:


完成预处理后,可以通过调用将张量作为输入层添加 tensor param of Input

所以在你的情况下:

tf_embedding_input = ...    # pre-processing output tensor

# Keras model
model = Sequential()
model.add(Input(tensor=tf_embedding_input)) 
model.add(Embedding(max_features, 128, input_length=maxlen))

10
2018-02-24 19:23



在这条线上 model.add(Input(tensor=tf_embedding_input)), 下列 提出错误: TypeError: The added layer must be an instance of class Layer. Found: Tensor("tf_embedding_input:0", shape=(?, 23), dtype=int64)。一世 解决了这个 通过将行更改为 model.add(InputLayer(input_tensor=embedding_input))。谢谢你指出我正确的方向! - Qululu
没问题,我通常使用功能 Model 并不是 Sequential 哪里 Input 有效,但很高兴你把它修好了 - indraforyou
是的,我之前使用过功能 Model 并将预处理包装在一个 Lambda 层后面的 Input 层: Lambda(preprocess_func, ...)。我能否认为,实际上,这实现了同样的目的? - Qululu
它应该......事实上,我将在我的答案中提出同样的建议。但后来我发现你正在为字符串创建一个占位符 tf.placeholder(tf.string)。由于我不在NLP上工作,我不确定它是否会与keras一起玩 - indraforyou