Home > Mobile >  Change shape of pytorch tensor
Change shape of pytorch tensor

Time:12-13

I have a pytorch tensor with a shape: torch.size([6000, 30, 30, 9]) and I want to convert it into the shape: torch.size([6000, 8100]) such that I go from 6000 elements that contain 30 elements that in turn contain 30 elements that in turn contain 9 elements TO 6000 elements that contain 8100 elements. How do I achieve it?

CodePudding user response:

let's say you have a tensor x with the shape torch.size([6000, 30, 30, 9]). In Pytorch, To change the shape of it to torch.size([6000, 8100]), you can use the function view or reshape to keep the first dimension of the tensor (6000) and flatten the rest of dimensions (30,30,9) as follows:

import torch

x= torch.rand(6000, 30, 30, 9)
print(x.shape) #torch.Size([6000, 30, 30, 9])
x=x.view(6000,-1) # or x= x.view(x.size(0),-1)
print(x.shape) #torch.Size([6000, 8100])

x= torch.rand(6000, 30, 30, 9)
print(x.shape) #torch.Size([6000, 30, 30, 9])
x=x.reshape(6000,-1) # or x= x.reshape(x.size(0),-1)
print(x.shape) #torch.Size([6000, 8100])
  • Related