【问题标题】:creating a dictionary with two tensors tensorFlow创建具有两个张量 tensorFlow 的字典
【发布时间】:2018-11-24 17:23:22
【问题描述】:

我有两个张量

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解决吗

【问题讨论】:

    标签: python-3.x tensorflow tensor


    【解决方案1】:

    您可以使用计数器来累积每个指数的值。这是来自 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]
    

    【讨论】:

    • 谢谢。这是在 Python 中执行此操作的好方法。我正在寻找张量流代码。这是我的深度学习模型的一部分。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-14
    • 1970-01-01
    • 1970-01-01
    • 2017-08-21
    • 2019-11-17
    • 2021-12-04
    相关资源
    最近更新 更多