Skip to main content

Tensor Class

Tensor
class
Multi-dimensional array (tensor) with typed storage.Core data structure for numerical computing. Supports N-dimensional arrays with any shape, multiple data types (float32, float64, int32, etc.), memory-efficient strided views, and device abstraction (CPU, WebGPU, WASM).
import { tensor } from 'deepbox/ndarray';

// Create from nested arrays
const t = tensor([[1, 2, 3], [4, 5, 6]]);
console.log(t.shape);  // [2, 3]
console.log(t.dtype);  // 'float32'

Properties

shape
Shape
The dimensions of the tensor as a readonly array of numbers.
dtype
DType
Data type of tensor elements. One of: 'float32', 'float64', 'int32', 'int64', 'uint8', 'bool', 'string'.
device
Device
Device where the tensor resides ('cpu', 'webgpu', 'wasm').
size
number
Total number of elements in the tensor.
ndim
number
Number of dimensions (rank) of the tensor.
data
TypedArray | string[]
Underlying data buffer. TypedArray for numeric types, string array for string dtype.
strides
readonly number[]
Memory strides for each dimension. Determines step size in the buffer for each axis.
offset
number
Offset into the underlying data buffer.

Methods

reshape
function
Reshape the tensor to a new shape without copying data.Parameters:
  • newShape (Shape) - The desired shape for the tensor
Returns: Tensor with the new shape
const t = tensor([1, 2, 3, 4, 5, 6]);
const reshaped = t.reshape([2, 3]);
console.log(reshaped.shape); // [2, 3]
flatten
function
Flatten the tensor to a 1-dimensional array.Returns: 1D tensor with shape [size]
const matrix = tensor([[1, 2, 3], [4, 5, 6]]);
const flat = matrix.flatten();
console.log(flat.shape); // [6]
slice
function
Slice the tensor along one or more axes.Parameters:
  • ...ranges (SliceRange[]) - Per-axis slice specifications (number, or {start?, end?, step?})
Returns: New tensor with the sliced data
const t = tensor([[1, 2, 3], [4, 5, 6]]);
t.slice(0);  // tensor([1, 2, 3])
t.slice({ start: 0, end: 1 }, { start: 1 }); // tensor([[2, 3]])
at
function
Get element at the specified indices.Parameters:
  • ...indices (number[]) - Index for each dimension
Returns: Element value
const t = tensor([[1, 2], [3, 4]]);
console.log(t.at(0, 1)); // 2
toArray
function
Convert tensor to nested JavaScript arrays.Returns: Nested array representation
const t = tensor([[1, 2], [3, 4]]);
console.log(t.toArray()); // [[1, 2], [3, 4]]
toString
function
Return a human-readable string representation.Parameters:
  • maxElements (number) - Maximum elements to display per dimension (default: 6)
Returns: Formatted string
const t = tensor([1, 2, 3]);
console.log(t.toString()); // "tensor([1, 2, 3], dtype=float32)"

Creation Functions

tensor
function
Create a tensor from nested arrays or TypedArray.Primary function for creating tensors. Accepts nested JavaScript arrays, TypedArrays, or scalars.Parameters:
  • data (NestedArray | TypedArray) - Input data
  • opts (TensorCreateOptions) - Optional { dtype?, device? }
Returns: New tensor
import { tensor } from 'deepbox/ndarray';

// From nested arrays
const t1 = tensor([[1, 2, 3], [4, 5, 6]]);

// Specify dtype
const t2 = tensor([1, 2, 3], { dtype: 'int32' });

// From TypedArray
const data = new Float32Array([1, 2, 3, 4]);
const t3 = tensor(data);

// Scalar
const t4 = tensor(42);
zeros
function
Create a tensor filled with zeros.Parameters:
  • shape (Shape) - Tensor dimensions
  • opts (TensorCreateOptions) - Optional { dtype?, device? }
Returns: Tensor filled with zeros
import { zeros } from 'deepbox/ndarray';

const z = zeros([2, 3]);
// [[0, 0, 0],
//  [0, 0, 0]]
ones
function
Create a tensor filled with ones.Parameters:
  • shape (Shape) - Tensor dimensions
  • opts (TensorCreateOptions) - Optional { dtype?, device? }
