数组拼接tf.concat()和np.concatenate()的区别

数组拼接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) 

猜你喜欢

转载自blog.csdn.net/kewendouhe/article/details/81569411