YouTip LogoYouTip

Pytorch Torch Ravel

# PyTorch torch.ravel() Tutorial `torch.ravel()` is a PyTorch function used to flatten a multi-dimensional tensor into a contiguous 1D tensor. Whenever possible, it returns a **view** of the input tensor rather than a copy, making it highly memory-efficient. --- ## Function Definition ```python torch.ravel(input) -> Tensor ``` ### Parameters * **`input`** *(Tensor)*: The input tensor to be flattened. ### Return Value * A 1D tensor containing the same elements as the input. It shares the underlying data memory with `input` whenever possible (i.e., it returns a view). --- ## Code Examples ### Example 1: Flattening a 2D Matrix The following example demonstrates how to flatten a 2D tensor (matrix) of shape `(2, 3)` into a 1D tensor of shape `(6,)`. ```python import torch # Create a 2x3 matrix x = torch.tensor([[1, 2, 3], [4, 5, 6]]) # Flatten to a 1D tensor y = torch.ravel(x) print("Original Tensor:") print(x) print("\nFlattened Tensor:") print(y) ``` **Output:** ```text Original Tensor: tensor([[1, 2, 3], [4, 5, 6]]) Flattened Tensor: tensor([1, 2, 3, 4, 5, 6]) ``` --- ### Example 2: Flattening a 3D Tensor `torch.ravel()` can flatten tensors of any arbitrary dimension. Here, we flatten a 3D tensor of shape `(2, 3, 2)` into a 1D tensor of shape `(12,)`. ```python import torch # Create a 3D tensor x = torch.arange(12).reshape(2, 3, 2) # Flatten to a 1D tensor y = torch.ravel(x) print("Original 3D Tensor:") print(x) print("\nFlattened Tensor:") print(y) ``` **Output:** ```text Original 3D Tensor: tensor([[[ 0, 1], [ 2, 3], [ 4, 5]], [[ 6, 7], [ 8, 9], [10, 11]]]) Flattened Tensor: tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) ``` --- ## Key Considerations & Memory Behavior ### 1. View vs. Copy Because `torch.ravel()` returns a **view** of the original tensor whenever possible, modifying the returned tensor will also modify the original tensor. ```python import torch x = torch.tensor([[1, 2], [3, 4]]) y = torch.ravel(x) # Modify an element in the flattened tensor y = 99 # The original tensor is also updated print(x) ``` **Output:** ```text tensor([[99, 2], [ 3, 4]]) ``` ### 2. Non-Contiguous Tensors If the input tensor is non-contiguous in memory (for example, after a transpose operation), `torch.ravel()` cannot return a view. In this case, it will automatically copy the data and return a new tensor. ```python # Transposing makes the tensor non-contiguous x_transposed = x.t() # This will return a copy, not a view y_copy = torch.ravel(x_transposed) ``` ### 3. Comparison with Similar Functions * **`torch.ravel(x)`**: Returns a 1D view if possible; otherwise, copies the data. Equivalent to NumPy's `np.ravel()`. * **`x.flatten()`**: Always returns a copy of the data (safer if you want to avoid side effects on the original tensor). * **`x.reshape(-1)`**: Similar to `ravel()`, it returns a view if possible, but the syntax is slightly different.
← Pytorch Torch ReciprocalPytorch Torch Randn β†’