Tensorflow-tf.concat() 显示了不同的结果


with tf.Session() as sess:
t1 = [
[[0],[1],[2]],
[[3],[4],[5]],
]
print(sess.run(tf.shape(t1)))
print(sess.run(tf.concat(t1,1)))
print("**********")
t2 = np.arange(6).reshape([2,3,1])
print(sess.run(tf.shape(t2)))
print(sess.run(tf.concat(t2,1)))

然后它显示

[2 3 1]
[[0 3] [1 4] [2 5]]
[2 3 1]
[[[0] [1] [2]] [[3] [4] [5]]]

T1和T2具有相同的形状和值,为什么结果不同?

因为t1list,而t2不是。

tf.concat连接一个张量列表。因此,t1被视为 2 个大小为3x1的张量的列表。另一方面,t2是一个被转换为单个2x3x1Tensor的numpy数组,没有其他东西可以连接这个张量。

我认为可能让您感到惊讶的是,根据上下文的不同,t1的解释不同。tf.shape期望Tensor作为参数,而不是张量列表,因此当传递给此函数时,t1被解释为2x3x1张量。

来自 tf.concat(( 上的文档页面:

tf.concat(
values,
axis,
name='concat')
...
Concatenates !!the list!! of tensors values along dimension axis,
...
the data from the input tensors is joined along the axis dimension.

tf.concat()将张量列表作为输入。 t1 是一个列表。tf.shape(t1)将其转换为单个张量并返回其形状。tf.concat(t1,1)将 t1 视为列表 2 个对象:[[0],[1],[2]][[3],[4],[5]]。它将 t1 转换为包含 2 个形状为 (3,1( 的张量的列表,将它们连接起来并返回形状为 (3,2( 的张量。 若要验证这一点,可以运行以下示例:

with tf.Session() as sess:
t1 = [
[[0],[1],[2]],
[[3],[4],[5]],
]
t100 = [[0],[1],[2]]
t101 = [[3],[4],[5]]
print(sess.run(tf.concat(t1,1)))
# construct a list from t100 and t101
print(sess.run(tf.concat([t100, t101],1)))

两者都将返回相同的结果。 另一方面,t2 是一个 numpy 数组,tf.concat(t2,1(,将 t2 视为包含单个 numpy 数组的列表,因此不会发生串联,它基本上返回 t2。

最新更新