用形状为(x,y)的二维布尔蒙版掩盖形状为(x,y,z)的3维张量

时间:2018-09-04 16:23:12

标签: python tensorflow

我有以下张量,output,形状为(2,6,2):

[[[0.4 0.2]
  [0.7 0.5]
  [0.4 0.1]
  [0.5 0.4]
  [0.9 0.7]
  [0.2 0.9]]

 [[0.6 0.6]
  [0.3 0.5]
  [0.7 0.2]
  [0.8 0.1]
  [0.3 0.5]
  [0.4 0.7]]]

,并具有以下布尔蒙版张量,mask,形状为(2,6):

mask = tf.sequence_mask(lengths=[3, 4] maxlen=6)

[[ True  True  True False False False]
 [ True  True  True  True False False]]

如何使用mask(或对其进行调整)来应用masked_output = tf.boolean_mask(output, masks),结果如下:

[[[0.4 0.2]
  [0.7 0.5]
  [0.4 0.1]
  [0.0 0.0]
  [0.0 0.0]
  [0.0 0.0]]

 [[0.6 0.6]
  [0.3 0.5]
  [0.7 0.2]
  [0.8 0.1]
  [0.0 0.0]
  [0.0 0.0]]]

编辑

以下更改,但看起来仍然很麻烦。任何其他建议,表示赞赏。

mask = tf.sequence_mask(lengths=[[3, 3], [4, 4]] maxlen=6)
mask = tf.transpose(mask, [0, 2, 1])

1 个答案:

答案 0 :(得分:0)

可能不是最有效的方法,但它可行

flat_mask = tf.reshape(mask, shape=(-1,))
expanded_flat_mask = tf.tile(flat_mask, [2])
expanded_mask = tf.reshape(expanded_flat_mask, shape=(2, 6, 2))
masked_output = tf.boolean_mask(output, expanded_mask)

或者

masked_output = output * tf.cast(tf.expand_dims(mask, axis=-1), output.dtype)