tf.concat(
values,
axis,
name='concat'
)
沿一维串联张量。沿着维度axis连接张量列表values。如果value[i].shape = [D0,D1, ...Daxis(i),...Dn],连接结果的形状为:
[D0, D1, ... Raxis, ...Dn]
其中
Raxis = sum(Daxis(i))
也就是说,来自输入张量的数据是沿着轴维连接的。输入张量的维数必须匹配,除轴外的所有维数必须相等。
例:
import tensorflow as tf
t1 = [[1, 2, 3], [4, 5, 6]]
t2 = [[7, 8, 9], [10, 11, 12]]
t3=tf.concat([t1, t2], 0) # [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
t4=tf.concat([t1, t2], 1) # [[1, 2, 3, 7, 8, 9], [4, 5, 6, 10, 11, 12]]
# tensor t3 with shape [2, 3]
# tensor t4 with shape [2, 3]
t3_shape = tf.shape(tf.concat([t1, t2], 0)) # [4, 3]
t4_shape = tf.shape(tf.concat([t1, t2], 1)) # [2, 6]
with tf.Session() as sess:
print(sess.run(t3))
print(sess.run(t4))
print(sess.run(t3_shape))
print(sess.run(t4_shape))
Output:
----------------------
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
[[ 1 2 3 7 8 9]
[ 4 5 6 10 11 12]]
[4 3]
[2 6]
----------------------
在Python中,axis也可以是负数。负的axis被解释为从秩的末尾开始计数,即,第axis + rank(values)维
。
例:
import tensorflow as tf
t1 = [[[1, 2], [2, 3]], [[4, 4], [5, 3]]]
t2 = [[[7, 4], [8, 4]], [[2, 10], [15, 11]]]
t3 = tf.concat([t1, t2], -1)
t3_shape = tf.shape(t3)
with tf.Session() as sess:
print(sess.run(t3))
print(sess.run(t3_shape))
Output:
-----------------
[[[ 1 2 7 4]
[ 2 3 8 4]]
[[ 4 4 2 10]
[ 5 3 15 11]]]
[2 2 4]
------------------
注意:如果沿着新轴进行连接,请考虑使用堆栈,如:
tf.concat([tf.expand_dims(t, axis) for t in tensors], axis)
也可以写为:
tf.stack(tensors, axis=axis)
参数:
values
: 张量对象列表或单个张量axis
: 0-D int32张量。要连接的维度。必须在[-rank(values), rank(values)]范围内。与Python中一样,axis的索引也是基于0的。在[0,rank(values)]范围内的正轴为第轴维数。负轴表示第axis + rank(values)维
返回值: