简体   繁体   中英

Tensorflow 2.0 Tensor Manipulation

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM