TensorFlow 中张量连接操作 tf.concat 的基本用法及实例代码

本文详细介绍TensorFlow中concat函数的使用方法,包括环境配置、官方说明、参数解释及实例演示,帮助读者理解如何沿指定轴连接张量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、环境

TensorFlow API r1.12

CUDA 9.2 V9.2.148

cudnn64_7.dll

Python 3.6.3

Windows 10

 

二、官方说明

按指定轴(axis)进行张量连接操作(Concatenates Tensors)

https://www.tensorflow.org/api_docs/python/tf/concat

tf.concat(
    values,
    axis,
    name='concat'
)

输入:

(1)values:多个张量组成的列表或者单个张量

(2)axis:0维整形张量(整数),指定数据轴进行张量连接操作,其范围是[-输入张量的阶,+输入张量的阶]。[0,输入张量的阶]范围内的正数表示按照指定的axis轴进行连接操作,在[-输入张量的阶,0]之间的负数表示按照指定的(axis + 输入张量的阶)的轴进行连接操作

(3)name:可选参数,定义该张量连接操作的名称

输出:

输入张量按照指定轴连接后的一个结果张量

 

三、实例

(1)单个张量作为输入

>>> t1 = [[1,2,3],[4,5,6]]
>>> con1 = tf.concat(t1,0)
>>> shape1 = tf.shape(con1)
>>> with tf.Session() as sess:
...     print(sess.run(con1))
...     print(sess.run(shape1))
... 
[1 2 3 4 5 6]
[6]

(2)多个张量组成的列表作为输入

按照 0 轴(行)进行连接:

>>> t1 = [[1,2,3],[4,5,6]]
>>> t2 = [[7,8,9],[10,11,12]]
>>> con2 = tf.concat([t1,t2],0)
>>> shape2 = tf.shape(con2)
>>> with tf.Session() as sess:
...     print(sess.run(con2))
...     print(sess.run(shape2))
... 
[[ 1  2  3]
 [ 4  5  6]
 [ 7  8  9]
 [10 11 12]]
[4 3]

按照 1 轴(列)进行连接:

>>> t1 = [[1,2,3],[4,5,6]]
>>> t2 = [[7,8,9],[10,11,12]]
>>> con3 = tf.concat([t1,t2],1)
>>> shape3 = tf.shape(con3)
>>> with tf.Session() as sess:
...     print(sess.run(con3))
...     print(sess.run(shape3))
... 
[[ 1  2  3  7  8  9]
 [ 4  5  6 10 11 12]]
[2 6]
>>> 

按照 -1 轴(列)进行连接:

>>> t1 = [[1,2,3],[4,5,6]]
>>> t2 = [[7,8,9],[10,11,12]]
>>> con4 = tf.concat([t1,t2],-1)
>>> shape4 = tf.shape(con4)
>>> with tf.Session() as sess:
...     print(sess.run(con4))
...     print(sess.run(shape4))
... 
[[ 1  2  3  7  8  9]
 [ 4  5  6 10 11 12]]
[2 6]

 

注意:如果想沿着一个新轴连接张量,则考虑使用 tf.stack()

不建议使用:tf.concat([tf.expand_dims(t, axis) for t in tensors],axis)

推荐使用:tf.stack(tensors, axis=axis)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

csdn-WJW

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值