【发布时间】:2017-01-27 15:15:29
【问题描述】:
我有两个多维张量 a 和 b。我想按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_nd 和tf.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