Introduction
Reshaping lets you change the shape of your data without changing its content. This helps your model understand and process data in the right format.
tensor.view(new_shape)
tensor.reshape(new_shape)
tensor.squeeze(dim=None)
tensor.unsqueeze(dim)view requires the tensor to be contiguous in memory.x = torch.randn(2, 3, 4) y = x.view(6, 4)
x = torch.randn(2, 3, 4) y = x.reshape(6, 4)
x = torch.randn(1, 3, 1, 4) y = x.squeeze()
x = torch.randn(3, 4) y = x.unsqueeze(0)
import torch # Original tensor of shape (2, 1, 3) x = torch.tensor([[[1, 2, 3]], [[4, 5, 6]]]) print(f"Original shape: {x.shape}") # Remove dimension of size 1 x_squeezed = x.squeeze() print(f"After squeeze: {x_squeezed.shape}") # Add a dimension at position 1 x_unsqueezed = x_squeezed.unsqueeze(1) print(f"After unsqueeze at dim 1: {x_unsqueezed.shape}") # Reshape to (3, 2) x_reshaped = x_squeezed.reshape(3, 2) print(f"After reshape to (3,2): {x_reshaped.shape}") # View to (3, 2) (same as reshape here) x_viewed = x_squeezed.view(3, 2) print(f"After view to (3,2): {x_viewed.shape}") # Print all tensors to verify content print(f"x_squeezed tensor:\n{x_squeezed}") print(f"x_unsqueezed tensor shape: {x_unsqueezed.shape}") print(f"x_reshaped tensor:\n{x_reshaped}") print(f"x_viewed tensor:\n{x_viewed}")
view only if the tensor is contiguous in memory; otherwise, use reshape.view and reshape change shape; squeeze removes size 1 dims; unsqueeze adds size 1 dims.torch.squeeze() function do to a tensor?torch.squeeze() removes dimensions that have size 1, effectively reducing unnecessary dimensions.unsqueeze which adds size 1 dims, squeeze removes them without changing data.unsqueeze(dim) adds a dimension of size 1 at the specified dim index.unsqueeze(0). tensor.unsqueeze(1) adds at position 1, C squeezes, D is invalid.t = torch.randn(2, 1, 3), what is the shape after t.view(2, 3)?t has shape (2, 1, 3), total elements = 2*1*3 = 6.import torch t = torch.randn(3, 1, 4) t = t.view(3, 3, 1, 1)
x of shape (4, 1, 28, 28). You want to prepare it for a fully connected layer that expects input shape (4, 784). Which sequence of PyTorch operations correctly reshapes x without changing data order?x has shape (4, 1, 28, 28). The middle dimension is size 1, which is unnecessary for flattening.squeeze(1) to remove the dimension of size 1 at index 1, resulting in shape (4, 28, 28).view(4, 784) to reshape (4, 28, 28) into (4, 784) without changing data order.Pass the test and this pattern moves unknown