tensorflow 中用来拼接张量的函数tf.concat(),用法:
tf.concat([tensor1, tensor2,...], axis)
代码详解-维度变化理解:
# 参考:https://blog.csdn.net/leviopku/article/details/82380118
import tensorflow as tf
import numpy as np
sess = tf.Session()
sess.run(tf.initialize_all_variables())
# 理解:
# 举例:两个需要tf.concat的张量维度为:[2 3, 5], 则: axis取值范围为:[-3, 3)
# 当axis=0 或 -3时, 拼接第一个维度下的元素 ==》 生成矩阵维度:(4, 3, 5)
# 当axis=1 或 -2时, 拼接第一个维度下的元素 ==》 生成矩阵维度:(2, 6, 5)
# 当axis=2 或 -1时, 拼接第一个维度下的元素 ==》 生成矩阵维度:(2, 3, 10)
# origin data
con_data1 = np.arange(1, 31).reshape([2, 3, 5])
con_data2 = np.arange(31, 61).reshape([2, 3, 5])
print('con_data1: \n', con_data1)
print('con_data1.shape: \n', con_data1.shape)
print('con_data2: \n', con_data2)
print('con_data2.shape: \n', con_data2.shape)
# con_data1:
# [[[ 1 2 3 4 5]
# [ 6 7 8 9 10]
# [11 12 13 14 15]]
#
# [[16 17 18 19 20]
# [21 22 23 24 25]
# [26 27 28 29 30]]]
# con_data1.shape:
# (2, 3, 5)
# con_data2:
# [[[31 32 33 34 35]
# [36 37 38 39 40]
# [41 42 43 44 45]]
#
# [[46 47 48 49 50]
# [51 52 53 54 55]
# [56 57 58 59 60]]]
# con_data2.shape:
# (2, 3, 5)
print('+++++++++++++++++++++++++++++++++++++++++')
# axis = 0
con_0 = tf.concat([con_data1, con_data2], axis=0)
con_0 = sess.run(con_0)
print('con_0: \n', con_0)
print('con_0.shape: \n', con_0.shape)
# con_0:
# [[[ 1 2 3 4 5]
# [ 6 7 8 9 10]
# [11 12 13 14 15]]
#
# [[16 17 18 19 20]
# [21 22 23 24 25]
# [26 27 28 29 30]]
#
# [[31 32 33 34 35]
# [36 37 38 39 40]
# [41 42 43 44 45]]
#
# [[46 47 48 49 50]
# [51 52 53 54 55]
# [56 57 58 59 60]]]
# con_0.shape:
# (4, 3, 5)
print('+++++++++++++++++++++++++++++++++++++++++')
# axis = 1
con_1 = tf.concat([con_data1, con_data2], axis=1)
con_1 = sess.run(con_1)
print('con_1: \n', con_1)
print('con_1.shape: \n', con_1.shape)
# con_1:
# [[[ 1 2 3 4 5]
# [ 6 7 8 9 10]
# [11 12 13 14 15]
# [31 32 33 34 35]
# [36 37 38 39 40]
# [41 42 43 44 45]]
#
# [[16 17 18 19 20]
# [21 22 23 24 25]
# [26 27 28 29 30]
# [46 47 48 49 50]
# [51 52 53 54 55]
# [56 57 58 59 60]]]
# con_1.shape:
# (2, 6, 5)
print('+++++++++++++++++++++++++++++++++++++++++')
# axis = 2
con_2 = tf.concat([con_data1, con_data2], axis=2)
con_2 = sess.run(con_2)
print('con_2: \n', con_2)
print('con_2.shape: \n', con_2.shape)
# con_2:
# [[[ 1 2 3 4 5 31 32 33 34 35]
# [ 6 7 8 9 10 36 37 38 39 40]
# [11 12 13 14 15 41 42 43 44 45]]
#
# [[16 17 18 19 20 46 47 48 49 50]
# [21 22 23 24 25 51 52 53 54 55]
# [26 27 28 29 30 56 57 58 59 60]]]
# con_2.shape:
# (2, 3, 10)
print('+++++++++++++++++++++++++++++++++++++++++')
# axis = -1 相当于 2
con_1_ = tf.concat([con_data1, con_data2], axis=-1)
con_1_ = sess.run(con_1_)
print('con_1_: \n', con_1_)
print('con_1_.shape: \n', con_1_.shape)
# con_1_:
# [[[ 1 2 3 4 5 31 32 33 34 35]
# [ 6 7 8 9 10 36 37 38 39 40]
# [11 12 13 14 15 41 42 43 44 45]]
#
# [[16 17 18 19 20 46 47 48 49 50]
# [21 22 23 24 25 51 52 53 54 55]
# [26 27 28 29 30 56 57 58 59 60]]]
# con_1_.shape:
# (2, 3, 10)
print('+++++++++++++++++++++++++++++++++++++++++')