首页 文章

Tensorflow - 从指标中选择值,所谓的操作是什么?

提问于
浏览
1

一个例子

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

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

并且具有形状 (2,2) 的张量 indicies 描述了在最内层维度中选择的值

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

1 回答

  • 0

    我想你可以用 tf.gather_nd 模仿这个 . 您只需将"your" indices转换为适合 tf.gather_nd 的表示 . 下面的示例与您的具体示例相关联,即形状 (2, 2, 2) 的输入张量,但我认为这可以让您了解如何为任意形状的输入张量编写转换,但我不确定实现它的容易程度这个(避免't thought about it too long). Also, I'米并没有声称这是最简单的解决方案 .

    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]]
    

    Edit :在这里处理任意形状是一个应该起作用的递归解决方案(仅在您的示例中测试):

    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))
    

相关问题