tensorflow - Tensorflow:根据布尔掩码重塑张量
问题描述
我有一个一维张量值: a = tf.constant([0.1, 0.2, 0.3, 0.4])
和一个 nD 布尔掩码: b = tf.constant([[1, 1, 0], [0, 1, 1]])
b 中 1 的总数与 a 的长度相匹配。
如何从 a 和 b 获得 [[0.1, 0.2, 0.0], [0.0, 0.3, 0.4]]?
解决方案
import tensorflow as tf
a = tf.constant([0.1, 0.2, 0.3, 0.4])
b = tf.constant([[1, 1, 0], [0, 1, 1]])
# reshape b to a 1D vector
b_res = tf.reshape(b, [-1])
# Get the indices to gather using cumsum
b_cum = tf.cumsum(b_res) - 1
# Gather the elements, multiply by b_res to zero out the unwanted values and reshape back
c = tf.reshape(tf.gather(a, b_cum) * tf.cast(b_res, 'float32'), [-1, 3])
print(c)
推荐阅读
- angularjs - AngularJs 视图加载超过 1300 项需要太长时间
- keyboard - 死键在 Remmina,RDP 连接中不起作用
- kubernetes - 是否可以在 kubeadm 集群中创建集群 Autoscaler?
- reactjs - 为什么 useState 不呈现 API 响应?
- firebase - Firebase 身份验证数据库规则
- python - 为什么我不能分配`cls.__hash__ = id`?
- vue.js - 在两个子组件Vue js之间共享数据
- codeigniter - Codeigniter 4分页404文件未找到错误
- sql - 特定的 SUM
- reactjs - @types/styled-components 返回类型 any 而不是 StyledComponent。预期的行为?