gpt4 book ai didi

sorting - 如何在 tensorflow 中对一批二维张量进行排序?

转载 作者:行者123 更新时间:2023-12-05 03:07:45 25 4
gpt4 key购买 nike

我有一个张量A,形状为[#batch, #MaxSequence, #Features],其中第 2 维的实际长度(可能小于#MaxSequence) 存储在张量 L 中。我想在每个批处理的序列中按第 3 维中的第 2 个特征对 A 进行排序。我看到这个 post使用 tf.gathertf.nn.top_k 对 2D 张量进行排序,但我不知道将其应用于 3D 情况。我需要使用循环来完成吗?

最佳答案

我有一些工作,但它可能存在更好的解决方案。我想我的代码对于这个简单的问题可能过于复杂了。

我们的想法是,我们必须转换 tf.nn.top_k(a[:,:,1].indices 的返回索引(按三维中的第二个特征排序) tf.gather_nd 可以使用。特别是对于我下面的例子,我们需要转换张量

 [[3, 2, 1, 0],
[0, 1, 2, 3],
[2, 0, 3, 1]]

 [[[0 3], [0 2], [0 1], [0 0]]
[[1 0], [1 1], [1 2], [1 3]]
[[2 2], [2 0], [2 3], [2 1]]]

我发现了什么:

  • 首先展平目标索引,因此我们得到 [3 2 1 0 0 1 2 3 2 0 3 1]
  • 有意构造一个配对向量[0 0 0 0 1 1 1 1 2 2 2]
  • tf.stack 上面的两个向量,然后我们将结果 reshape 为我们想要的结果。

完整的 tf 代码如下(get_shape 方法定义 here ):

import tensorflow as tf
a = tf.Variable([[[0.51, 0.52, 0.53, 0.94, 0.35],
[0.32, 0.72, 0.83, 0.74, 0.55],
[0.23, 0.73, 0.63, 0.64, 0.35],
[0.01, 0.74, 0.73, 0.04, 0.75]],
[[0.32, 0.76, 0.83, 0.74, 0.55],
[0.23, 0.72, 0.63, 0.64, 0.35],
[0.11, 0.02, 0.03, 0.14, 0.15],
[0.01, 0.00, 0.73, 0.04, 0.75]],
[[0.51, 0.52, 0.53, 0.94, 0.35],
[0.32, 0.00, 0.83, 0.74, 0.55],
[0.23, 0.92, 0.63, 0.64, 0.35],
[0.11, 0.02, 0.03, 0.14, 0.15]]], tf.float32)
batch_size, seq_length, num_features = get_shape(a)

idx = tf.reshape(range(batch_size), [-1, 1])
idx_flat = tf.reshape(tf.tile(idx, [1, seq_length]), [-1])
top_k_flat = tf.reshape(tf.nn.top_k(a[:,:,1],
k=seq_length).indices, [-1])
final_idx = tf.reshape(tf.stack([idx_flat, top_k_flat], 1),
[batch_size, seq_length, 2])
reordered = tf.gather_nd(a, final_idx)
sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
print sess.run(reordered)

#ORDERED
#by this
#Column (within each example)
[[[ 0.01 , 0.74000001, 0.73000002, 0.04 , 0.75 ],
[ 0.23 , 0.73000002, 0.63 , 0.63999999, 0.34999999],
[ 0.31999999, 0.72000003, 0.82999998, 0.74000001, 0.55000001],
[ 0.50999999, 0.51999998, 0.52999997, 0.94 , 0.34999999]],
[[ 0.31999999, 0.75999999, 0.82999998, 0.74000001, 0.55000001],
[ 0.23 , 0.72000003, 0.63 , 0.63999999, 0.34999999],
[ 0.11 , 0.02 , 0.03 , 0.14 , 0.15000001],
[ 0.01 , 0. , 0.73000002, 0.04 , 0.75 ]],
[[ 0.23 , 0.92000002, 0.63 , 0.63999999, 0.34999999],
[ 0.50999999, 0.51999998, 0.52999997, 0.94 , 0.34999999],
[ 0.11 , 0.02 , 0.03 , 0.14 , 0.15000001],
[ 0.31999999, 0. , 0.82999998, 0.74000001, 0.55000001]]

注意在输出中,我们有三个例子。在每个示例中,序列按第二个特征降序排列。

关于sorting - 如何在 tensorflow 中对一批二维张量进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46572061/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com