Home > Net >  How to convert a 3D tensor of dtype= complex64 to 3D tensor of dtype = float32 in tensorflow
How to convert a 3D tensor of dtype= complex64 to 3D tensor of dtype = float32 in tensorflow

Time:08-09

I have tensor of dimension (B,N,K) with complex values and I want to convert the tensor into dimension(B,N,2*K) in such a way that every real value is placed next to its complex value, something like this:

[[[ 2.51-0.49j  0.80-0.74j]
  [-0.01 0.34j -2.04 0.70j]
  [ 0.02-1.85j -0.38 1.66j]]

 [[ 0.54 0.49j  0.28 1.75j]
  [-1.52-1.72j  0.68 0.17j]
  [-0.89 0.32j -1.88 0.15j]]] (2, 3, 2)

This complex tensor gets converted to:

[[[ 2.51  -0.49  0.80  -0.74]
  [-0.01  0.34   -2.04  0.70]
  [ 0.02 -1.85   -0.38  1.66]]

 [[ 0.54  0.49   0.28  1.75]
  [-1.52  1.72   0.68  0.17]
  [-0.89  0.32  -1.88  0.15]]] (2, 3, 4)

I have reduced the number of decimal places for readability.

CodePudding user response:

Something like this should work fine:

inp = tf.convert_to_tensor([[[ 2.51-0.49j , 0.80-0.74j],
                   [-0.01 0.34j, -2.04 0.70j],
                   [ 0.02-1.85j, -0.38 1.66j]],

                  [[ 0.54 0.49j,  0.28 1.75j],
                   [-1.52-1.72j,  0.68 0.17j],
                   [-0.89 0.32j, -1.88 0.15j]]])
initial_shape = tf.shape(inp)

# convert to 1 number per "last dimension"
tmp = tf.reshape(inp, (initial_shape[0], -1, 1)) 

# get real part
real = tf.math.real(tmp) 
# get imaginary part
imag = tf.math.imag(tmp) 
# concatenate real with its corresponding imaginary 
to_reshape = tf.concat((real, imag), axis=-1) 

# reshape to initial shape, with the last *2
tf.reshape(to_reshape, (initial_shape[0], initial_shape[1], initial_shape[2]*2)) 

Output:

<tf.Tensor: shape=(2, 3, 4), dtype=float64, numpy=
array([[[ 2.51, -0.49,  0.8 , -0.74],
        [-0.01,  0.34, -2.04,  0.7 ],
        [ 0.02, -1.85, -0.38,  1.66]],

       [[ 0.54,  0.49,  0.28,  1.75],
        [-1.52, -1.72,  0.68,  0.17],
        [-0.89,  0.32, -1.88,  0.15]]])>
  • Related