gpt4 book ai didi

python-3.x - 如何根据 tensorflow 中的条件获得最高的最小张量值

转载 作者:行者123 更新时间:2023-12-04 21:02:17 26 4
gpt4 key购买 nike

我有一个这样的张量:

sim_topics = [[0.65 0.   0.   0.   0.42  0.   0.   0.51 0.   0.34 0.]
[0. 0.51 0. 0. 0.52 0. 0. 0. 0.53 0.42 0.]
[0. 0.32 0. 0.50 0.34 0. 0. 0.39 0.32 0.52 0.]
[0. 0.23 0.37 0. 0. 0.37 0.37 0. 0.47 0.39 0.3 ]]

和一个像这样的 bool 张量:
bool_t = [False  True  True  True]

我想选择 sim_topics 的一部分基于 bool_t 中的 bool 标志在某种程度上它只是选择 top k smallest每行值(如果该行为真,则保持原样)。

所以预期的输出是这样的:(这里 k=2 )
[[0.65 0.   0.    0.   0.42  0.   0.   0.51 0.   0.34 0.]
[0. 0.51 0. 0. 0.52 0. 0. 0. 0.53 0.42 0.]
[0. 0.32 0. 0.50 0 0 0. 0. 0 0.32 0 ]
[0. 0.23 0 0. 0. 0 0 0. 0 0 0.3 ]]

我试图首先使用 boolean_mask 来完成此操作。和 where要获得我想要的指数,然后去获得最小的指数。但是,当我使用 where 时它没有给我提供 zero 的索引.

最佳答案

k = 2
dim0 = sim_topics.shape[0]
a = tf.cast(tf.equal(sim_topics,0), sim_topics.dtype)
b = tf.reshape(tf.reduce_sum(a,1) + k, (dim0,-1))
c = tf.cast(tf.argsort(tf.argsort(sim_topics,1),1), sim_topics.dtype)
d = tf.logical_or(tf.less(c,b),tf.reshape(tf.logical_not(bool_t),(dim0,-1)))
with tf.Session() as sess:
print(sess.run(sim_topics * tf.cast(d,sim_topics.dtype)))


[[0.65 0. 0. 0. 0.42 0. 0. 0.51 0. 0.34 0. ]
[0. 0.51 0. 0. 0. 0. 0. 0. 0. 0.42 0. ]
[0. 0.32 0. 0. 0. 0. 0. 0. 0.32 0. 0. ]
[0. 0.23 0. 0. 0. 0. 0. 0. 0. 0. 0.3 ]]

关于python-3.x - 如何根据 tensorflow 中的条件获得最高的最小张量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57581670/

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