【问题标题】:How to retrieve specific elements from a 2 dimensional tensorflow array?如何从二维张量流数组中检索特定元素?
【发布时间】:2021-04-21 19:50:50
【问题描述】:

我有一个形状为 (4,2) 的张量

<tf.Tensor: shape=(4, 2), dtype=int32, numpy=
array([[0, 1],
       [2, 3],
       [4, 5],
       [6, 7]])>

如果我只从张量中选择元素,例如 1,2,5,6,我会怎么做,假设我有 2 个列表或 numpy 数组 M = [0,1,2,3] 和N=[1,0,1,0] 指定元素我如何访问它们,如果它是一个 numpy 数组,那么 array[M,N] 工作正常,但在 tensorflow 中它说:

Only integers, slices (`:`), ellipsis (`...`), tf.newaxis (`None`) and scalar tf.int32/tf.int64 tensors are valid indices, got array 

有具体的方法吗!?

【问题讨论】:

    标签: python arrays numpy tensorflow tensorflow2.0


    【解决方案1】:

    使用gather_nd():

    a = tf.constant([[0, 1],
           [2, 3],
           [4, 5],
           [6, 7]])
    M = [0,1,2,3]
    N = [1,0,1,0]
    
    inds = tf.stack((M, N))
    inds = tf.transpose(inds)
    res = tf.gather_nd(a, inds)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-12
      • 1970-01-01
      • 2019-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多