20

In my previous question, I used Keras' Layer.set_input() to connect my Tensorflow pre-processing output tensor to my Keras model's input. However, this method has been removed after Keras version 1.1.1.

How can I achieve this in newer Keras versions?

Example:

# 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'))
Community
  • 1
  • 1
Qululu
  • 1,040
  • 2
  • 12
  • 23

1 Answers1

17

After you are done with pre-processing, You can add the tensor as input layer by calling tensor param of Input

So in your case:

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))
indraforyou
  • 8,969
  • 3
  • 49
  • 40
  • 12
    On this line `model.add(Input(tensor=tf_embedding_input))`, the following **error is raised**: `TypeError: The added layer must be an instance of class Layer. Found: Tensor("tf_embedding_input:0", shape=(?, 23), dtype=int64)`. I **solved this** by changing the line to `model.add(InputLayer(input_tensor=embedding_input))`. Thanks for pointing me in the right direction though! – Qululu Mar 01 '17 at 07:51
  • 1
    No problem, I usually use the functional `Model` and not `Sequential` where `Input` works, but glad that you fixed it at your end – indraforyou Mar 01 '17 at 08:42
  • Yes, I had previously used the functional `Model` and wrapped the pre-processing in a `Lambda` layer following an `Input` layer: `Lambda(preprocess_func, ...)`. Can I assume that, practically, this achieves the same thing? – Qululu Mar 01 '17 at 08:45
  • 1
    It should .. infact I was about to suggest the same in my answer. But then I saw you are creating a placeholder for string `tf.placeholder(tf.string)`. And since I don't work on NLP, I was not certain if it plays will with keras – indraforyou Mar 01 '17 at 08:51