7 、合併與分割

一、concat,拼接 

 例:統計班級的學生的分數ui

  a = [class1-4,student,scores],4個班級,35個學生,8門課的分數spa

  b = [class5-6,student,scores],2個班級,35個學生,8門課的分數code

 cancat要求除了指定合併的維度以外,其他的維度要大小要相同blog

1 a = tf.ones([4,35,8]) 2 b = tf.ones([2,35,8]) 3 c = tf.concat([a,b],axis = 0)  #參數要用[]括起來,並且要指定維度,TypeError: concat() missing 1 required positional argument: 'axis'
4 print(c.shape)  #(6, 35, 8)
5 
6 a = tf.ones([4,35,8]) 7 b = tf.ones([4,3,8]) #除了指定的維度,其他的維度要相同
8 c = tf.concat([a,b],axis = 1) 9 print(c.shape) #(4, 38, 8)

二、stack,建立一個新維度,須要合併建立一個新維度的全部張量的維度同樣

 1 #建立新的維度須要全部維度的大小是同樣的
 2 a = tf.ones([4,35,8])
 3 b = tf.ones([4,35,8])
 4 
 5 c1 = tf.concat([a,b],axis=-1)
 6 print(c1.shape) #(4, 35, 16)
 7 
 8 c2 = tf.stack([a,b],axis=0) # 在第一個維度以前建立新的維度
 9 print(c2.shape) #(2, 4, 35, 8)
10 
11 c3 = tf.stack([a,b],axis=3)  #在最後一個維度以後建立新的維度
12 print(c3.shape) #(4, 35, 8, 2)

三、unstack 對一個張量進行切割,按指定的維度分紅等數量的個數,如[4,35,8]指定在第一維度上進行切割,那麼會切割成4個[35,8]的張量

1 #三、unstack分割數據
2 a = tf.ones([4,35,8]) 3 b = tf.ones([4,35,8]) 4 
5 c = tf.stack([a,b],axis=0) 6 print(c.shape) #(2, 4, 35, 8)
7 
8 aa,bb = tf.unstack(c,axis=0) 9 print(aa.shape,bb.shape) #分割成兩個同樣的(4, 35, 8)

四、split ,在對一個張量進行切割以後,能夠指定要分割以後的數量 it

 1 #四、split
 2 a = tf.ones([4,35,8])  3 b = tf.ones([4,35,8])  4 
 5 c = tf.stack([a,b],axis=0)  6 print(c.shape)  7 
 8 res = tf.unstack(c,axis=3) #生成8個[4,35]張量的list
 9 print(len(res)) # 8
10 
11 res = tf.split(c,axis=3,num_or_size_splits=2) #num_or_size_split指定要分割的份數,也能夠指定每一份張量數,用列表裝着
12 print(len(res)) # 2 生成兩個(2, 4, 35, 4)
13 print(res[0].shape) # (2, 4, 35, 4)
14 
15 res = tf.split(c,axis=3,num_or_size_splits=[1,2,3,2]) #指定劃分後的張量的個數,並對劃分後每一個張量的維度大小進行指定
16 print(res[0].shape) #(2, 4, 35, 1)
17 print(res[1].shape) #(2, 4, 35, 2)
18 print(res[2].shape) #(2, 4, 35, 3)
19 print(res[3].shape) #(2, 4, 35, 2)
相關文章
相關標籤/搜索