目标是添加两个具有相同形状的张量
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)
这将返回
tf.Tensor(
[[1 4]
[2 5]
[3 6]], shape=(3, 2), dtype=int32)