天天看點

TensorFlow2-基礎(四):Tensor的索引、切片一、按照順序采樣二、任意采樣

一、按照順序采樣

1、Basic indexing: [idx][idx][idx]

隻能取一個元素

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

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
           

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

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

4、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])

5、::-1 可以實作倒序的功能

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

6、索引方式-案例

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]
           

二、任意采樣

1、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]
           

2、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]
           

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.]])
           

參考資料:

TensorFlow學習筆記3(Tensor的索引與切片)

TensorFlow索引與切片的實作方法

TensorFlow基礎(6.索引和切片)

TensorFlow——索引與切片操作

繼續閱讀