2

I have two dictionaries below:

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

I have an input string tensor X. I would like to use X an index in word2int as shown below:

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

Question:

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

Hung Le
  • 31
  • 7

1 Answers1

3

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

It is not possible to get string value unless calling sess.run(string_tensor).


It is worth to mention there is a cleaner way to convert ids to words or vice-versa with index_table_from_file. Here is a an example of how you can use it.

Amir
  • 16,067
  • 10
  • 80
  • 119