Home > Software design >  How can I reshape the tensor
How can I reshape the tensor

Time:02-12

tensor([[17,  0],
        [93,  0],
        [ 4,  0],
        [72,  0],
        [83,  0],
        [67,  0],
        [34,  0],
        [21,  0],
        [19,  0])

I want to remove 0 from this tensor, which is a two-dimensional array, and make it a one-dimensional array.

How can I make this tensor with the tensor below?

tensor([[17],
        [93],
        [4],
        [72],
        [83],
        [67],
        [34],
        [21],
        [19])

CodePudding user response:

Assuming that the tensor is a numpy array.

Firsly, flatten the matrix using x= x.flatten()

Then remove all occurences of zeros using x = x[x!=0]

Then reshape the array back in 2D using x = np.reshape(x, ( -1, x.shape[0] ))

This (x) would return you:

array([[17, 93,  4, 72, 83, 67, 34, 21, 19]])

CodePudding user response:

In Tensorflow, you can simply use a boolean_mask:

import tensorflow as tf

tensor = tf.constant([[17,  0],
        [93,  0],
        [ 4,  0],
        [72,  0],
        [83,  0],
        [67,  0],
        [34,  0],
        [21,  0],
        [19,  0]])
tensor = tf.boolean_mask(tensor, tf.cast(tensor, dtype=tf.bool), axis=0)
tf.Tensor([17 93  4 72 83 67 34 21 19], shape=(9,), dtype=int32)
  • Related