Tensorflow 2.0 张量操作

Tensorflow 2.0 Tensor Manipulation

想要在张量流中重塑和组合两个张量:

a = [[1, 3, 5],
     [7, 9, 11]]

a.shape = (2, 3)

b = [[2, 2, 6],
     [8, 10, 12]]

b.shape = (2, 3)

c = 合并(a, b)

c 的结果应该是:

c = [[[[1, 2], [3, 2], [5, 6]],
[[7, 8], [9, 10], [11, 12]]]]

c.shape = (1, 2, 3, 2)

我需要将a和b转换成c?

PS : 需要一些像 tf.concat, tf.reshape 这样的张量操作函数,循环太慢无法处理大量数据。 Numpy 也是一种选择。

您可以尝试 tf.stacktf.expand_dims:

import tensorflow as tf

a = tf.constant([[1, 3, 5],
                [7, 9, 11]])

b = tf.constant([[2, 2, 6],
                  [8, 10, 12]])

c = tf.expand_dims(tf.stack([a, b], axis=-1), axis=0)
tf.Tensor(
[[[[ 1  2]
   [ 3  2]
   [ 5  6]]

  [[ 7  8]
   [ 9 10]
   [11 12]]]], shape=(1, 2, 3, 2), dtype=int32)

tf.stacktf.newaxis

c = tf.stack([a, b], axis=-1)[tf.newaxis,...]
tf.Tensor(
[[[[ 1  2]
   [ 3  2]
   [ 5  6]]

  [[ 7  8]
   [ 9 10]
   [11 12]]]], shape=(1, 2, 3, 2), dtype=int32)