Does tensorflow have the function similar to pytorch's "masked_fill_"

Viewed 1461

I want to set INF value to matrix by mask matrix, just like pytorch code:

scores.data.masked_fill_(y_mask.data, -float('inf'))

I try to use tf.map_fn to implement that, but the performance is too slow. So does tensorflow have any efficient function to implement that?

3 Answers

I have used a math calculate method to instead. It's valid and much faster.

def mask_fill_inf(matrix, mask):
    negmask = 1 - mask
    num = 3.4 * math.pow(10, 38)
    return (matrix * mask) + (-((negmask * num + num) - num))

Do anyone have the better method?

I am inspired by the above answer.

masked_fill ==>

def mask_fill_inf(matrix, mask):
    num = 3.4 * math.pow(10, 38)
    return (matrix + (-(((mask * num) + num) - num)))
Related