python - 将输入字符串张量转换为 python 字符串

标签 python tensorflow

我有以下两本词典:

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

我有一个输入字符串张量X。我想在 word2int 中使用 X 索引,如下所示:

X = tf.placeholder(tf.string)
find_closest_word = tf.convert_to_tensor(int2word[find_closest(word2int[X], vectors)], dtype=tf.string)

问题:

如何将字符串张量 X 转换为 python 字符串,以便将其用作 word2int 中的索引?

最佳答案

How can I convert a string tensor X to a python string so that it can be used as index in word2int?

除非调用sess.run(string_tensor),否则无法获取字符串值。


值得一提的是,有一种更简洁的方法可以将 id 转换为单词,反之亦然,使用 index_table_from_fileHere这是一个如何使用它的示例。

关于python - 将输入字符串张量转换为 python 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54319247/

相关文章:

python - 在 TensorFlow 中读取 jpeg 图像列表并将其转换为 TFRecords 的最快方法是什么?

python - 当批量大小=1时批量归一化

python - Pandas 分析隐藏标签

python - 导入 tflearn 非常慢

python - 使用 IronPython 覆盖 DLL 函数

tensorflow - 在 Anaconda OSX 上安装 Keras

java - java中libtensorflow_framework.so.1无法打开错误是什么意思

python - 针对特定指标在 tensorflow 中进行优化

python - 从 excel/vba 调用 python 脚本

python - 加载预先计算的向量 Gensim