tf.boolean_mask() 函数的作用是通过布尔值对指定的列的元素进行过滤。
语法结构boolean_mask(tensor, mask, name="boolean_mask", axis=None)
其中, tensor :被过滤的元素 mask :一堆bool值,它的维度不一定等于tensor return :mask为true对应的tensor的元素 当 tensor 与 mask 维度一致时,返回一维
1-D example examples1: >>> import numpy as np >>> import tensorflow as tf >>> a = [1, 2, 3, 4] >>> mask = np.array([True, True, False, False]) # mask 与 a 维度相同 >>> b = tf.boolean_mask(a, mask) >>> with tf.Session() as sess: print(sess.run(b)) print(b.shape)[1 2] (?,)
2-D example examples2: >>> import numpy as np >>> import tensorflow as tf >>> a = [[1, 2], [3, 4], [5, 6]] >>> mask = np.array([True, False, True]) # mask 与 a 维度不同 >>> b = tf.boolean_mask(a, mask) >>> with tf.Session() as sess: print(sess.run(b)) print(b.shape)[[1 2] [5 6]] (?, 2)
3-D example examples3: >>> import numpy as np >>> import tensorflow as tf >>> a = tf.constant([ [[2, 4], [4, 1]], [[6, 8], [2, 1]]], tf.float32) >>> mask = a > 2 # mask 与 a 维度相同 >>> b = tf.boolean_mask(a, mask) >>> with tf.Session() as sess: print(sess.run(a)) print(sess.run(mask)) print(sess.run(b)) print(b.shape)[[[2. 4.] [4. 1.]]
[[6. 8.] [2. 1.]]]
[[[False True] [ True False]]
[[ True True] [False False]]]
[4. 4. 6. 8.] (?,)
上面的 shape 有如下的规则: 假设 tensor.rank=4,维度为(m,n,p,q),则 (1)当mask.shape=(m,n,p,q),结果返回(?,),表示所有维度都被过滤 (2)当mask.shape=(m,n,p),结果返回(?,q),表示 q 维度没有过滤 (3)当mask.shape=(m,n),结果返回(?,p,q),表示 p,q 维度没有过滤 (4)当mask.shape=(m),结果返回(?,n,p,q),表示 n,p,q 维度没有过滤
tensorflow 使用一种叫tensor的数据结构去展示所有的数据,我们可以把tensor看成是n维的array或者list。在tensorflow的各部分图形间流动传递的只能是tensor。 tensorflow用3种方式描述一个tensor的维数:rank、shape、dimension number (维数),所以shape和rank的意思的一样的,只是表达的形式不同。
rank shape dimension 0 [ ] 0 维 1 [ D0 ] 1 维 2 [ D0, D1 ] 2 维 n [ D0, D1, …, Dn-1 ] n 维查看更多关于python中tf.boolean_mask()函数的使用的详细内容...