tf.gather()函数
tf.gather()
该接口的作用:就是抽取出params的第axis维度上在indices里面所有的index
tf.gather(
params,
indices,
validate_indices=None,
name=None,
axis=0
)
'''
Args:
params: A Tensor. The tensor from which to gather values. Must be at least rank axis + 1.
indices: A Tensor. Must be one of the following types: int32, int64. Index tensor. Must be in range [0, params.shape[axis]).
axis: A Tensor. Must be one of the following types: int32, int64. The axis in params to gather indices from. Defaults to the first dimension. Supports negative indexes.
name: A name for the operation (optional).
Returns:
A Tensor. Has the same type as params.
'''
参数说明:
params: A Tensor.
indices: A Tensor. types必须是: int32, int64. 里面的每一个元素大小必须在 [0, params.shape[axis])范围内.
axis: 维度。沿着params的哪一个维度进行抽取indices
返回的是一个tensor
示例
1.当axis参数省略时,即axis默认为axis=0
temp=np.arange(7)*7*2+tf.constant(1,shape=[7])
print(temp) #temp是一个tf张量,直接打印只显示形状和类型,需要创建会话机制
temp1=tf.gather(temp,[0,2,4]) #取temp一维张量中第0,第2,第4的值形成一个tf张量
with tf.Session() as sess:
print(sess.run(temp))
print(sess.run(temp1))
结果:
Tensor("add:0", shape=(7,), dtype=int32)
[ 1 15 29 43 57 71 85]
[ 1 29 57]
2.当temp为多维时,这里是4维张量,indices=[0,2],axis=0
input =[ [[[1, 1, 1], [2, 2, 2]],
[[3, 3, 3], [4, 4, 4]],
[[5, 5, 5], [6, 6, 6]]],
[[[7, 7, 7], [8, 8, 8]],
[[9, 9, 9], [10, 10, 10]],
[[11, 11, 11], [12, 12, 12]]],
[[[13, 13, 13], [14, 14, 14]],
[[15, 15, 15], [16, 16, 16]],
[[17, 17, 17], [18, 18, 18]]]
]
print(tf.shape(input))
with tf.Session() as sess:
output=tf.gather(input, [0,2],axis=0)#其实默认axis=0
print(sess.run(output))
结果:
Tensor("Shape:0", shape=(4,), dtype=int32)
[[[[ 1 1 1]
[ 2 2 2]]
[[ 3 3 3]
[ 4 4 4]]
[[ 5 5 5]
[ 6 6 6]]]
[[[13 13 13]
[14 14 14]]
[[15 15 15]
[16 16 16]]
[[17 17 17]
[18 18 18]]]]
解释:
第一个[ 是列表语法需要的括号,剩下的最里面的三个[[[是axis=0需要搜寻的中括号。这里一共有3个[[[。
indices的[0,2]即取第0个[[[和第2个[[[,也就是第0个和第2个三维立体。
3.当indices=[0,2],axis=1
input =[ [[[1, 1, 1], [2, 2, 2]],
[[3, 3, 3], [4, 4, 4]],
[[5, 5, 5], [6, 6, 6]]],
[[[7, 7, 7], [8, 8, 8]],
[[9, 9, 9], [10, 10, 10]],
[[11, 11, 11], [12, 12, 12]]],
[[[13, 13, 13], [14, 14, 14]],
[[15, 15, 15], [16, 16, 16]],
[[17, 17, 17], [18, 18, 18]]]
]
print(tf.shape(input))
with tf.Session() as sess:
output=tf.gather(input, [0,2],axis=1)#默认axis=0
print(sess.run(output))
结果:
Tensor("Shape:0", shape=(4,), dtype=int32)
[[[[ 1 1 1]
[ 2 2 2]]
[[ 5 5 5]
[ 6 6 6]]]
[[[ 7 7 7]
[ 8 8 8]]
[[11 11 11]
[12 12 12]]]
[[[13 13 13]
[14 14 14]]
[[17 17 17]
[18 18 18]]]]
解释:
第一个[ 是列表语法需要的括号,先把这个干扰去掉,剩下的每个[[[中所有内侧的 [[ 是axis=1搜索的中括号。
然后[0,2]即再取每个[[[体内的第0个[[和第2个[[,也就是去每个三维体的第0个面和第2个面