Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reshaping tensor 2d to 1d

tensor([[17,  0],
        [93,  0],
        [0,  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],
        [0],
        [21],
        [19])

When using the code below, there is a problem that the existing zero disappears.
How should I fix this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

x = x.flatten()
x = x[x!=0]
x = np.reshape(x, ( -1, x.shape[0] ))

array([[17, 93, 21, 19]])

>Solution :

You can use slicing to index the 0 column

import torch

t = torch.tensor(
      [[17,  0],
       [93,  0],
       [0,  0],
       [21,  0],
       [19,  0]]
    )

print(t[:,0])

Output

tensor([17, 93,  0, 21, 19])

And if you want to keep it a 2D array then you can use numpy.reshape

import torch
import numpy as np

t = torch.tensor(
      [[17,  0],
       [93,  0],
       [0,  0],
       [21,  0],
       [19,  0]]
    )

print(np.reshape(t[:,0], (-1, 1)))

Output

array([[17],
       [93],
       [ 0],
       [21],
       [19]], dtype=int32)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading