[英]KeyError: tf.Tensor 'Placeholder_6:0' shape=<unknown> dtype=string
Can you please explain the problem below? 您能解释下面的问题吗? Here is my code fragment in my python notebook: 这是我的python笔记本中的代码片段:
word2int = {}
int2word = {}
for i,word in enumerate(words):
word2int[word] = i
int2word[i] = word
def euclidean_dist(vec1, vec2):
return np.sqrt(np.sum((vec1-vec2)**2))
def find_closest(word_index, vectors):
min_dist = 10000 # to act like positive infinity
min_index = -1
query_vector = vectors[word_index]
for index, vector in enumerate(vectors):
if euclidean_dist(vector, query_vector) < min_dist and not np.array_equal(vector, query_vector):
min_dist = euclidean_dist(vector, query_vector)
min_index = index
return min_index
Z = tf.placeholder(tf.string)
find_closest_word = int2word[find_closest(word2int[Z], vectors)]
# Create SignatureDef metadata for the model
classification_inputs = tf.saved_model.utils.build_tensor_info(Z)
classification_outputs_classes = tf.saved_model.utils.build_tensor_info(find_closest_word)
classification_signature = (
tf.saved_model.signature_def_utils.build_signature_def(
inputs={
tf.saved_model.signature_constants.CLASSIFY_INPUTS:
classification_inputs
},
outputs={
tf.saved_model.signature_constants.CLASSIFY_OUTPUT_CLASSES:
classification_outputs_classes
},
method_name=tf.saved_model.signature_constants.CLASSIFY_METHOD_NAME))
Here is the error message when I run the code fragment above: 这是我运行上面的代码片段时的错误消息:
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-65-016dad8c7403> in <module>()
12 return min_index
13 Z = tf.placeholder(tf.string)
---> 14 find_closest_word = int2word[find_closest(word2int[Z], vectors)]
KeyError: <tf.Tensor 'Placeholder_7:0' shape=<unknown> dtype=string>
How can I convert a string tensor Z
to a python string so that it can be used as index in word2int
? 如何将字符串张量Z
转换为python字符串,以便可以将其用作word2int
索引?
From your code, I guess you think Z
is the word you pass as input to the network. 从您的代码中,我想您认为Z
是您作为输入传递给网络的单词。 It isn't, since you define it as Z = tf.placeholder(tf.string)
. 并非如此,因为您将其定义为Z = tf.placeholder(tf.string)
。 Z is thus a placeholder object that will eventually be filled with a string in your feed_dict
when you run the graph in a tf.Session
instance by calling its run()
method. 因此,Z是一个占位符对象,当您通过调用tf.Session
实例的run()
方法在其上run()
图形时, 最终将在feed_dict
使用字符串填充该对象。
Since your word2int
dictionary is just a string-to-index dict, you get the KeyError
when you try to use the placeholder as a key. 由于word2int
词典只是一个字符串到索引的字典,因此当您尝试使用占位符作为键时,会出现KeyError
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.