TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks. boolean_mask() is method used to apply boolean mask to a Tensor.
Syntax: tensorflow.boolean_mask(tensor, mask, axis, name)
Parameters:
- tensor: It’s a N-dimensional input tensor.
- mask: It’s a boolean tensor with k-dimensions where k<=N and k is known statically.
- axis: It’s a 0-dimensional tensor which represents the axis from which mask should be applied. Default value for axis is zero and k+axis<=N.
- name: It’s an optional parameter that defines the name for the operation.
Return: It returns (N-K+1)-dimensional tensor which have the values that are populated against the True values in mask.
Example 1: In this example input is 1-D.
Python3
# importing the library import tensorflow as tf # initializing the inputs tensor = [ 1 , 2 , 3 ] mask = [ False , True , True ] # printing the input print ( 'Tensor: ' ,tensor) print ( 'Mask: ' ,mask) # applying the mask result = tf.boolean_mask(tensor, mask) # printing the result print ( 'Result: ' ,result) |
Output:
Tensor: [1, 2, 3] Mask: [False, True, True] Result: tf.Tensor([2 3], shape=(2,), dtype=int32)
Example 2: In this example 2-D input is taken.
Python3
# importing the library import tensorflow as tf # initializing the inputs tensor = [[ 1 , 2 ], [ 10 , 14 ], [ 9 , 7 ]] mask = [ False , True , True ] # printing the input print ( 'Tensor: ' ,tensor) print ( 'Mask: ' ,mask) # applying the mask result = tf.boolean_mask(tensor, mask) # printing the result print ( 'Result: ' ,result) |
Output:
Tensor: [[1, 2], [10, 14], [9, 7]] Mask: [False, True, True] Result: tf.Tensor( [[10 14] [ 9 7]], shape=(2, 2), dtype=int32)