Home > Net >  Using reshape or view in a certain fashion
Using reshape or view in a certain fashion

Time:07-07

import torch
import numpy as np
a = torch.tensor([[1, 4], [2, 5],[3, 6]])
bb=a.detach().numpy()
b = a.view(6).detach().numpy()

Element b is like:

[1 4 2 5 3 6]

How do I reshape back to the following:

[1 2 3 4 5 6]

This is just an example, want some generic answers, even 3D.

CodePudding user response:

If you want to remain in PyTorch, you can view b in a's shape, then apply a transpose and flatten:

>>> b.view(-1,2).T.flatten()
tensor([1, 2, 3, 4, 5, 6])

CodePudding user response:

In Pytorch you can use reshape and permute as in this example:

Import torch
a = torch.randn((3,3,2))
b = a.permute(2,0,1).reshape(-1) 
a
tensor([[[ 0.2372,  0.5550],
         [ 0.7700, -0.3693],
         [-0.4151,  0.6247]],

        [[ 1.2179,  0.6992],
         [ 0.5033,  1.6290],
         [-1.2165, -0.4180]],

        [[ 0.3189,  0.3208],
         [ 0.3894,  2.5544],
         [-1.3069, -0.6905]]])
b
tensor([ 0.2372,  0.7700, -0.4151,  1.2179,  0.5033, -1.2165,  0.3189,  0.3894,
        -1.3069,  0.5550, -0.3693,  0.6247,  0.6992,  1.6290, -0.4180,  0.3208,
         2.5544, -0.6905])

I think this solves the problem.

CodePudding user response:

I can't help with the torch step, but starting with a numpy array:

In [70]: a=np.array([[1, 4], [2, 5],[3, 6]])
In [71]: a
Out[71]: 
array([[1, 4],
       [2, 5],
       [3, 6]])

In [72]: a.ravel()           # can also use reshape
Out[72]: array([1, 4, 2, 5, 3, 6])

To get a column major copy:

In [73]: a.ravel(order='F')
Out[73]: array([1, 2, 3, 4, 5, 6])

In [74]: a.T.ravel()
Out[74]: array([1, 2, 3, 4, 5, 6])

the transpose:

In [79]: a.T
Out[79]: 
array([[1, 2, 3],
       [4, 5, 6]])

For 3d arrays, you can use transpose with an order parameter.

  • Related