Tensorflow Dictionary lookup with String tensor

后端 未结 4 2208
名媛妹妹
名媛妹妹 2020-12-29 20:35

Is there any way to perform a dictionary lookup based on a String tensor in Tensorflow?

In plain Python, I\'d do something like

value = dictionary[ke         


        
4条回答
  •  被撕碎了的回忆
    2020-12-29 21:21

    tf.gather can help you, but it only gets values of list. You can convert dictionary into key and value lists, and then apply tf.gather. Example:

    # Your dict
    dict_ = {'a': 1.12, 'b': 5.86, 'c': 68.}
    # concrete query
    query_list = ['a', 'c']
    
    # unpack key and value lists
    key, value = list(zip(*dict_.items()))
    # map query list to list -> [0, 2]
    query_list = [i for i, s in enumerate(key) if s in query_list]
    
    # query as tensor
    query = tf.placeholder(tf.int32, shape=[None])
    # convert value list to tensor
    vl_tf = tf.constant(value)
    # get value
    my_vl = tf.gather(vl_tf, query)
    
    # session run
    sess = tf.InteractiveSession()
    sess.run(my_vl, feed_dict={query:query_list})
    

提交回复
热议问题