Pytorch Torch View_As_Real
## PyTorch torch.view_as_real Function
`torch.view_as_real` is a PyTorch function used to return a real-valued view of a complex tensor. It splits each complex value into its real and imaginary components, appending a new dimension of size 2 at the end of the tensor.
---
### Function Definition
```python
torch.view_as_real(input) -> Tensor
```
#### Parameters
* **input** (*Tensor*): The input complex tensor. It must have a complex data type, such as `torch.complex64` or `torch.complex128`.
#### Return Value
* Returns a real-valued tensor representing the complex input tensor. If the input tensor has a shape of `(...)`, the returned tensor will have a shape of `(..., 2)`.
---
### Code Example
The following example demonstrates how to convert a 1D complex tensor into a 2D real tensor using `torch.view_as_real`.
```python
import torch
# Create a complex tensor
x = torch.tensor([1+2j, 3+4j, 5+6j])
# Convert to a real-valued view
y = torch.view_as_real(x)
print("Original complex tensor shape:", x.shape)
print("Real tensor shape:", y.shape)
print("Real tensor content:")
print(y)
```
#### Output
```text
Original complex tensor shape: torch.Size()
Real tensor shape: torch.Size([3, 2])
Real tensor content:
tensor([[1., 2.],
[3., 4.],
[5., 6.]])
```
---
### Key Considerations and Behavior
1. **Memory Sharing (View vs. Copy)**:
`torch.view_as_real` returns a **view** of the original tensor, meaning it shares the same underlying data storage. Modifying the returned real tensor will directly modify the original complex tensor, and vice versa. No data copy is performed, making this operation extremely fast ($O(1)$ time complexity).
2. **Data Type Mapping**:
The data type of the returned tensor is mapped to its corresponding real-valued counterpart:
* `torch.complex64` (FloatComplex) $\rightarrow$ `torch.float32` (Float)
* `torch.complex128` (DoubleComplex) $\rightarrow$ `torch.float64` (Double)
3. **Inverse Operation**:
To perform the reverse operation (converting a real tensor with a final dimension of size 2 back into a complex tensor), you can use the complementary function: [`torch.view_as_complex`](https://pytorch.org/docs/stable/generated/torch.view_as_complex.html).
YouTip