TensorFlow使用Embedding报错NotFoundError,求解决方案
Hey there, let's get that Embedding layer working properly! The error you're seeing happens because the trainable weights (embedding matrix) of your Embedding layer haven't been initialized yet—TensorFlow hasn't allocated any resources for them, so the session can't locate the required embedding tensor.
Here's the step-by-step fix:
You need to explicitly initialize all global variables in your TensorFlow session before running any operations that depend on them. Add this line right after creating your session:
input_question_ = Input((query_maxlen,)) embedded_question = Embedding(vocab_size, embedding_dim)(input_question_) sess = tf.Session() # Initialize all global variables (including the Embedding layer's weights) sess.run(tf.global_variables_initializer()) # Now this will work correctly sess.run(embedded_question, feed_dict={ input_question_: queries_train})
Why this works:
When you create an Embedding layer, TensorFlow defines the embedding matrix as a trainable variable, but it doesn't automatically allocate memory or set initial values for it. The tf.global_variables_initializer() operation tells TensorFlow to initialize all such variables in the graph, which creates the necessary resources (like the localhost/embedding_1/embeddings resource your error mentions).
Bonus tip (if you prefer Keras workflows):
Since you're using Keras' Input and Embedding layers, you could also wrap this into a Keras model and use Keras' built-in methods instead of raw TensorFlow sessions—this handles initialization automatically:
from tensorflow.keras.models import Model input_question_ = Input((query_maxlen,)) embedded_question = Embedding(vocab_size, embedding_dim)(input_question_) model = Model(inputs=input_question_, outputs=embedded_question) # No need for manual session initialization—Keras handles it embeddings_output = model.predict(queries_train)
内容的提问来源于stack exchange,提问作者Mahmud

