tf.boolean_mask()函数的使用,顺便学习>和<逻辑表达式
在做目标检测(YOLO)时涉及到一个函数boolean_mask(a,b) 将使a (m维)矩阵仅保留与b中“True”元素同下标的部分。使用tf.boolean_mask用来过滤概率值比较低的锚盒,这个函数的一个参数b为滤波器掩模,生成掩模要用到逻辑表达式(>或者<)生成布尔值,假设阈值threshold=C,并且当mask和tensor的维度相同时,输出1维矩阵。
重点看例子:
import numpy as np
import tensorflow as tf
a = tf.constant([
[[2,4],[4,1]],
[[6,8],[2,1]]
],tf.float32)
b = tf.reduce_max(a,-1)
c= a >2
print("a="+str(sess.run(a)))
print("b="+str(sess.run(b)))
print("c="+str(sess.run(c)))
d=tf.boolean_mask(a,c)
print("d="+str(d.eval(session=sess)))
print(d.shape)
运行结果如下:
a=[[[2. 4.]
[4. 1.]]
[[6. 8.]
[2. 1.]]]
b=[[4. 4.]
[8. 2.]]
c=[[[False True]
[ True False]]
[[ True True]
[False False]]]
d=[4. 4. 6. 8.]
(?,)
最后d的值为[4,4,6,8]
d.shape=(?,)
请注意,
tf.boolean_mask(
tensor,
mask,
name='boolean_mask',
axis=None
)
Args:
tensor: N-D tensor.
mask: K-D boolean tensor, K <= N and K must be known statically.
name: A name for this operation (optional).
axis: A 0-D int Tensor representing the axis in tensor to mask from. By default, axis is 0 which will mask from the first dimension. Otherwise K + axis <= N.
Returns:
(N-K+1)-dimensional tensor populated by entries in tensor corresponding to True values in mask.