Shape & Indexing
Change tensor shape without copying data when possible. The total number of elements must remain the same. Use -1 for one inferred dimension.
shape: Shape - Target shape (e.g., [2, 6] or [3, -1])Permute tensor dimensions. Without axes argument, reverses all dimensions (matrix transpose). Creates a strided view — no data copy.
axes: number[] - New order of dimensions. Default: reversed.Collapse all dimensions into a single 1D tensor. Equivalent to reshape(t, [-1]).
Remove size-1 dimensions. If axis is specified, only removes that dimension (must be size 1).
Insert a size-1 dimension at the specified position. Useful for broadcasting.
Alias for unsqueeze. Adds a new axis at the given position.
Extract a sub-tensor using [start, stop] ranges for each dimension. Returns a strided view — no data copy.
ranges: SliceRange[] - Array of [start, stop] pairs, one per dimensionGather elements along an axis using an index tensor. Supports autograd backward pass.
import { tensor, reshape, transpose, flatten, squeeze, unsqueeze, slice, gather } from "deepbox/ndarray";const t = tensor([[1, 2, 3], [4, 5, 6]]);// Reshapereshape(t, [3, 2]); // [[1, 2], [3, 4], [5, 6]]reshape(t, [6]); // [1, 2, 3, 4, 5, 6]reshape(t, [-1]); // [1, 2, 3, 4, 5, 6] (-1 inferred)// Transposetranspose(t); // [[1, 4], [2, 5], [3, 6]]// Flattenflatten(t); // [1, 2, 3, 4, 5, 6]// Squeeze/Unsqueezeconst s = tensor([[[1, 2, 3]]]); // shape: [1, 1, 3]squeeze(s); // shape: [3]unsqueeze(t, 0); // shape: [1, 2, 3]// Slicingslice(t, [[0, 1], [1, 3]]); // [[2, 3]] (row 0, cols 1-2)// Gatherconst idx = tensor([0, 2], { dtype: "int32" });gather(t, idx, 1); // [[1, 3], [4, 6]]When to Use
- reshape — Match expected input shapes for layers (e.g., flatten before Linear)
- transpose — Convert between row-major and column-major, or permute batch dimensions
- squeeze/unsqueeze — Add or remove batch dimensions for broadcasting
- slice — Extract windows, crops, or sub-sequences from tensors
- gather — Implement embedding lookups, advanced indexing, or attention patterns