Home > Software design >  Tensorflow 2.0 Tensor Manipulation
Tensorflow 2.0 Tensor Manipulation

Time:02-14

wanted to reshape and combine two tensor in the tensorflow :

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

a.shape = (2, 3)

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

b.shape = (2, 3)

c = combine(a, b)

result of c should be :

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

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

I need to convert a and b into c?

PS : Needed some tensor manipulation function in use like tf.concat, tf.reshape, looping is too slow to handle huge data. Numpy is also an option.

CodePudding user response:

You can try tf.stack and tf.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)

Or tf.stack and tf.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)
  • Related