【问题标题】:Tensorflow - pick values from indicies, what is the operation called?Tensorflow - 从指标中选择值,这个操作叫什么?
【发布时间】:2017-07-18 06:53:22
【问题描述】:

一个例子

假设我有一个张量values,形状为(2,2,2)

values = [[[0, 1],[2, 3]],[[4, 5],[6, 7]]]

还有一个张量indicies,形状为(2,2),它描述了在最内层维度中要选择的值

indicies = [[1,0],[0,0]]

那么结果将是具有这些值的(2,2) 矩阵

result = [[1,2],[4,6]]

tensorflow中这个操作叫什么,怎么做?

一般

注意上面的形状(2,2,2)只是一个例子,它可以是任何维度。此操作的一些条件:

  • ndim(values) -1 = ndim(indicies)
  • values.shape[:-1] == indicies.shape == result.shape
  • indicies.max() < values.shape[-1] -1

【问题讨论】:

    标签: python numpy tensorflow


    【解决方案1】:

    我认为您可以使用tf.gather_nd 来效仿。您只需将“您的”索引转换为适合tf.gather_nd 的表示。以下示例与您的具体示例相关联,即形状为(2, 2, 2) 的输入张量,但我认为这让您了解如何编写任意形状的输入张量的转换,尽管我不确定它有多容易实现这一点(没有考虑太久)。另外,我并不是说这是最简单的解决方案。

    import tensorflow as tf
    import numpy as np
    
    values = np.array([[[0, 1], [2, 3]], [[4, 5], [6, 7]]])
    values_tf = tf.constant(values)
    indices = np.array([[1, 0], [0, 0]])
    
    converted_idx = []
    for k in range(values.shape[0]):
        outer = []
        for l in range(values.shape[1]):
            inds = [k, l, indices[k][l]]
            outer.append(inds)
            print(inds)
        converted_idx.append(outer)
    
    with tf.Session() as sess:
        result = tf.gather_nd(values_tf, converted_idx)
        print(sess.run(result))
    

    打印出来

    [[1 2]
     [4 6]]
    

    编辑:在这里处理任意形状是一个递归解决方案,应该可以工作(仅在您的示例中测试):

    def convert_idx(last_dim_vals, ori_indices, access_to_ori, depth):
        if depth == len(last_dim_vals.shape) - 1:
            inds = access_to_ori + [ori_indices[tuple(access_to_ori)]]
            return inds
    
        outer = []
        for k in range(ori_indices.shape[depth]):
            inds = convert_idx(last_dim_vals, ori_indices, access_to_ori + [k], depth + 1)
            outer.append(inds)
        return outer
    

    您可以将它与我发布的原始代码一起使用,如下所示:

    ...
    converted_idx = convert_idx(values, indices, [], 0)
    with tf.Session() as sess:
        result = tf.gather_nd(values_tf, converted_idx)
        print(sess.run(result))
    

    【讨论】:

      猜你喜欢
      • 2014-03-05
      • 2011-04-15
      • 1970-01-01
      • 2010-11-09
      • 2023-02-21
      • 1970-01-01
      • 1970-01-01
      • 2016-11-06
      相关资源
      最近更新 更多