首页 > 解决方案 > 如何根据张量流中的条件获得最小的张量值

问题描述

我有一个这样的张量:

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_t = [False  True  True  True]

sim_topics我想根据 bool 标志选择一部分,bool_t它只选择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_maskwhere获得我想要的索引来实现这一点,然后去获得最小的索引。但是,当我使用where它时,它并没有给我有 zero.

标签: python-3.xtensorflowdeep-learning

解决方案


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 ]]

推荐阅读