TensorFlow学习笔记3(Tensor的索引与切片)

按照顺序采样

一共有6种方式进行索引:

Basic indexing: [idx][idx][idx]

只能取一个元素

a = tf.ones([1,5,5,3])
a[0][0]
a[0][0][0]
a[0][0][0][2]

Same with Numpy: [idx, idx,...]

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

切片

start: end 表示从A到B取值,包含A不包含B. [A:B)

a = tf.range(10)
a[-1:]
a[-2:]
a[:2]
a[:-1]

start: end: step

a.shape     #TensorShape([4,28,28,3])
a[0:2, :, :, :].shape   #TensorShape([2,28,28,3])
a[:, 0:28:2, 0:28,2, :].shape  #TensorShape([4,14,14,3])
a[:,:14,:14,:]     #TensorShape([4,14,14,3])
a[:,14:,14:,:].shape     #TensorShape([4,14,14,3])
a[:,::2,::2,:].shape     #TensorShape([4,14,14,3])

::-1 可以实现倒序的功能

a = tf.range(4)     #[0,1,2,3]
a[::-1]             #[3,2,1,0]
a[::-2]             #[3,1]
a[2::-2]            #[2,0]

...

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

任意采样

tf.gather

data: [classes, students, subjects]
eg: [4, 35, 8]

tf.gather(a, axis=0, indices=[2,3]).shape    #[2,35,8]
a[2:4].shape    #[2,35,8]
tf.gather(a, axis=0, indices=[2,1,4,0]).shape      #[4,35,8]
tf.gather(a, axis=1, indices=[2,3,7,9,16]).shape   #[4,5,8]
tf.gather(a, axis=2, indices=[2,3,7]).shape        #[4,35,3]

tf.gather_nd

eg:采样某些学生的某些成绩,如何实现这个功能?可以通过串型两个tf.gather实现
eg:如何实现[class1_student1, class2_student2, class3_student3, class4_student4]? ---> [4,8]

a.shape    #[4,35,8]
tf.gather_nd(a, [0])  #[35,8]
tf.gather_nd(a, [0,1])  #[8]  取0号班级1号学生的成绩
tf.gather_nd(a, [0,1,2])  #[] 取0号班级1号学生第2科的成绩
tf.gather_nd(a, [[0,1,2]])  #[1]  返回一个成绩,为一个数组
a.shape   #[4,35,8]
tf.gather_nd(a, [[0,0],[1,1]]).shape  #[2,8]
tf.gather_nd(a, [[0,0],[1,1],[2,2]]).shape   #[3,8]
tf.gather_nd(a, [[0,0,0],[1,1,1],[2,2,2]]).shape  #[3]
tf.gather_nd(a, [[[0,0,0],[1,1,1],[2,2,2]]]).shape  #[1,3]

tf.boolean_mask

a.shape   #[4,28,28,3]
tf.boolean_mask(a, mask=[True, True, False, False]).shape   #[2, 28, 28, 3]
tf.boolean_mask(a, mask=[True, True, False], axis=3).shape  #[4, 28, 28, 2]

a=tf.ones([2,3,4])
tf.boolean_mask(a, mask=[[True, False, False],[False, True, True]])        # array([[1.,1.,1.,1.],[1.,1.,1.,1.],[1.,1.,1.,1.]])
posted @ 2021-06-02 20:20  stdforml  阅读(269)  评论(0编辑  收藏  举报