【问题标题】:How to sort a multi-dimensional tensor using the returned indices of tf.nn.top_k?如何使用 tf.nn.top_k 的返回索引对多维张量进行排序?
【发布时间】:2017-01-27 15:15:29
【问题描述】:

我有两个多维张量 ab。我想按a 的值对它们进行排序。

我发现tf.nn.top_k 能够对张量进行排序并返回用于对输入进行排序的索引。如何使用从tf.nn.top_k(a, k=2) 返回的索引对b 进行排序?

例如,

import tensorflow as tf

a = tf.reshape(tf.range(30), (2, 5, 3))
b = tf.reshape(tf.range(210), (2, 5, 3, 7))
k = 2
sorted_a, indices = tf.nn.top_k(a, k)

# How to sort b into
# sorted_b[0, 0, 0, :] = b[0, 0, indices[0, 0, 0], :]
# sorted_b[0, 0, 1, :] = b[0, 0, indices[0, 0, 1], :]
# sorted_b[0, 1, 0, :] = b[0, 1, indices[0, 1, 0], :]
# ...

更新

结合tf.gather_ndtf.meshgrid 可以是一种解决方案。比如下面的代码在python 3.5上用tensorflow1.0.0-rc0测试:

a = tf.reshape(tf.range(30), (2, 5, 3))
b = tf.reshape(tf.range(210), (2, 5, 3, 7))
k = 2

sorted_a, indices = tf.nn.top_k(a, k)

shape_a = tf.shape(a)
auxiliary_indices = tf.meshgrid(*[tf.range(d) for d in (tf.unstack(shape_a[:(a.get_shape().ndims - 1)]) + [k])], indexing='ij')

sorted_b = tf.gather_nd(b, tf.stack(auxiliary_indices[:-1] + [indices], axis=-1))

不过,不知道有没有更易读的解决方案,不需要在上面创建auxiliary_indices

【问题讨论】:

  • 正如你所说,应该可以使用tf.gather_nd 来解决它,可能与tf.meshgrid 结合使用,但经过一段时间的尝试我无法...
  • @jdehesa 感谢分享tf.meshgrid。我用一种可能的解决方案更新了这个问题。
  • 那太好了,我自己在某个时候可能真的需要它! :) 如果您仍然想要更好的解决方案,可以将问题留待解决,但以防万一您不知道(也许您知道),如果您愿意,it is okay to answer you own questions

标签: tensorflow


【解决方案1】:

您的代码有问题。

b = tf.reshape(tf.range(60), (2, 5, 3, 7))

因为 TensorFlow 无法将具有 60 个元素的张量重塑为 [2,5,3,7](210 个元素)。 而且您不能使用 3 阶张量的索引对 4 阶张量 (b) 进行排序。

【讨论】:

  • 我很抱歉错字。我已经纠正了错误。 (tf.reshape(tf.range(210), (2, 5, 3, 7)))。当b 是 2 阶张量,indices 是 1 阶张量时,tf.gather(b, indices) 可以解决问题。当indices 是秩> 1 的张量时,我认为tf.gather_nd 可以提供帮助,但它需要生成一些辅助索引作为tf.gather_nd 的输入。不知道有没有更灵活、更高效的解决方案。
猜你喜欢
  • 1970-01-01
  • 2013-12-30
  • 2015-08-27
  • 2021-11-25
  • 1970-01-01
  • 2019-02-05
  • 2021-12-30
  • 1970-01-01
  • 2019-09-15
相关资源
最近更新 更多