Python – tensorflow.boolean_mask() 方法
TensorFlow 是由 Google 设计的开源Python库,用于开发机器学习模型和深度学习神经网络。 boolean_mask()是用于将布尔掩码应用于张量的方法。
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 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.
示例 1:在此示例中,输入为一维。
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)
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)
输出:
Tensor: [1, 2, 3]
Mask: [False, True, True]
Result: tf.Tensor([2 3], shape=(2,), dtype=int32)
示例 2:在此示例中,采用二维输入。
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)
输出:
Tensor: [[1, 2], [10, 14], [9, 7]]
Mask: [False, True, True]
Result: tf.Tensor(
[[10 14]
[ 9 7]], shape=(2, 2), dtype=int32)