torch.reshape
function reshape(input: Tensor, shape: number[]): voidReturns a tensor with the same data and number of elements as input, but with the specified shape.
Reshapes a tensor without changing its underlying data or number of elements. This is a powerful operation for adjusting tensor dimensions to match required operation inputs. Useful for:
- Converting between different tensor layouts
- Flattening multi-dimensional data for processing
- Expanding 1D data into matrices or higher-dimensional tensors
- Preparing data for operations with specific shape requirements
- Batch processing and data reformatting
- Memory layout preserved: Assumes row-major (C-style) contiguous layout
- No data movement: Very fast operation when tensor is already contiguous
- View operation: Result shares storage with input when possible
- Dimension inference: Use -1 for one dimension to compute it automatically
- Element count preserved: Total elements must remain the same
- Dimension mismatch: If total elements don't match, operation fails
- Non-contiguous tensors: May need to call contiguous() first
- Memory order: Assumes C-style row-major order (not Fortran/column-major)
Parameters
inputTensor- The input tensor (any shape, any dtype)
shapenumber[]- Target shape as array of integers. Can include at most one -1 to infer that dimension.
Returns
A new view of the data with the specified shape (same number of elements)
Examples
// Flatten to 1D
const x = torch.randn(2, 3, 4);
torch.reshape(x, [24]); // [24]
// Reshape to 2D
const y = torch.randn(12);
torch.reshape(y, [3, 4]); // [3, 4]
// Reshape with dimension inference (-1)
const z = torch.randn(2, 3, 4);
torch.reshape(z, [-1, 12]); // [2, 12]
torch.reshape(z, [2, -1]); // [2, 12]
// Batch processing: convert batches to matrices
const batches = torch.randn(32, 10, 10); // 32 images of 10x10
const flat = torch.reshape(batches, [32, 100]); // 32 vectors of 100
// Add dimension for operations
const vector = torch.randn(64);
const matrix = torch.reshape(vector, [1, 64]); // Add batch dimension