python-3.x - 如何根据张量流中的条件获得最小的张量值
问题描述
我有一个这样的张量:
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_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 - 如何重新分类熊猫数据框列?
- java - 将值返回给驱动程序时出现空异常错误
- ansible - 是否可以将 with_dict 与 with_items 结合使用?
- spring - 配置 Spring Security 5 Oauth 2 以使用 access_token uri 参数
- mysql - 将 sql 文件返回到 mysql 数据库时抑制警告
- php - 输入文件的表单编辑
- visual-studio - 创建或打开解决方案时出现 Visual Studio 2017 错误
- r - R正则表达式替换可变数量的周期之后的所有周期,前面有空格/行首
- outlook - 如何使用具有正确序列号的 ICS 更新 Outlook AppointmentItem?即如何确定序号?
- powerbi - 我们如何在 Switch 和 Format 函数中分配前缀字符