Returns: Tensor filled with ones
import { ones } from 'deepbox/ndarray';

const o = ones([2, 3]);
// [[1, 1, 1],
//  [1, 1, 1]]
full
function
Create a tensor filled with a scalar value.Parameters:
  • shape (Shape) - Tensor dimensions
  • value (number | string) - Fill value
  • opts (TensorCreateOptions) - Optional { dtype?, device? }
Returns: Tensor filled with the value
import { full } from 'deepbox/ndarray';

const f = full([2, 3], 7);
// [[7, 7, 7],
//  [7, 7, 7]]
empty
function
Create an uninitialized tensor (values are undefined).Parameters:
  • shape (Shape) - Tensor dimensions
  • opts (TensorCreateOptions) - Optional { dtype?, device? }
Returns: Uninitialized tensor
import { empty } from 'deepbox/ndarray';

const e = empty([2, 3]);
arange
function
Create a tensor with evenly spaced values within a given interval.Parameters:
  • start (number) - Start value (or stop if only one arg)
  • stop (number) - Optional stop value
  • step (number) - Step size (default: 1)
  • opts (TensorCreateOptions) - Optional { dtype?, device? }
Returns: 1D tensor with range values
import { arange } from 'deepbox/ndarray';

const a1 = arange(5);        // [0, 1, 2, 3, 4]
const a2 = arange(1, 5);     // [1, 2, 3, 4]
const a3 = arange(0, 10, 2); // [0, 2, 4, 6, 8]
linspace
function
Create evenly spaced numbers over a specified interval.Returns num evenly spaced samples, calculated over the interval [start, stop].Parameters:
  • start (number) - Starting value
  • stop (number) - End value
  • num (number) - Number of samples (default: 50)
  • endpoint (boolean) - If true, stop is the last sample (default: true)
  • opts (TensorCreateOptions) - Optional { dtype?, device? }
Returns: 1D tensor with linearly spaced values
import { linspace } from 'deepbox/ndarray';

const x = linspace(0, 10, 5);
// [0, 2.5, 5, 7.5, 10]

const y = linspace(0, 10, 5, false);
// [0, 2, 4, 6, 8]
logspace
function
Create numbers spaced evenly on a log scale.In linear space, the sequence starts at base^start and ends with base^stop.Parameters:
  • start (number) - base^start is the starting value
  • stop (number) - base^stop is the final value
  • num (number) - Number of samples (default: 50)
  • base (number) - Base of the log space (default: 10)
  • endpoint (boolean) - If true, stop is the last sample (default: true)
  • opts (TensorCreateOptions) - Optional { dtype?, device? }
Returns: 1D tensor with log-spaced values
import { logspace } from 'deepbox/ndarray';

const x = logspace(0, 3, 4);
// [1, 10, 100, 1000]
geomspace
function
Create numbers spaced evenly on a log scale (geometric progression).Each output value is a constant multiple of the previous.Parameters:
  • start (number) - Starting value
  • stop (number) - Final value
  • num (number) - Number of samples (default: 50)
  • endpoint (boolean) - If true, stop is the last sample (default: true)
  • opts (TensorCreateOptions) - Optional { dtype?, device? }
Returns: 1D tensor with geometrically spaced values
import { geomspace } from 'deepbox/ndarray';

const x = geomspace(1, 1000, 4);
// [1, 10, 100, 1000]
eye
function
Create a 2D identity matrix.Returns a 2D tensor with ones on the diagonal and zeros elsewhere.Parameters:
  • n (number) - Number of rows
  • m (number) - Number of columns (default: n, making it square)
  • k (number) - Index of the diagonal (default: 0, main diagonal)
  • opts (TensorCreateOptions) - Optional { dtype?, device? }
Returns: 2D identity matrix
import { eye } from 'deepbox/ndarray';

const I = eye(3);
// [[1, 0, 0],
//  [0, 1, 0],
//  [0, 0, 1]]

const A = eye(3, 4, 1);
// [[0, 1, 0, 0],
//  [0, 0, 1, 0],
//  [0, 0, 0, 1]]
randn
function
Create a tensor filled with random samples from a standard normal distribution.Uses Box-Muller transform to generate N(0, 1) distributed values.Parameters:
  • shape (Shape) - Tensor dimensions
  • opts (TensorCreateOptions) - Optional { dtype?, device? }
