使用两个张量tensorFlow创建一个字典

时间:2018-06-14 20:58:50

标签: python-3.x tensorflow tensor

我有两个张量

top_k_values = [[0.1,0.2,0.3] 
                [0.4, 0.5,0.6]]
top_k_indices= [[1,3,5] 
                [2, 5,3]]

我想获取索引和值并创建字典

dict[1] = 0.1   
dict[2] = 0.4    
dict[3] = 0.2 + 0.6   
dict [5] = 0.3 + 0.5

我想按键排序这个词典,然后选择前3个索引 有人可以帮帮我吗 我一直在尝试使用map_fn。但这似乎并没有起作用

上述问题是否可以用tensorflow解决

1 个答案:

答案 0 :(得分:-1)

您可以使用计数器累积每个indice的值。这是来自python标准库。我不知道你是否可以对tensorflow库做同样的事情。

>>> from collections import counter
>>> d=Counter()
>>> for indice_list, value_list in zip(top_k_indices, top_k_values):
...     for indice, value in zip(indice_list, value_list):
...         d[indice] += value

>>> d
Counter({3: 0.8, 5: 0.8, 2: 0.4, 1: 0.1})
# this is your expected result

# a counter is a kind of dict, but if you need a real dict:
>>> dict(d)
{1: 0.1, 3: 0.8, 5: 0.8, 2: 0.4}

# 3 indices with maximum values
>>> d.most_common(3)
[(3, 0.8), (5, 0.8), (2, 0.4)]
>>> sorted([indice for indice, value in d.most_common(3)])
[2, 3, 5]