tf.concat, np.concatenate

tf.concat(concat_dim, values, name='concat'),   连接两个矩阵的操作


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

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

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

t1 = [[1, 2, 3], [4, 5, 6]]
t2 = [[7, 8, 9], [10, 11, 12]]
tf.concat(0, [t1, t2]) == > [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

如果concat_dim是1,那么在某一个shape的第二个维度上连

t1 = [[1, 2, 3], [4, 5, 6]]
t2 = [[7, 8, 9], [10, 11, 12]]
tf.concat(1, [t1, t2]) ==> [[1, 2, 3, 7, 8, 9], [4, 5, 6, 10, 11, 12

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

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

# tensor t3 with shape [2, 3]
# tensor t4 with shape [2, 3]
tf.shape(tf.concat(0, [t3, t4])) ==> [4, 3]
tf.shape(tf.concat(1, [t3, t4])) ==> [2, 6]

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

这里要注意的是:如果是两个向量,它们是无法调用  tf.concat(1, [t1, t2])  来连接的,因为它们对应的shape只有一个维度,当然不能在第二维上连了,虽然实际中两个向量可以在行上连,但是放在程序里是会报错的
如果要连,必须要调用tf.expand_dims来扩维:


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


--------------------- 
作者:xf__mao 
来源:CSDN 
原文:https://blog.csdn.net/mao_xiao_feng/article/details/53366163 
版权声明:本文为博主原创文章,转载请附上博文链接!

数组拼接tf.concat()和np.concatenate()的区别
Tensorflow新手,在程序里要将两个数组进行拼接,使用了tf.concat()函数,然而运行过程中出现了如下错误:

TypeError: Tensors in list passed to ‘values’ of ‘ConcatV2’ Op have types [float64, < NOT CONVERTIBLE TO TENSOR>] that don’t all match.

具体代码如下:

All_Patches1 = scipy.io.loadmat(path + '/data/All_Patches1.mat')['All_Patches1']
All_Patches2 = scipy.io.loadmat(path + '/data/All_Patches2.mat')['All_Patches2']
All_Labels = scipy.io.loadmat(path + '/data/All_Labels.mat')['All_Labels']

All_Patches = tf.concat([All_Patches1,All_Patches2],axis = 0)


在查了一系列相关类似错误后始终没有把自己bug解决,只得向师兄寻求援助,师兄只瞅了一眼就发现了我几个小时咩有解决的问题,原来症结就在对tensorflow计算图上理解不够。 
tensorflow所有的计算都是计算图上的一个节点,定义好的运算是通过会话(session)来执行的,使用tf.concat()函数后也需要在session中执行,但是我只是对两个常量数组进行拼接,此时正确的函数应该是np.concatenate(),它可以直接使用,即如下代码:

All_Patches = np.concatenate((All_Patches1,All_Patches2),axis = 0)

这个问题过后稍稍了解了为什么tensorflow和numpy中均定义了类似功能的函数。正确使用tf.concat()函数的一个示范如下:

x_labeled = tf.placeholder(tf.float32, [batch_size_labeled, patch_size, patch_size, num_band])
x_unlabeled = tf.placeholder(tf.float32, [batch_size_unlabeled, patch_size, patch_size, num_band])
x_input = tf.concat([x_labeled, x_unlabeled], axis=0) 
--------------------- 
作者:kewendouhe 
来源:CSDN 
原文:https://blog.csdn.net/kewendouhe/article/details/81569411 
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/infinita_LV/article/details/86139068