Tensorflow张量值图 [英] Tensorflow tensor value map
问题描述
我的问题是如何用字典映射张量?例如像这样:
my question is how to map tensor with a dictionary? for example like this:
dict = {1:3, 2:4}
origin_tensor = tf.Variable([1,2,1], tf.int32)
字典很大.现在,如何根据 dict 制作映射选项以将张量映射到 tf.Variable([3,4,3], tf.int32) ?
The dictionary is large. Now, How can I make a map options to map the tensor to tf.Variable([3,4,3], tf.int32) according to the dict ?
另外,mapping的时候没有办法使用.eval(),可以认为origin_tensor是batch reader的标签张量.
What's more, it is no way to use .eval() when mapping, you can think the origin_tensor is a label tensor from batch reader.
推荐答案
在 Tensorflow 2.0(与未测试的早期版本的兼容性)中使用 tf.lookup
:
In Tensorflow 2.0 (compatibility with earlier versions not tested) use tf.lookup
:
dictionary = {1:3, 2:4}
origin_tensor = tf.Variable([1,2,1], dtype=tf.int64)
注意:dict
在python中是保留的,所以用dictionary
代替,dtype=tf.int32
用dtype代替=tf.int64
与 tf.lookup.KeyValueTensorInitializer
note: dict
is reserved in python so it is replaced with dictionary
and dtype=tf.int32
is replaced with dtype=tf.int64
for compatibility with tf.lookup.KeyValueTensorInitializer
这是原始张量:
origin_tensor
>> <tf.Variable 'Variable:0' shape=(3,) dtype=int64, numpy=array([1, 2, 1])>
这是由从 Python 字典初始化的键值张量构成的 Tensorflow 查找表:
This is the Tensorflow lookup table made from a key-value tensor initialized from a python dictionary:
table = tf.lookup.StaticVocabularyTable(
tf.lookup.KeyValueTensorInitializer(
list(dictionary.keys()),
list(dictionary.values()),
key_dtype=tf.int64,
value_dtype=tf.int64,
),
num_oov_buckets=1,
)
这是根据查找表返回具有所需元素的 result_tensor
的实际查找:
This is the actual lookup that returns the result_tensor
with desired elements based on the lookup table:
result_tensor = table.lookup(origin_tensor)
结果如下:
result_tensor
>> <tf.Tensor: id=400475, shape=(3,), dtype=int64, numpy=array([3, 4, 3])>
干杯!
这篇关于Tensorflow张量值图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!