📅  最后修改于: 2023-12-03 15:04:10.837000             🧑  作者: Mango
在 TensorFlow 中,tf.concat()
函数用于在给定维度上连接两个或多个张量。连接过程通过指定轴进行。函数的语法如下:
tf.concat(values, axis, name='concat')
假设我们要连接两个形状相同的张量,如下所示:
import tensorflow as tf
import numpy as np
A = tf.constant([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
B = tf.constant([[-1, -2, -3], [-4, -5, -6], [-7, -8, -9]])
C = tf.concat([A, B], axis=0)
with tf.Session() as sess:
print(sess.run(C))
输出:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[-1 -2 -3]
[-4 -5 -6]
[-7 -8 -9]]
在上面的例子中,我们使用tf.constant()
函数创建两个形状相同的张量(A 和 B),然后通过将它们沿着维度0连接起来,形成一个新的张量 C。
多维张量的连接与二维张量的连接类似,但是需要特别注意轴的指定。例如,假设我们有一个形状为 (2, 2, 2)
的张量 A 和一个形状为 (2, 2, 2)
的张量 B,如下所示:
import tensorflow as tf
import numpy as np
A = tf.constant([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
B = tf.constant([[[-1, -2], [-3, -4]], [[-5, -6], [-7, -8]]])
C = tf.concat([A, B], axis=2)
with tf.Session() as sess:
print(sess.run(C))
输出:
[[[ 1 2 -1 -2]
[ 3 4 -3 -4]]
[[ 5 6 -5 -6]
[ 7 8 -7 -8]]]
在上面的例子中,我们通过将张量 A 和 B 沿着第三个维度连接起来生成一个新的张量 C。
以上就是 Python – tensorflow.concat()
函数的介绍和例子。该函数可以用于在 TensorFlow 中连接两个或多个张量,并通过指定轴进行连接。使用此函数时,需要特别注意指定维度。