tensorflow中的concatenate的使用

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]]])>   
# 这就是从最内层开始拼接,很容易就能看明白    

  • 3
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值