torch.view_as_complex
Interpret a real tensor as a complex tensor.
Converts a real tensor with last dimension size 2 into a complex tensor view. The last dimension's first element is interpreted as the real part, and the second element as the imaginary part. This is a zero-copy operation that reinterprets the memory layout.
Important Note on Implementation: torch.js uses an emulated complex representation since WebGPU lacks native complex support. Complex tensors are stored as real tensors with shape [..., 2] where the last dimension stores [real, imaginary] pairs. Complex operations are performed on this paired representation.
- Zero-copy operation: This is a view that reinterprets shape, not a copy
- Last dimension constraint: Input must have exactly 2 as last dimension size
- Shape reduction: Output shape is input shape with last dimension removed
- Data layout: Internally stored as interleaved [re, im, ...] pairs
- True complex dtype: Returns tensor with dtype 'complex64' (complex with float32 components)
- Inverse: Use
view_as_real()to convert back to real representation
- Dimension requirement: Will throw if input's last dimension is not exactly 2
- Float32 only: Input must be float32 (complex64 uses float32 components)
Parameters
inputTensor- Real-valued tensor with shape [..., 2] where: - Last dimension must be exactly 2 - First element of last dimension: real part - Second element of last dimension: imaginary part
Returns
Tensor– Complex tensor with shape [...] and dtype 'complex64'. Internally stored as interleaved [re, im, re, im, ...] pairs.Examples
// Simple complex number
const real_imag = torch.tensor([[1, 2], [3, 4]]); // shape [2, 2]
const z = torch.view_as_complex(real_imag); // shape [2]
// z[0] = 1 + 2i (real=1, imag=2)
// z[1] = 3 + 4i (real=3, imag=4)
// Batch of complex numbers
const batch = torch.randn(32, 10, 2); // 32 samples, 10 complex numbers each
const complex_batch = torch.view_as_complex(batch); // shape [32, 10]
// 3D complex tensor (common in signal processing)
const fft_result = torch.randn(10, 100, 2); // Frequency x bins x [real, imag]
const complex_fft = torch.view_as_complex(fft_result); // shape [10, 100]
// Roundtrip conversion
const original = torch.tensor([[1, 2], [3, 4]]);
const as_complex = torch.view_as_complex(original);
const back_to_real = torch.view_as_real(as_complex); // identical to originalSee Also
- PyTorch torch.view_as_complex()
- view_as_real - Inverse operation converting complex back to real
- complex - Create complex tensor from separate real and imaginary tensors
- polar - Create complex tensor from magnitude and phase angle