Arrays 如何在Tensorflow中保持堆叠张量
目标是用一个匹配的形状附加2个张量Arrays 如何在Tensorflow中保持堆叠张量,arrays,tensorflow,stack,append,shapes,Arrays,Tensorflow,Stack,Append,Shapes,目标是用一个匹配的形状附加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]
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
,但要调整张量形状:
#res是形状(2,2)
z=tf.expand_dims(z,轴=0)#形状现在是(1,2)而不是(2,)
结果=tf.concat((res,z),轴=0)#形状匹配,轴0除外
打印(结果)
这会回来的
tf.Tensor(
[[1 4]
[2 5]
[3,6]],形状=(3,2),数据类型=int32)