Python – tensorflow.boolean_mask() method

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 know statically.
  • axis: It’s a 0-dimensional tensor which represets 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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output:

Tensor:  [[1, 2], [10, 14], [9, 7]]
Mask:  [False, True, True]
Result:  tf.Tensor(
[[10 14]
 [ 9  7]], shape=(2, 2), dtype=int32)



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.