神经网络学习-tensorflow2.0-tesor的索引与切片

1.直接通过维度编号进行索引

example:

input:

a=tf.random.uniform([2,2,6,3],minval=0,maxval=20,dtype=tf.int32)
print(a,"\n",a[0][0])
这里a[0][0]也可以写作a[0,0]

output:

tf.Tensor(
[[[[ 1 17 1]
[ 6 9 15]
[18 19 19]
[19 19 4]
[14 2 5]
[15 15 17]]

[[ 5 19 10]
[14 3 5]
[ 7 17 14]
[17 18 14]
[18 15 14]
[ 7 1 15]]]


[[[17 12 0]
[15 14 16]
[ 7 10 16]
[ 4 8 13]
[ 7 3 13]
[19 16 8]]

[[11 6 4]
[11 12 14]
[14 18 0]
[18 13 2]
[19 8 2]
[15 5 17]]]], shape=(2, 2, 6, 3), dtype=int32)
tf.Tensor(
[[ 1 17 1]
[ 6 9 15]
[18 19 19]
[19 19 4]
[14 2 5]
[15 15 17]], shape=(6, 3), dtype=int32)

 

a=range(10)(即a=[0,1,2,3,4,5,6,7,8,9])

a[-1:]=[9]

a[:2]=[0,1]

a[:-1]=[0,1,2,3,4,5,6,7,8]

 

2.tersor.shape:可以用来访问tensor的shape

example:

input: 

a=tf.random.normal([4,28,28,3])

print(a[1,2].shape)

output:  (28, 3)

(*注意*)a[0, : , : , :]=(28,28,3)

a[ : , : , : ,0]=(4,28,28)

a[ : , : ,0, : ]=(4,28,3)

 

3.使用双冒号取出tensor的一部分 start:end:step

(省略start则默认从头开始,省略end则默认取到末尾)

example:

input:

a=tf.random.normal([4,28,28,3])
print(a[1,4:13:2].shape,'\n',a[1,::2].shape,'\n',a[1,5::2].shape)

output:

(5, 28, 3)
(14, 28, 3)
(12, 28, 3)

(*注意*)当step取值为负数时,则会逆着原tensor的数据进行采集

 

4.省略号的用法:省略号可以代表任意长度的连续冒号,连续输入三个 . 即为使用省略号。

example:

a=tf.random.normal([2,4,28,28,3])
a[0,...,1]=[4,28,28]

 

5.tf.gather(tensor,axis=a,indices=[the lines chose]):从tensor中的第a个维度(a从零算起)抽取选中的列,并按照所写顺序进行排列。

6.tf.gather_nd(tensor,position):直接通过索引访问所需要的元素,并组成新的tensor

example:

input:

a=tf.random.uniform([3,5,3],minval=0,maxval=20,dtype=tf.int64)
b=tf.gather_nd(a,[[1,0,2],[0,1,1]])
print(a,'\n',b)

output:

tf.Tensor(
[[[12 4 12]
[ 6 5 0]
[ 3 19 7]
[10 16 5]
[15 12 5]]

[[15 4 17]
[ 7 13 0]
[15 2 11]
[14 9 16]
[ 7 16 19]]

[[13 8 6]
[15 12 17]
[16 19 11]
[ 5 13 12]
[ 0 11 7]]], shape=(3, 5, 3), dtype=int64)
tf.Tensor([17 5], shape=(2,), dtype=int64)

 

 

7.tf.boolean_mask(tensor,[bool expression],axis=a):对tensor的第a个维度进行选择,布尔表达式中True的保留,False的剔除

example:

input:

 

a=tf.random.uniform([3,5,3],minval=0,maxval=20,dtype=tf.int64)
b=tf.boolean_mask(a,[True,False,False],axis=0)
print(a,'\n',b)

 

output:

tf.Tensor(
[[[12 7 19]
[ 7 12 9]
[ 5 5 13]
[16 11 12]
[12 8 6]]

[[11 17 0]
[12 8 6]
[ 7 0 16]
[ 2 9 9]
[16 10 18]]

[[16 15 15]
[ 8 0 16]
[ 4 16 14]
[10 16 2]
[ 3 18 13]]], shape=(3, 5, 3), dtype=int64)
tf.Tensor(
[[[12 7 19]
[ 7 12 9]
[ 5 5 13]
[16 11 12]
[12 8 6]]], shape=(1, 5, 3), dtype=int64)

 

posted @ 2020-10-05 12:09  ladadee  阅读(291)  评论(0)    收藏  举报