【问题标题】:Tensorflow tf.gather with axis parameter带有轴参数的Tensorflow tf.gather
【发布时间】:2018-05-22 09:17:11
【问题描述】:

我正在使用 tensorflow 的 tf.gather 从多维数组中获取元素,如下所示:

import tensorflow as tf

indices = tf.constant([0, 1, 1])
x = tf.constant([[1, 2, 3],
                 [4, 5, 6],
                 [7, 8, 9]])

result = tf.gather(x, indices, axis=1)

with tf.Session() as sess:
    selection = sess.run(result)
    print(selection)

导致:

[[1 2 2]
 [4 5 5]
 [7 8 8]]

我想要的是:

[1
 5
 8]

如何使用tf.gather 在指定轴上应用单个索引? (与此答案中指定的解决方法相同的结果:https://stackoverflow.com/a/41845855/9763766

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    您需要将indices 转换为full indices,并使用gather_nd。可以通过这样做来实现:

    result = tf.squeeze(tf.gather_nd(x,tf.stack([tf.range(indices.shape[0])[...,tf.newaxis], indices[...,tf.newaxis]], axis=2)))
    

    【讨论】:

      猜你喜欢
      • 2021-02-25
      • 1970-01-01
      • 2016-06-20
      • 1970-01-01
      • 2018-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多