tf.concat的用法

tf.concat是连接两个矩阵的操作

tf.concat(concat_dim, values, name='concat')

除去name参数用以指定该操作的name,与方法有关的一共两个参数:

第一个参数concat_dim:必须是一个数,表明在哪一维上连接

     如果concat_dim是0,那么在某一个shape的第一个维度上连,对应到实际,就是叠放到列上

[python]  view plain  copy
  1. t1 = [[123], [456]]  
  2. t2 = [[789], [101112]]  
  3. tf.concat(0, [t1, t2]) == > [[123], [456], [789], [101112]]  
             如果 concat_dim是1,那么在某一个shape的第二个维度上连

[python]  view plain  copy
  1. t1 = [[123], [456]]  
  2. t2 = [[789], [101112]]  
  3. tf.concat(1, [t1, t2]) ==> [[123789], [456101112  

             如果有更高维,最后连接的依然是指定那个维:

             values[i].shape = [D0, D1, ... Dconcat_dim(i), ...Dn]连接后就是:[D0, D1, ... Rconcat_dim, ...Dn]

[python]  view plain  copy
  1. # tensor t3 with shape [2, 3]  
  2. # tensor t4 with shape [2, 3]  
  3. tf.shape(tf.concat(0, [t3, t4])) ==> [43]  
  4. tf.shape(tf.concat(1, [t3, t4])) ==> [26]  

第二个参数values:就是两个或者一组待连接的tensor了


/×××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××/

这里要注意的是:如果是两个向量,它们是无法调用

[python]  view plain  copy
  1. tf.concat(1, [t1, t2])  
来连接的,因为它们对应的shape只有一个维度,当然不能在第二维上连了,虽然实际中两个向量可以在行上连,但是放在程序里是会报错的

如果要连,必须要调用tf.expand_dims来扩维:

[python]  view plain  copy
  1. t1=tf.constant([1,2,3])  
  2. t2=tf.constant([4,5,6])  
  3. #concated = tf.concat(1, [t1,t2])这样会报错  
  4. t1=tf.expand_dims(tf.constant([1,2,3]),1)  
  5. t2=tf.expand_dims(tf.constant([4,5,6]),1)  
  6. concated = tf.concat(1, [t1,t2])#这样就是正确的  

猜你喜欢

转载自blog.csdn.net/u014182497/article/details/80619146
今日推荐