tf.where
记录一下where的用法:
官方文档
tf.where(input, name=None)`
Returns locations of true values in a boolean tensor.
This operation returns the coordinates of true elements in input. The coordinates are returned in a 2-D tensor where the first dimension (rows) represents the number of true elements, and the second dimension (columns) represents the coordinates of the true elements. Keep in mind, the shape of the output tensor can vary depending on how many true values there are in input. Indices are output in row-major order.
For example:
# 'input' tensor is [[True, False]
# [True, False]]
# 'input' has two true values, so output has two coordinates.
# 'input' has rank of 2, so coordinates have two indices.
where(input) ==> [[0, 0],
[1, 0]]
# `input` tensor is [[[True, False][True, False]]
# [[False, True][False, True]]
# [[False, False][False, True]]]
# 'input' has 5 true values, so output has 5 coordinates.
# 'input' has rank of 3, so coordinates have three indices.
where(input) ==> [[0, 0, 0], [0, 1, 0],
[1, 0, 1],[1, 1, 1],
[2, 1, 1]]
改了一下格式一下子就很好理解了 = =
where返回的是为true位置的下标
第一个例子,是一个2阶(这个阶可以这么理解,如果是n个1y的张量就是2阶,如果是n个2y的张量就是3阶,n个3*y的张量还是3阶,阶是指的块数,还不理解就看第二个例子,直观的看,最后有几个]]]这个括号就是几阶,方便定位的…也不知道对不对(捂脸)),所以[0,0]和[0,1]指的是[0,0]和[0,1]这两个位置上是true,
第二个例子因为有三阶(就是三个块),所以输出是三列。每一个块都是[[True, False][True, False]]是一个2x2的矩阵。因为一共有5个true所以有五行。
[0,0,0] 指的是第0块的[0,0]位置,[0,1,0]指的是第0块的 [1,0]位置,以此类推。这样就搞懂惹
完整用法
(转自 https://blog.youkuaiyun.com/weixin_34318326/article/details/92119620):
格式:
tf.where(condition, x=None, y=None, name=None)
参数:
condition: 一个元素为bool型的tensor。元素内容为false,或true。
x: 一个和condition有相同shape的tensor,如果x是一个高维的tensor,x的第一维size必须和condition一样。
y: 和x有一样shape的tensor
返回:
一个和x,y有同样shape的tensor
功能:
遍历condition Tensor中的元素,如果该元素为true,则output Tensor中对应位置的元素来自x Tensor中对应位置的元素;否则output Tensor中对应位置的元素来自Y tensor中对应位置的元素。
tf.gather_nd
gather_nd=gather n dimension tensor
tf.gather_nd(
params,
indices,
name=None
)
例子:
params = [['a', 'b'], ['c', 'd']]
indices = [[0, 0], [1, 1]]
output = ['a', 'd']
一看就懂系列。

本文详细解析了TensorFlow中tf.where函数的使用方法,包括其返回true值位置的坐标、不同阶张量的处理方式及具体示例。此外,还介绍了tf.where的完整用法,包括条件参数、x和y参数的使用,以及tf.gather_nd函数的用法。
4990

被折叠的 条评论
为什么被折叠?



