介绍
返回condition(条件)是True 的元素坐标
语法
tf.where(
condition,
x=None,
y=None,
name=None
)
参数:
- condition:bool型的tf.Tensor
- x:如果x不提供或x为None,那么y也不能提供或y为None;如果x提供,y也必须提供
- y:类型与x相同,并且具有可通过condition和广播的形状x。
该函数有些复杂,具体意思见下面例子
例子:没提供x,y
tf.where将返回 condition是True,形状(n,d)的形式。(其中n是值为True的数量,d是值为True的索引)。
索引以行优先顺序输出。
tf.where([True, False, False, True])
执行结果:
<tf.Tensor: id=51, shape=(2, 1), dtype=int64, numpy=
array([[0],
[3]])>
2行1列,2行表示有2个值为True,列中的 0 和 3,表示值为True的索引
将上例复杂化
tf.where([[True, False, False, True],[False, False, True, True]])
执行结果:
<tf.Tensor: id=53, shape=(4, 2), dtype=int64, numpy=
array([[0, 0],
[0, 3],
[1, 2],
[1, 3]])>
返回结果是4行2列,4表示有4个值为True,列中的元素表示 值为True的索引
[0, 0]表示0行0列为True,[0, 3]表示0行3列为True,以此类推
0,1代替True,False
tf.where([[1, 0, 0, 1],[0, 0, 1, 1]])
执行结果:
<tf.Tensor: id=53, shape=(4, 2), dtype=int64, numpy=
array([[0, 0],
[0, 3],
[1, 2],
[1, 3]])>
例子:提供x,y
condition 相当于 mask(掩码),condition 中的True,从 x 取出对应的元素,condition 中的False,从 y 取出对应的元素
tf.where([True, False, False, True], [1,2,3,4], [100,200,300,400])
执行结果:
<tf.Tensor: id=60, shape=(4,), dtype=int32, numpy=array([ 1, 200, 300, 4], dtype=int32)>
