`Chapter 11 part 02 sequence models: tf.one_hot() inside the keras model error
Closed this issue · 2 comments
gayanlanke commented
import tensorflow as tf
inputs = keras.Input(shape=(None,), dtype="int64")
embedded = tf.one_hot(inputs, depth=max_tokens)
x = layers.Bidirectional(layers.LSTM(32))(embedded)
x = layers.Dropout(0.5)(x)
outputs = layers.Dense(1, activation="sigmoid")(x)
model = keras.Model(inputs, outputs)
model.compile(optimizer="rmsprop",
loss="binary_crossentropy",
metrics=["accuracy"])
model.summary()
Error message:
ValueError: A KerasTensor cannot be used as input to a TensorFlow function. A KerasTensor is a symbolic placeholder for a shape and dtype, used when constructing Keras Functional models or Keras Functions. You can only use it as input to a Keras layer or a Keras operation (from the namespaces keras.layers and keras.operations). You are likely doing something like:
x = Input(...)
...
tf_fn(x) # Invalid.
What you should do instead is wrap tf_fn in a layer:
class MyLayer(Layer):
def call(self, x):
return tf_fn(x)
x = MyLayer()(x)
The solution can be found here
class EmbeddedLayer(keras.Layer):
def call(self, x):
return tf.one_hot(x, depth=max_tokens)
inputs = keras.Input(shape=(None,), dtype="int64")
embedded = EmbeddedLayer()(inputs)
x = layers.Bidirectional(layers.LSTM(32))(embedded)
x = layers.Dropout(0.5)(x)
outputs = layers.Dense(1, activation="sigmoid")(x)
model = keras.Model(inputs, outputs)
model.compile(
optimizer="rmsprop",
loss="binary_crossentropy",
metrics=["accuracy"],
)
model.summary()
ifond commented
I have received your E-mail——Steven Lee
gayanlanke commented
Found the solution in #239.
Thanks.