如何在 Tensorflow 中保持堆叠张量

How to keep stacking tensors in Tensorflow

目标是附加 2 个具有一个匹配形状的张量

import tensorflow as tf 
x = tf.constant([1, 4]) 
y = tf.constant([2, 5]) 
z = tf.constant([3, 6]) 
res = tf.stack([x, y],axis=0)
print(res)
->tf.Tensor(
  [[1 4]
  [2 5]], shape=(2, 2), dtype=int32)
print(z)
->tf.Tensor([3 6], shape=(2,), dtype=int32)
result = tf.stack((res, z),axis=1)
->tensorflow.python.framework.errors_impl.InvalidArgumentError: Shapes of all inputs must match: values[0].shape = [2,2] != values[1].shape = [2] [Op:Pack] name: stack

如我所料

print(result)
->->tf.Tensor(
  [[1 4]
  [2 5]
  [3,6]], shape=(2, 3), dtype=int32)

我尝试了 concat 和 stack 的不同组合。这怎么可能?

第一个 tf.stack 有效,因为所有输入张量 x, y, z 具有相同的形状 (2,)。第二个 tf.stack 将不起作用,因为我们正在处理不同形状的张量。

为了加入它们,您可以使用 tf.concat 但调整 Tensor 的形状:

# res is shape (2, 2)
z = tf.expand_dims(z, axis=0)     # Shape is now (1, 2) instead of (2,)
result = tf.concat((res, z), axis=0)     # Shape match except in axis 0

print(result)

这将 return

tf.Tensor(
[[1 4]
 [2 5]
 [3 6]], shape=(3, 2), dtype=int32)