如何在Tensorflow中保持堆叠张量

问题描述 投票:0回答:1

目标是添加两个具有相同形状的张量

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的不同组合。这怎么可能?

arrays tensorflow stack append shapes
1个回答
0
投票

第一个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)
© www.soinside.com 2019 - 2024. All rights reserved.