带条件的张量流掩模张量元

2024-04-26 12:25:42 发布

您现在位置:Python中文网/ 问答频道 /正文

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

例如

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内置函数的解决方案或其他解决方法来做到这一点?你知道吗


Tags: 数据falsetruedatasizetfbatchmask
2条回答

我做了一个简单的解决方法(改变面具的形状),也许有更好的方法,但我现在想不出来。你知道吗

# reshape mask to the same shape with data
batch_size, total_timestep, feature_dimension = tf.shape(data)

# mask = [[[True], [True], [False]], [[False], [True], [True]]]
mask = tf.reshape(mask, [batch_size, total_timestep, 1]) # shape=(2, 3, 1)
# mask = [[[True, True], [True, True], [False, False]], [[False, False], [True, True], [True, True]]]
mask = tf.broadcast_to(mask, [batch_size, total_timestep, feature_dimension]) # shape=(2, 3, 2)

# adapt mask
data = tf.where(mask, data, tf.constant(-1, dtype=data.dtype) )

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

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)

相关问题 更多 >