前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >tf.concat

tf.concat

作者头像
狼啸风云
发布2022-10-28 15:19:32
6490
发布2022-10-28 15:19:32
举报
文章被收录于专栏:计算机视觉理论及其实现
代码语言:javascript
复制
tf.concat(
    values,
    axis,
    name='concat'
)

沿一维串联张量。沿着维度axis连接张量列表values。如果value[i].shape = [D0,D1, ...Daxis(i),...Dn],连接结果的形状为:

代码语言:javascript
复制
[D0, D1, ... Raxis, ...Dn]

其中

代码语言:javascript
复制
Raxis = sum(Daxis(i))

也就是说,来自输入张量的数据是沿着轴维连接的。输入张量的维数必须匹配,除轴外的所有维数必须相等。

例:

代码语言:javascript
复制
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)维

例:

代码语言:javascript
复制
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]
------------------

注意:如果沿着新轴进行连接,请考虑使用堆栈,如:

代码语言:javascript
复制
tf.concat([tf.expand_dims(t, axis) for t in tensors], axis)

也可以写为:

代码语言:javascript
复制
tf.stack(tensors, axis=axis)

参数:

  • values:  张量对象列表或单个张量
  • axis:  0-D int32张量。要连接的维度。必须在[-rank(values), rank(values)]范围内。与Python中一样,axis的索引也是基于0的。在[0,rank(values)]范围内的正轴为第轴维数。负轴表示第axis + rank(values)维
  • name:  操作的名称(可选)

返回值:

  • 由输入张量串联而成的张量
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-10-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档