首页 文章

张量切片和张量应用函数

提问于
浏览
0

我有两个问题:

  • 设张量 T 的形状 [n1, n2, n3, n4] . 让另一个张量为 IDX 且形状为 [n1, n2]int 类型包含所需的索引 . 我怎样才能获得形状张量 [n1, n2, n4] 我想要只提取 n3n3 dim中的那些索引,这些索引在 IDX 中指定 . 简单的例子:
x = [[[2, 3, 1, 2, 5],
   [7, 1, 5, 6, 0],
   [7, 8, 1, 3, 8]],
  [[0, 7, 7, 6, 9],
   [5, 6, 7, 8, 8],
   [2, 3, 2, 9, 6]]]
idx = [[1, 0, 2],
   [4, 3, 3]]
res = [[3, 7, 1],
   [9, 8, 9]]`
  • 给定一个采用1D张量函数func(x,y)的函数如何将其应用于最后一维上的4D张量X,Y,即结果 - 结果为[张,张,k] = f的X张量(X [对于所有i,j,k,i,j,k,:],Y [i,j,k,:]) . 我找到了tf.py_func,但在我的情况下无法获得如何使用它 .

在此先感谢您的帮助!

1 回答

  • 1

    我用 tf.gather_nd 处理问题1 .

    输入是:

    • x :你的张量 T 从中提取形状 [n1, n2, n3, n4]

    • 我使用了从0到 size(T) 的更清晰的值

    • idx :要从 T 中提取的索引,形状 [n1, n2] 并包含 0n3 - 1 的值

    结果是:

    • res :为 idx 中的每个indice提取的 T 值,形状 [n1, n2, n4]

    由于 tf.gather_nd() 期望您创建要在 x 中检索的整个索引(例如 [1, 0, 4, 1] ),我们必须首先在 indices_base 中创建它 .

    参数 indices 需要成形 res + R ,即 [n1, n2, n4, R] ,其中 R=4 是Tensor x 的等级 .

    # Inputs:
    n1 = 2
    n2 = 3
    n3 = 5
    n4 = 2
    x = tf.reshape(tf.range(n1*n2*n3*n4), [n1, n2, n3, n4])  # range(60) reshaped
    idx = tf.constant([[1, 0, 2], [4, 3, 3]])  # shape [n1, n2]
    
    range_n1 = tf.reshape(tf.range(n1), [n1, 1, 1, 1])
    indices_base_1 = tf.tile(range_n1, [1, n2, n4, 1]) 
    
    range_n2 = tf.reshape(tf.range(n2), [1, n2, 1, 1])
    indices_base_2 = tf.tile(range_n2, [n1, 1, n4, 1])
    
    range_n4 = tf.reshape(tf.range(n4), [1, 1, n4, 1])
    indices_base_4 = tf.tile(range_n4, [n1, n2, 1, 1])
    
    idx = tf.reshape(idx, [n1, n2, 1, 1])
    idx = tf.tile(idx, [1, 1, n4, 1])
    
    # Create the big indices needed of shape [n1, n2, n3, n4]
    indices = tf.concat(3, [indices_base_1, indices_base_2, idx, indices_base_4])
    
    # Finally we can apply tf.gather_nd
    res = tf.gather_nd(x, indices)
    

    无论如何,这是非常复杂的,我不确定它是否能产生良好的性能 .

    P.S:你应该在一个单独的帖子中发布问题2 .

相关问题