April 2, 2024, 10:19 p.m. | Super Kai (Kazuya Ito)

DEV Community dev.to

flatten() can remove zero or more dimensions from a 0D or more tensor as shown below:



import torch

my_tensor = torch.tensor(2)

torch.flatten(my_tensor)
torch.flatten(my_tensor, 0, 0)
torch.flatten(my_tensor, 0, -1)
torch.flatten(my_tensor, -1, 0)
torch.flatten(my_tensor, -1, -1)
# tensor([2])

my_tensor= torch.tensor([2, 7, 4]) # 1D tensor

torch.flatten(my_tensor)
torch.flatten(my_tensor, 0, 0)
torch.flatten(my_tensor, 0, -1)
torch.flatten(my_tensor, -1, 0)
torch.flatten(my_tensor, -1, -1)
# tensor([2, 7, 4])

my_tensor = torch.tensor([[2, 7, 4], [8, 3, 2]]) # 2D tensor

torch.flatten(my_tensor)
torch.flatten(my_tensor, 0, 0)
torch.flatten(my_tensor, 0, 1)
torch.flatten(my_tensor, 0, …

dimensions flat flatten import pytorch tensor torch

AI Engineer Intern, Agents

@ Occam AI | US

AI Research Scientist

@ Vara | Berlin, Germany and Remote

Data Architect

@ University of Texas at Austin | Austin, TX

Data ETL Engineer

@ University of Texas at Austin | Austin, TX

Lead GNSS Data Scientist

@ Lurra Systems | Melbourne

Data Engineer - Takealot Group (Takealot.com | Superbalist.com | Mr D Food)

@ takealot.com | Cape Town