Skip to main content
 首页 » 编程设计

python之Tensorflow之带条件的掩码张量元素

2024年09月03日29lonelyxmas

我有两个张量,一个是形状为 [batch_size, timestep, feature] 的 3d 张量,另一个是形状为 [batch_size, timestep] 的二维张量

例如。

data = tf.constant([[[0, 0], [1, 1], [2, 2]], [[3, 3], [4, 4], [5, 5]]], dtype=tf.float32) # shape=(2, 3, 2) 
mask = tf.constant([[True, True, False], [False, True, True]]) # shape=(2, 3) 

我想根据数据调整掩码

#Desired output (mask timestep with value -1) 
[[[0, 0], [1, 1], [-1, -1]], [[-1, -1], [4, 4], [5, 5]]] 

是否有任何具有 tensorflow 内置功能的解决方案或其他解决方法来执行此操作?

请您参考如下方法:

我更喜欢使用tf.tile() 操作来展开 mask :

data = tf.constant([[[0, 0], [1, 1], [2, 2]], [[3, 3], [4, 4], [5, 5]]], dtype=tf.float32) 
mask = tf.constant([[True, True, False], [False, True, True]]) 
 
mask_expand = tf.tile(tf.expand_dims(mask, axis=-1), multiples=[1,1, tf.shape(data)[-1]]) 
 
minus_ones = tf.fill(tf.shape(data), tf.constant(-1, dtype=data.dtype)) 
data = tf.where(mask_expand, data, minus_ones)