简体   繁体   中英

How can I reshape the tensor

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])

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]])

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)

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