根据另一张量上的计数创建张量(tensorflow)

2024-05-15 05:03:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我想对一维张量进行排序,这样张量就会根据张量中项目的频率排序,比如给定这个张量[6,0,1,0,2,6,6],我想这样排序[6,6,6,0,0,1,2],目前为止我已经做到了:

ks = tf.constant([6,0,1,0,2,6,6])
unique_s, idx, cnts = tf.unique_with_counts(ks)
r = tf.gather(unique_s,tf.nn.top_k(cnts, k=(1+tf.reduce_max(idx))).indices)
s = tf.gather(cnts,tf.nn.top_k(cnts, k=(1+tf.reduce_max(idx))).indices)

其中r包含值[6,0,1,2],s包含[3,2,1,1]。现在,我想根据s中的计数展开r,所以在Python中,我们可以将上面的列表设置为:

^{pr2}$

但由于张量流中不允许迭代张量,我现在有点卡住了。在


Tags: 项目reduce排序tftopnnmax频率
1条回答
网友
1楼 · 发布于 2024-05-15 05:03:10

我相当肯定有一个更优雅的解决方案,但这里是:

这需要运行两个会话:

  1. 查找唯一值的数目
  2. 拆分、相乘和合并

代码:

import tensorflow as tf
ks = tf.constant([6,0,1,0,2,6,6])
unique_s, idx, cnts = tf.unique_with_counts(ks)
r = tf.gather(unique_s,tf.nn.top_k(cnts, k=(1+tf.reduce_max(idx))).indices)
# Dynamic length of r
len_r = tf.shape(r)
s = tf.gather(cnts,tf.nn.top_k(cnts, k=(1+tf.reduce_max(idx))).indices)

# Evaluate number of unique values
with tf.Session() as sess:
    splits = len_r.eval()[0]

# Split r & s into a list of tensors
split_r = tf.split(r, splits)
split_s = tf.split(s, splits)
# Tile r, s times
mult = [tf.tile(each_r,each_s) for each_r, each_s in zip(split_r, split_s)]
# Concatenate
join = tf.concat(mult, axis=0)

with tf.Session() as sess:
    print(join.eval())

输出[6 6 6 0 0 1 2]

相关问题 更多 >

    热门问题