简体   繁体   中英

Tensorflow transform tensor with vector lookups

Given a fixed dictionary with unique keys and values (all numbers are non-negative integers):

d = {(1,3): 6, (5,4): 9}

what would be an efficient way in tensorflow to transform:

tf.constant([[1,3], [5,4], [1,3]]) -> tf.constant([6, 9, 6])

and vice versa:

tf.constant([6, 9, 6]) -> tf.constant([[1,3], [5,4], [1,3]])

As @OphirYoktan mentions, there's a lookup operator. I would recommend using tf.embedding_lookup but since you are aiming to also map vector - id you could do the following.

Use tf.map_fn

d_inverse = {v:k for k,v in d.items()}
d_mapped = tf.map_fn(lambda x: d[x], d.values())
d_mapped_inverse = tf.map_fn(lambda x: d_inverse[x], d_inverse.items()}

You only need to set the values in the dicts d and d_inverse as tf.constants

Having said that, these mappings should have to do with computational reasons regarding your graph, otherwise I would advice you to do them outside the graph.

在tensorflow中有一个lookuptable模块-文档位于: https ://www.tensorflow.org/api_docs/python/tf/contrib/lookup

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM