TensorFlow:替代 tf.stack() 操作

TensorFlow: Alternative to tf.stack() operation

TensorFlow支持栈操作如下: “将 R 阶张量列表堆叠成一个 R+1 阶张量”。

我的问题是,我们可以使用其他操作(如 tf.concat 或 tf.expand_dims)或任何其他操作来模拟 tf.stack 的行为吗?我的意图是跳过使用 tf.stack

您可以使用 tf.concat 操作和 tf.expand_dims 来实现此操作,下面是一个示例。

使用堆栈:

t1 = tf.constant([1,2,3])
t2 = tf.constant([4,5,6]) 

tf.stack((t1,t2),axis=0)

结果:

<tf.Tensor: shape=(2, 3), dtype=int32, numpy=
array([[1, 2, 3],
       [4, 5, 6]], dtype=int32)> 

使用连接:

tf.concat((tf.expand_dims(t1,0),tf.expand_dims(t2,0)),axis=0)

结果:

<tf.Tensor: shape=(2, 3), dtype=int32, numpy=
array([[1, 2, 3],
       [4, 5, 6]], dtype=int32)>