concatenate的使用
tf.keras.layers.Concatenate(axis=-1, **kwargs)
- Layer that concatenates a list of inputs.
在一层中将输入进行拼接 - It takes as input a list of tensors, all of the same shape except for the concatenation axis, and returns a single tensor that is the concatenation of all inputs.
将输入的tensors按照拼接的维度进行拼接,拼接的时候除了待拼接的维度尺寸可以不一样,其他的要保持一致。
解释一下axis的具体含义。
axis表示从第几个维度去拼接。
axis =0; 表示从第一个维度去拼接。
axis =1; 表示从第二个维度去拼接。
axis =2; 表示从第三个维度去拼接。
具体解释见代码如下:
>>> x = np.arange(20).reshape(2, 2, 5)
>>> print(x)
[[[ 0 1 2 3 4]
[ 5 6 7 8 9]]
[[10 11 12 13 14]
[15 16 17 18 19]]]
>>> y = np.arange(20, 40).reshape(2, 2, 5)
>>> print(y)
[[[20 21 22 23 24]
[25 26 27 28 29]]
[[30 31 32 33 34]
[35 36 37 38 39]]]
# 从第一个维度开始拼接
>>> tf.keras.layers.Concatenate(axis=0)([x, y])
<tf.Tensor: shape=(4, 2, 5), dtype=int32, numpy=
array([[[ 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]]])>
#从输出结果可以看出,沿着最外层的维度依次向后拼接的,所以要求两个数组第二维和第三维的shape要一致。
# 从第二个维度拼接
>>> tf.keras.layers.Concatenate(axis=1)([x, y])
<tf.Tensor: shape=(2, 4, 5), dtype=int32, numpy=
array([[[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[20, 21, 22, 23, 24],
[25, 26, 27, 28, 29]],
[[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[30, 31, 32, 33, 34],
[35, 36, 37, 38, 39]]])>
#从输出结果中可以看出,是沿着第二维度开始拼接的(简单点可看是第几层括号,这就是第二层括号开始),
# 第一个数组里第一个二层括号结束后,紧跟着第二个的数组的二层括号。
# 从第三个维度拼接
>>> tf.keras.layers.Concatenate(axis=2)([x, y])
<tf.Tensor: shape=(2, 2, 10), dtype=int32, numpy=
array([[[ 0, 1, 2, 3, 4, 20, 21, 22, 23, 24],
[ 5, 6, 7, 8, 9, 25, 26, 27, 28, 29]],
[[10, 11, 12, 13, 14, 30, 31, 32, 33, 34],
[15, 16, 17, 18, 19, 35, 36, 37, 38, 39]]])>
# 这就是从最内层开始拼接,很容易就能看明白