Returns: Tensor with random normal values
import { randn } from 'deepbox/ndarray';

const x = randn([2, 3]);
// Random values from N(0, 1)

Shape Manipulation

reshape
function
Reshape a tensor to a new shape without copying data.Parameters:
  • t (Tensor) - Input tensor
  • newShape (Shape) - The desired shape (can use -1 for one inferred dimension)
Returns: Reshaped tensor
import { reshape, tensor } from 'deepbox/ndarray';

const t = tensor([1, 2, 3, 4, 5, 6]);
const r = reshape(t, [2, 3]);
console.log(r.shape); // [2, 3]

// Infer one dimension
const r2 = reshape(t, [-1, 2]); // [3, 2]
flatten
function
Flatten a tensor to 1D.Parameters:
  • t (Tensor) - Input tensor
Returns: 1D tensor
import { flatten, tensor } from 'deepbox/ndarray';

const t = tensor([[1, 2], [3, 4]]);
const flat = flatten(t);
console.log(flat.shape); // [4]
transpose
function
Transpose tensor dimensions.Reverses or permutes the axes of a tensor.Parameters:
  • t (Tensor) - Input tensor
  • axes (readonly number[]) - Optional permutation of axes. If undefined, reverses all axes
Returns: Transposed tensor
import { transpose, tensor } from 'deepbox/ndarray';

const x = tensor([[1, 2], [3, 4]]);
const y = transpose(x);
// [[1, 3],
//  [2, 4]]

const z = tensor([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]);
const w = transpose(z, [2, 0, 1]);
expandDims
function
Expand tensor dimensions by inserting a new axis.Parameters:
  • t (Tensor) - Input tensor
  • axis (Axis) - Position where new axis is placed
Returns: Tensor with expanded dimensions
import { expandDims, tensor } from 'deepbox/ndarray';

const t = tensor([1, 2, 3]);  // shape: [3]
const e = expandDims(t, 0);   // shape: [1, 3]
const e2 = expandDims(t, -1); // shape: [3, 1]
squeeze
function
Remove dimensions of size 1 from tensor shape.Parameters:
  • t (Tensor) - Input tensor
  • axis (Axis | readonly Axis[]) - Optional specific axis/axes to squeeze
Returns: Tensor with squeezed dimensions
import { squeeze, tensor } from 'deepbox/ndarray';

const t = tensor([[[1], [2], [3]]]);  // shape: [1, 3, 1]
const s = squeeze(t);                 // shape: [3]
const s2 = squeeze(t, 0);             // shape: [3, 1]
unsqueeze
function
Alias for expandDims.

Indexing

slice
function
Slice a tensor along one or more axes.Parameters:
  • t (Tensor) - Input tensor
  • ...ranges (SliceRange[]) - Per-axis slice specifications
Returns: Sliced tensor
import { slice, tensor } from 'deepbox/ndarray';

const t = tensor([[1, 2, 3], [4, 5, 6]]);
slice(t, 0);  // tensor([1, 2, 3])
slice(t, { start: 0, end: 1 }, { start: 1 }); // tensor([[2, 3]])
gather
function
Gather values along an axis using indices.Parameters:
  • t (Tensor) - Input tensor
  • indices (Tensor) - Index tensor
  • axis (Axis) - Axis along which to gather
Returns: Gathered tensor
import { gather, tensor } from 'deepbox/ndarray';

const t = tensor([[1, 2], [3, 4]]);
const indices = tensor([1, 0], { dtype: 'int32' });
const result = gather(t, indices, 0);
// [[3, 4], [1, 2]]

Types

TensorCreateOptions
type
Options for tensor creation.
type TensorCreateOptions = {
  dtype?: DType;
  device?: Device;
};
NestedArray
type
Recursive type for nested number arrays.
type NestedArray = number | boolean | NestedArray[];
SliceRange
type
Slice range specification.
type SliceRange = number | {
  start?: number;
  end?: number;
  step?: number;
};
AnyTensor
type
Union type representing either a Tensor or GradTensor.
type AnyTensor = Tensor | GradTensor;

Build docs developers (and LLMs) love