【问题标题】:equivalent list comprehension in tensorflow张量流中的等效列表理解
【发布时间】:2017-05-31 12:10:56
【问题描述】:

如何使用字典将包含 N int 的等级 1 的张量修改为包含大小为 M 的 N 向量的等级 2 的张量

在 python 中类似于:

dict = {1 : [1,2,3] , 2 : [3,2,1]}
array1 = np.array([1,1,2,1,2])
array2 = np.array([dict[x] for x in array1])

但我无法迭代张量(除了 while 循环,但我认为这不是最佳解决方案)

【问题讨论】:

    标签: python tensorflow list-comprehension tensor


    【解决方案1】:

    如果你的字典是这样的

    dict = {1: tf.constant([1, 2, 3]), 2: tf.constant([1, 2, 3])}
    tensor1 = tf.constant([1, 1, 2, 1, 2])
    

    那么这样的事情应该可以完成:

    vals = [dict[tensor1[k]] for k in range(tensor1.get_shape().as_list()[0])]
    tensor2 = tf.stack(vals, axis=0)
    

    如果你有未知的维度,它会变得更加复杂。例如,如果 tensor1 的形状未知,我看不到不涉及 tf.while_loop 的解决方案。

    【讨论】:

    • 我想我错过了一些我得到错误 KeyError:
    • 我得到 TypeError: Tensor is unhashable if Tensor equal is enabled。相反,使用 tensor.experimental_ref() 作为键。
    猜你喜欢
    • 1970-01-01
    • 2021-03-16
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-03
    • 2018-10-31
    • 1970-01-01
    相关资源
    最近更新 更多