Search code examples
tensorflowshapesmask

Tensorflow boolean_mask with dynamic mask


The documentation of boolean_mask says that the shape of the mask must be known statically. But if you do

mask.set_shape([None])
tf.boolean_mask(tensor, mask)

it seems to work fine. Is there any reason to not do this?


Solution

  • Looking at the documentation closely reveals that it concerns the dimensionality of the mask, not its whole shape:

    mask: K-D boolean tensor, K <= N and K must be known statically.

    Your mask now has size None, meaning its static shape is completely unknown, including the dimension. Your options are to either to ensure that the dimensionality of the mask is statically known (e.g., make sure its produced by an operation whose output dimensions are known, or feed a placeholder with known dimensions), or to enforce information about the size that you know, but that cannot be inferred at time of the construction of the computational graph. The latter you can do by set_shape.

    When you run mask.set_shape([None]), you are enforcing an assumption that the dimensionality of the mask will always be 1 (since None is in brackets), although the number of elements is unknown. If you are certain that your mask will always be 1-dimensional, this is fine to do.