Skip to content

deepbox/ndarray

Tensor Creation

Create tensors with tensor, zeros, arange, linspace and related functions, choose a dtype and device, and work with the Tensor class and the AnyTensor type.

  • Creation
  • Tensor

Overview

  • tensor() uses the global default dtype, float32 unless you call setDtype. NumPy defaults to float64, so tensor([0.8]) stores 0.800000011920929. Pass { dtype: "float64" } when decimals must be exact, for example when you compare results with NumPy or scikit-learn. Booleans give bool and strings give string.
  • Nested arrays are copied. A typed array is wrapped without a copy, so the tensor and the array share memory (float16 and bfloat16 are rounded into a new array instead). arange also uses the default float dtype, so pass { dtype: "int32" } when you want integers.
  • reshape, transpose, squeeze and unsqueeze return views that share memory when the layout allows it, and reshape copies a non-contiguous input. On the CPU, slice returns a copy, unlike NumPy slicing (on a device it returns a view).
  • int64 tensors are backed by BigInt64Array, so their elements are bigint. bool is stored as uint8. float16 and bfloat16 keep float32 host storage rounded to their precision. Complex, Complex64Array and Complex128Array exist as standalone types, because tensors cannot hold complex values yet.
  • Tensor and GradTensor share one method surface (t.add(1).mul(2).sum(), t.T, t.matmul(w)), and AnyTensor is the union Tensor | GradTensor. See Autograd.

Types

6

AnyTensor

type

Union type representing either a Tensor or GradTensor.

This type enables functions to accept both regular tensors and differentiable tensors interchangeably, improving API flexibility.

Use this type when a function should work with either tensor type: - Tensor: For pure numerical operations without gradient tracking - GradTensor: For operations that need automatic differentiation

type AnyTensor = TensorClass | GradTensorClass;

NestedArray

type

Recursive type for nested number arrays.

Used to represent multi-dimensional data in JavaScript arrays.

type NestedArray = number | boolean | NestedArray[];

SliceRange

type

A single index or a start/end/step range for tensor slicing.

type SliceRange = number | {    readonly start?: number;    readonly end?: number;    readonly step?: number;};

StringNestedArray

type

Recursive type for nested string arrays used in string tensor creation.

type StringNestedArray = string | StringNestedArray[];

TensorCreateOptions

type

Options for the tensor creation function.

  • readonly dtype?: DType
  • readonly device?: Device

TensorOptions

type

Options for tensor dtype and device configuration.

  • readonly dtype: DType
  • readonly device: Device

Classes

6

Complex

An immutable complex number with real and imaginary parts.

Example
import { Complex } from 'deepbox/ndarray'; const z = new Complex(3, 4);console.log(z.abs());   // 5console.log(z.phase()); // 0.9273...console.log(z.conj());  // Complex(3, -4)
Members (21)
  • constructor(re: number, im?: number)
  • readonly re: number
  • readonly im: number
  • static readonly ZERO: Complex

    Zero constant.

  • static readonly ONE: Complex

    One constant.

  • static readonly I: Complex

    Imaginary unit.

  • abs(): number

    Absolute value (modulus).

  • phase(): number

    Phase angle (argument) in radians.

  • conj(): Complex

    Complex conjugate.

  • add(other: Complex): Complex

    Addition.

  • sub(other: Complex): Complex

    Subtraction.

  • mul(other: Complex): Complex

    Multiplication.

  • div(other: Complex): Complex

    Division using Smith's algorithm.

  • neg(): Complex

    Negation.

  • exp(): Complex

    Complex exponential.

  • log(): Complex

    Complex natural logarithm (principal value).

  • sqrt(): Complex

    Complex square root (principal value, branch cut along the negative real axis).

  • pow(n: Complex | number): Complex

    Complex power.

  • equals(other: Complex, tol?: number): boolean

    Check equality within an absolute tolerance on both parts.

  • toString(): string

    String representation.

  • static fromPolar(r: number, theta: number): Complex

    Create from polar coordinates.

Complex64Array

Complex64 typed array: each element is two float32 values (real, imag).

The length property reports the number of complex elements. The underlying Float32Array has 2 * length entries.

Index access returns the real part as a number. Use getComplex(i) to get the full Complex value, or getReal(i)/getImag(i) for components.

Example
import { Complex64Array, Complex } from 'deepbox/ndarray'; const arr = Complex64Array.fromComplexArray([  new Complex(1, 2),  new Complex(3, 4),]);console.log(arr.getComplex(0)); // Complex(1, 2)console.log(arr.length);        // 2
Members (19)
  • constructor(length: number)
  • readonly length: number

    Number of complex elements.

  • readonly BYTES_PER_ELEMENT = 8

    Bytes per complex element (8 = 2 × 4).

  • readonly buffer: ArrayBuffer
  • readonly byteOffset: number
  • readonly byteLength: number
  • [Symbol.toStringTag]: string
  • getReal(index: number): number

    Get the real part at index.

  • getImag(index: number): number

    Get the imaginary part at index.

  • getComplex(index: number): Complex

    Get the element at index as a Complex.

  • setComplex(index: number, value: Complex): void

    Store a complex value at index.

  • setRI(index: number, re: number, im: number): void

    Store real and imaginary parts at index.

  • static fromComplexArray(values: readonly Complex[]): Complex64Array

    Create from an array of Complex values.

  • static fromInterleaved(data: ArrayLike<number>): Complex64Array

    Create from interleaved real/imaginary pairs [re0, im0, re1, im1, ...].

  • fill(value: Complex, start?: number, end?: number): this

    Fill the range [start, end) with a complex value.

  • slice(start?: number, end?: number): Complex64Array

    Copy of the range [start, end).

  • set(source: ArrayLike<number> | Complex64Array | Complex128Array, offset?: number): void

    Copy values into this array starting at complex index offset.

  • [Symbol.iterator](): IterableIterator<number>

    Iterator over real parts (for TypedArray compatibility).

  • toComplexArray(): Complex[]

    Convert to an array of Complex values.

Complex128Array

Complex128 typed array: each element is two float64 values (real, imag).

Same API as Complex64Array but with double precision.

Example
import { Complex128Array, Complex } from 'deepbox/ndarray'; const arr = Complex128Array.fromComplexArray([  new Complex(1.5, 2.5),  new Complex(3.14, -1.0),]);console.log(arr.getComplex(1)); // Complex(3.14, -1)
Members (19)
  • constructor(length: number)
  • readonly length: number

    Number of complex elements.

  • readonly BYTES_PER_ELEMENT = 16

    Bytes per complex element (16 = 2 × 8).

  • readonly buffer: ArrayBuffer
  • readonly byteOffset: number
  • readonly byteLength: number
  • [Symbol.toStringTag]: string
  • getReal(index: number): number

    Get the real part at index.

  • getImag(index: number): number

    Get the imaginary part at index.

  • getComplex(index: number): Complex

    Get the element at index as a Complex.

  • setComplex(index: number, value: Complex): void

    Store a complex value at index.

  • setRI(index: number, re: number, im: number): void

    Store real and imaginary parts at index.

  • static fromComplexArray(values: readonly Complex[]): Complex128Array

    Create from an array of Complex values.

  • static fromInterleaved(data: ArrayLike<number>): Complex128Array

    Create from interleaved real/imaginary pairs [re0, im0, re1, im1, ...].

  • fill(value: Complex, start?: number, end?: number): this

    Fill the range [start, end) with a complex value.

  • slice(start?: number, end?: number): Complex128Array

    Copy of the range [start, end).

  • set(source: ArrayLike<number> | Complex64Array | Complex128Array, offset?: number): void

    Copy values into this array starting at complex index offset.

  • [Symbol.iterator](): IterableIterator<number>

    Iterator over real parts (for TypedArray compatibility).

  • toComplexArray(): Complex[]

    Convert to an array of Complex values.

BFloat16Array

Software BFloat16 (Brain Floating Point) array.

BFloat16 uses the same exponent range as float32 (8 bits) but only 7 mantissa bits, making it ideal for deep learning workloads where dynamic range matters more than precision.

Example
import { BFloat16Array } from 'deepbox/ndarray'; const arr = BFloat16Array.from([1.0, 2.0, 3.0]);console.log(arr[0]); // 1.0console.log(arr.BYTES_PER_ELEMENT); // 2
Members (18)
  • constructor(lengthOrData: number | ArrayLike<number> | ArrayBuffer, byteOffset?: number, length?: number)
  • static readonly BYTES_PER_ELEMENT = 2

    Bytes per element (always 2).

  • readonly length: number

    Number of elements.

  • readonly BYTES_PER_ELEMENT = 2

    Bytes per element (always 2).

  • readonly buffer: ArrayBuffer

    ArrayBuffer backing the storage.

  • readonly byteOffset: number

    Byte offset into the buffer.

  • readonly byteLength: number

    Byte length of the storage.

  • [Symbol.toStringTag]: string

    String tag.

  • static from(source: ArrayLike<number> | Iterable<number>): BFloat16Array

    Create a BFloat16Array from an iterable of numbers.

  • static of(...values: number[]): BFloat16Array

    Create a BFloat16Array with the given values.

  • at(index: number): number | undefined

    Get the element at index (negative counts from the end), or undefined when out of range.

  • set(source: ArrayLike<number>, offset?: number): void

    Copy numbers from source into this array starting at offset, rounding each to bfloat16.

  • slice(start?: number, end?: number): BFloat16Array

    Create a copy of a portion of the array.

  • subarray(begin?: number, end?: number): BFloat16Array

    Create a view over a portion of the array that shares memory with it.

  • fill(value: number, start?: number, end?: number): this

    Fill the range [start, end) with a value rounded to bfloat16.

  • copyWithin(target: number, start: number, end?: number): this

    Copy elements within the array.

  • [Symbol.iterator](): IterableIterator<number>

    Iterator over the element values.

  • toArray(): number[]

    Convert to a regular Array.

Float16Array

Software IEEE 754 half-precision floating-point array.

Stores elements in 2 bytes each (Uint16Array backing) and converts to/from float64 on access. Provides the same interface as native TypedArrays so they can be used with Deepbox tensors.

Example
import { Float16Array } from 'deepbox/ndarray'; const arr = Float16Array.from([1.5, 2.5, 3.5]);console.log(arr[0]); // 1.5 (after float16 rounding)console.log(arr.length); // 3console.log(arr.BYTES_PER_ELEMENT); // 2
Members (18)
  • constructor(lengthOrData: number | ArrayLike<number> | ArrayBuffer, byteOffset?: number, length?: number)
  • static readonly BYTES_PER_ELEMENT = 2

    Bytes per element (always 2).

  • readonly length: number

    Number of elements.

  • readonly BYTES_PER_ELEMENT = 2

    Bytes per element (always 2).

  • readonly buffer: ArrayBuffer

    ArrayBuffer backing the storage.

  • readonly byteOffset: number

    Byte offset into the buffer.

  • readonly byteLength: number

    Byte length of the storage.

  • [Symbol.toStringTag]: string

    String tag.

  • static from(source: ArrayLike<number> | Iterable<number>): Float16Array

    Create a Float16Array from an iterable of numbers.

  • static of(...values: number[]): Float16Array

    Create a Float16Array with the given values.

  • at(index: number): number | undefined

    Get the element at index (negative counts from the end), or undefined when out of range.

  • set(source: ArrayLike<number>, offset?: number): void

    Copy numbers from source into this array starting at offset, rounding each to float16.

  • slice(start?: number, end?: number): Float16Array

    Create a copy of a portion of the array.

  • subarray(begin?: number, end?: number): Float16Array

    Create a view over a portion of the array that shares memory with it.

  • fill(value: number, start?: number, end?: number): this

    Fill the range [start, end) with a value rounded to float16.

  • copyWithin(target: number, start: number, end?: number): this

    Copy elements within the array.

  • [Symbol.iterator](): IterableIterator<number>

    Iterator over the element values.

  • toArray(): number[]

    Convert to a regular Array.

Tensor

extends Shape = Shape, D extends DType = DType>

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 - Device placement (cpu, webgpu, wasm): with a registered WebGpuBackend, tensors on webgpu store their data in GPU memory and the accelerated op set (element-wise arithmetic, activations, matmul, reductions over all or selected axes, 2-D convolution and pooling) executes on the GPU, so move data with await t.to(device) / await t.cpu(). With a registered WasmBackend, wasm tensors keep zero-copy host storage and accelerate eligible float32 arithmetic with SIMD. Ops a device cannot execute throw DeviceError with a transfer hint instead of silently computing elsewhere (see Devices & execution on DeepboxDocs).

Example
import { tensor } from 'deepbox/ndarray'; // Create from nested arraysconst t = tensor([[1, 2, 3], [4, 5, 6]]);console.log(t.shape);  // [2, 3]console.log(t.dtype);  // 'float32' // Access propertiesconsole.log(t.size);   // 6console.log(t.ndim);   // 2
Members (105)
  • readonly shape: S
  • readonly dtype: D
  • readonly device: Device
  • readonly strides: readonly number[]
  • readonly offset: number
  • readonly size: number
  • readonly ndim: number
  • readonly data: TensorData<D>

    Underlying host storage (TypedArray, or string[] for string dtype).

  • isDeviceTensor: boolean

    true when the tensor's storage lives in device memory (its data cannot be read synchronously).

  • deviceBuffer: DeviceBuffer | null

    The device buffer backing this tensor, or null for host tensors.

  • T: Tensor

    Axes reversed, as transpose() with no argument (like numpy.ndarray.T).

  • requiresGrad: false

    Always false: a plain Tensor does not track gradients.

  • grad: null

    Always null: a plain Tensor never holds a gradient.

  • dispose(): void

    Release this tensor's device memory reference immediately.

  • static fromTypedArray<S extends Shape, D extends Exclude<DType, "string">>(args: { readonly data: TensorData<D>; readonly shape: S; readonly dtype: D; readonly device: Device; readonly offset?: number; readonly strides?: readonly number[]; }): Tensor<S, D>
  • static fromDeviceBuffer<S extends Shape>(args: { readonly owner: DeviceBufferOwner; readonly shape: S; readonly device: Device; readonly offset?: number; readonly strides?: readonly number[]; }): Tensor<S, "float32">

    Create a tensor over existing device memory.

  • static fromStringArray<S extends Shape>(args: { readonly data: string[]; readonly shape: S; readonly device?: Device; readonly offset?: number; readonly strides?: readonly number[]; }): Tensor<S, "string">
  • static zeros<S extends Shape>(shape: S, opts: TensorOptions & { readonly dtype: "string"; }): Tensor<S, "string">
  • static zeros<S extends Shape, D extends Exclude<DType, "string">>(shape: S, opts: TensorOptions & { readonly dtype: D; }): Tensor<S, D>
  • view<S2 extends Shape>(this: Tensor<S, "string">, shape: S2, strides?: readonly number[], offset?: number): Tensor<S2, "string">

    Create a view sharing the same underlying data.

  • view<S2 extends Shape>(this: Tensor<S, Exclude<DType, "string">>, shape: S2, strides?: readonly number[], offset?: number): Tensor<S2, Exclude<DType, "string">>
  • view<S2 extends Shape>(this: Tensor<S, DType>, shape: S2, strides?: readonly number[], offset?: number): Tensor<S2, DType>
  • reshape<S2 extends Shape>(this: Tensor<S, "string">, newShape: S2): Tensor<S2, "string">

    Reshape the tensor to a new shape.

  • reshape<S2 extends Shape>(this: Tensor<S, Exclude<DType, "string">>, newShape: S2): Tensor<S2, Exclude<DType, "string">>
  • reshape<S2 extends Shape>(this: Tensor<S, DType>, newShape: S2): Tensor<S2, DType>
  • flatten(this: Tensor<S, "string">): Tensor<[ number ], "string">

    Flatten the tensor to a 1-dimensional array.

  • flatten(this: Tensor<S, Exclude<DType, "string">>): Tensor<[ number ], Exclude<DType, "string">>
  • flatten(this: Tensor<S, DType>): Tensor<[ number ], DType>
  • add(other: number | Tensor): Tensor

    Element-wise sum with a tensor or a number (functional form: add).

  • sub(other: number | Tensor): Tensor

    Element-wise difference with a tensor or a number (functional form: sub).

  • mul(other: number | Tensor): Tensor

    Element-wise product with a tensor or a number (functional form: mul).

  • div(other: number | Tensor): Tensor

    Element-wise true division by a tensor or a number (functional form: div).

  • pow(exponent: number | Tensor): Tensor

    Element-wise power (functional form: pow).

  • neg(): Tensor

    Element-wise negation (functional form: neg).

  • abs(): Tensor

    Element-wise absolute value (functional form: abs).

  • exp(): Tensor

    Element-wise exponential (functional form: exp).

  • log(): Tensor

    Element-wise natural logarithm (functional form: log).

  • sqrt(): Tensor

    Element-wise square root (functional form: sqrt).

  • square(): Tensor

    Element-wise square (functional form: square).

  • sin(): Tensor

    Element-wise sine (functional form: sin).

  • cos(): Tensor

    Element-wise cosine (functional form: cos).

  • tanh(): Tensor

    Element-wise hyperbolic tangent (functional form: tanh).

  • sigmoid(): Tensor

    Element-wise logistic sigmoid (functional form: sigmoid).

  • relu(): Tensor

    Element-wise rectified linear unit (functional form: relu).

  • expm1(): Tensor

    Element-wise exp(x) - 1, accurate for small x (functional form: expm1).

  • log1p(): Tensor

    Element-wise log(1 + x), accurate for small x (functional form: log1p).

  • tan(): Tensor

    Element-wise tangent (functional form: tan).

  • maximum(other: number | Tensor): Tensor

    Element-wise larger of two tensors, or of a tensor and a number (functional form: maximum).

  • minimum(other: number | Tensor): Tensor

    Element-wise smaller of two tensors, or of a tensor and a number (functional form: minimum).

  • leakyRelu(negativeSlope?: number): Tensor

    Leaky ReLU (functional form: leakyRelu).

  • elu(alpha?: number): Tensor

    Exponential linear unit (functional form: elu).

  • selu(): Tensor

    Scaled exponential linear unit (functional form: selu).

  • gelu(options?: GeluApproximation | GeluOptions): Tensor

    Gaussian error linear unit (functional form: gelu).

  • softplus(): Tensor

    Softplus, log(1 + exp(x)) (functional form: softplus).

  • mish(): Tensor

    Mish, x * tanh(softplus(x)) (functional form: mish).

  • swish(): Tensor

    Swish (SiLU), x * sigmoid(x) (functional form: swish).

  • logSigmoid(): Tensor

    Log of the logistic function, log(sigmoid(x)) (functional form: logSigmoid).

  • hardtanh(minVal?: number, maxVal?: number): Tensor

    Clamp to [minVal, maxVal] (functional form: hardtanh).

  • tanhshrink(): Tensor

    x - tanh(x) (functional form: tanhshrink).

  • softmax(axis?: Axis): Tensor

    Softmax along an axis (functional form: softmax).

  • logSoftmax(axis?: Axis): Tensor

    Log-softmax along an axis (functional form: logSoftmax).

  • sum(axis?: Axis | readonly Axis[], keepdims?: boolean): Tensor

    Sum of elements over one axis, several axes, or all of them (functional form: sum).

  • mean(axis?: Axis | readonly Axis[], keepdims?: boolean): Tensor

    Mean of elements (functional form: mean).

  • max(axis?: Axis | readonly Axis[], keepdims?: boolean): Tensor

    Maximum of elements (functional form: max).

  • min(axis?: Axis | readonly Axis[], keepdims?: boolean): Tensor

    Minimum of elements (functional form: min).

  • prod(axis?: Axis | readonly Axis[], keepdims?: boolean): Tensor

    Product of elements (functional form: prod).

  • std(axis?: Axis | readonly Axis[], keepdims?: boolean, ddof?: number): Tensor

    Standard deviation (functional form: std).

  • var(axis?: Axis | readonly Axis[], keepdims?: boolean, ddof?: number): Tensor

    Variance (functional form: variance).

  • argmax(axis?: Axis, keepdims?: boolean): Tensor

    Index of the maximum (functional form: argmax).

  • argmin(axis?: Axis, keepdims?: boolean): Tensor

    Index of the minimum (functional form: argmin).

  • cumsum(axis?: Axis): Tensor

    Cumulative sum (functional form: cumsum).

  • matmul(other: Tensor): Tensor

    Matrix product with another tensor (functional form: matmul).

  • dot(other: Tensor): Tensor

    Dot product (functional form: dot).

  • transpose(axes?: readonly number[]): Tensor

    Permute the axes (functional form: transpose).

  • squeeze(axis?: Axis | readonly Axis[]): Tensor

    Remove axes of size 1 (functional form: squeeze).

  • unsqueeze(axis: number): Tensor

    Insert an axis of size 1 (functional form: unsqueeze).

  • gather(indices: Tensor, axis: Axis): Tensor

    Select entries along an axis with a 1-D index tensor (functional form: gather).

  • detach(): this

    Return the tensor itself.

  • backward(_grad?: Tensor): void

    Throws, because a plain Tensor is not part of a computation graph.

  • clone(): Tensor

    Copy of the tensor with its own contiguous storage (functional form: clone).

  • fill(value: number | bigint | boolean | string): this

    Set every element to one value, in place, and return the tensor (like torch.Tensor.fill_).

  • clip(min?: number, max?: number): Tensor

    Limit values to [min, max] (functional form: clip).

  • eq(other: number | Tensor): Tensor

    Element-wise equality, giving a bool tensor (functional form: equal).

  • ne(other: number | Tensor): Tensor

    Element-wise inequality (functional form: notEqual).

  • gt(other: number | Tensor): Tensor

    Element-wise greater-than (functional form: greater).

  • ge(other: number | Tensor): Tensor

    Element-wise greater-or-equal (functional form: greaterEqual).

  • lt(other: number | Tensor): Tensor

    Element-wise less-than (functional form: less).

  • le(other: number | Tensor): Tensor

    Element-wise less-or-equal (functional form: lessEqual).

  • isnan(): Tensor

    Element-wise NaN test, giving a bool tensor (functional form: isnan).

  • any(axis?: Axis | readonly Axis[], keepdims?: boolean): Tensor

    True where any element is non-zero (functional form: any).

  • all(axis?: Axis | readonly Axis[], keepdims?: boolean): Tensor

    True where all elements are non-zero (functional form: all).

  • round(decimals?: number): Tensor

    Round half to even (functional form: round).

  • floor(): Tensor

    Round down (functional form: floor).

  • ceil(): Tensor

    Round up (functional form: ceil).

  • sort(axis?: Axis | undefined, descending?: boolean): Tensor

    Sorted copy along an axis (functional form: sort).

  • argsort(axis?: Axis | undefined, descending?: boolean): Tensor

    Indices that would sort the tensor along an axis (functional form: argsort).

  • flip(axes?: Axis | readonly Axis[]): Tensor

    Reverse the order of elements along axes (functional form: flip).

  • to(device: Device): Promise<Tensor<S, DType>>

    Move the tensor to another device.

  • cpu(): Promise<Tensor<S, DType>>

    Move the tensor to the CPU.

  • slice(...ranges: SliceRange[]): Tensor

    Slice this tensor along one or more axes.

  • at(...indices: number[]): ElementOf<D>

    Read a single element.

  • astype(dtype: DType): Tensor

    Return a new tensor with the data converted to the given dtype.

  • item(): ElementOf<D>

    Extract the value of a single-element tensor as a JS scalar.

  • toArray(): unknown

    Convert to nested JavaScript arrays (a bare scalar for 0-D tensors).

  • toString(maxElements?: number): string

    Return a human-readable string representation of this tensor.

Functions

21

roundToBFloat16

function roundToBFloat16(value: number): number;

Round a number to the nearest representable bfloat16 value (ties to even).

Parameters

value
number

Returns

number

roundToFloat16

function roundToFloat16(value: number): number;

Round a number to the nearest representable IEEE 754 binary16 value (ties to even, overflow to ±Infinity).

Parameters

value
number

Returns

number

arange

function arange(start: number, stop?: number, step?: number, opts?: TensorCreateOptions): Tensor;

Evenly spaced values within a half-open interval, like NumPy's arange.

Call as arange(stop) for 0, 1, ..., stop - 1, or arange(start, stop, step). The length is ceil((stop - start) / step) (0 when the range is empty); element i is start + i * step. The default dtype is the configured default dtype, not an integer dtype.

Parameters

start
number
Start of the interval, or the stop value when stop is omitted
stopoptional
number
End of the interval (exclusive)
stepoptional
number
Spacing between values (default: 1, must be non-zero)
optsoptional
TensorCreateOptions
dtype and device

Returns

Tensor

Throws

  • InvalidParameterErrorIf step is zero or any argument is not finite
Example
arange(5);             // [0, 1, 2, 3, 4]arange(1, 2, 0.25);    // [1, 1.25, 1.5, 1.75]arange(3, 0, -1);      // [3, 2, 1]

empty

function empty(shape: Shape, opts?: TensorCreateOptions): Tensor;

Tensor with unspecified initial contents.

JavaScript always zero-initializes memory, so numeric tensors come back filled with 0 and string tensors with empty strings. Prefer zeros when the initial value matters to readers of your code.

Parameters

shape
Shape
Shape of the tensor
optsoptional
TensorCreateOptions
dtype (default: the configured default dtype) and device

Returns

Tensor

eye

function eye(n: number, m?: number, k?: number, opts?: TensorCreateOptions): Tensor;

Identity matrix.

Returns a 2D tensor with ones on the diagonal and zeros elsewhere.

Parameters

n
number
Number of rows
moptional
number
Number of columns (default: n, making it square)
koptional
number
Index of the diagonal (default: 0, main diagonal; positive is above)
optsoptional
TensorCreateOptions
Tensor options

Returns

TensorTensor of shape (n, m)

Throws

  • InvalidParameterErrorIf k is not an integer
  • DTypeErrorIf the dtype is string or complex
Example
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]]

flatten

function flatten(t: Tensor): Tensor;

Flatten a tensor to 1D in row-major order.

Returns a view for contiguous input and a copy otherwise (see reshape).

Parameters

t
Tensor
Input tensor

Returns

Tensor1D tensor with t.size elements

full

function full(shape: Shape, value: number | string | boolean, opts?: TensorCreateOptions): Tensor;

Tensor filled with one value.

Numeric dtypes take a number (or a boolean, stored as 1/0); string takes a string. The value is converted like tensor() does: integer dtypes truncate toward zero, bool maps nonzero to true, float16 / bfloat16 round to half precision, and int64 requires a finite integer.

Parameters

shape
Shape
Shape of the tensor
value
number | string | boolean
Fill value
optsoptional
TensorCreateOptions
dtype (default: the configured default dtype) and device

Returns

Tensor

Throws

  • DTypeErrorIf value does not fit the dtype
Example
full([2, 2], 7);                       // [[7, 7], [7, 7]]full([3], 5, { dtype: "bool" });       // [1, 1, 1]full([2], "x", { dtype: "string" });   // ["x", "x"]

gather

function gather(t: Tensor, indices: Tensor, axis: Axis): Tensor;

Gather values along an axis specified by indices.

The result has the shape of t with the size of axis replaced by indices.size, i.e. out[..., k, ...] = t[..., indices[k], ...]. This is torch.index_select(t, axis, indices) (and numpy.take for in-bounds indices); negative indices are not wrapped and raise an IndexError.

Parameters

t
Tensor
Input tensor (host tensor of any dtype, including string)
indices
Tensor
1D tensor of integer indices into axis
axis
Axis
Axis along which to gather (negative counts from the end)

Returns

TensorGathered tensor (copy) with the dtype of t

Throws

  • DTypeErrorIf indices is a string tensor
  • InvalidParameterErrorIf indices is not 1D or holds non-integers
  • IndexErrorIf an index is outside [0, size of axis)
Example
const t = tensor([[1, 2], [3, 4], [5, 6]]);const indices = tensor([0, 2]);const result = gather(t, indices, 0);  // [[1, 2], [5, 6]]

geomspace

function geomspace(start: number, stop: number, num?: number, endpoint?: boolean, opts?: TensorCreateOptions): Tensor;

Numbers spaced evenly on a log scale (geometric progression).

Each output value is a constant multiple of the previous. The first value is exactly start and, with endpoint: true, the last is exactly stop. Integer dtypes truncate the values toward zero.

Parameters

start
number
Starting value of the sequence (non-zero, same sign as stop)
stop
number
Final value of the sequence
numoptional
number
Number of samples (default: 50)
endpointoptional
boolean
If true, stop is the last sample (default: true)
optsoptional
TensorCreateOptions
Tensor options

Returns

TensorTensor of shape (num,)

Throws

  • InvalidParameterErrorIf start or stop is zero, non-finite or of opposite sign, or num is not a non-negative integer
Example
import { geomspace } from 'deepbox/ndarray'; const x = geomspace(1, 1000, 4);// [1, 10, 100, 1000]

linspace

function linspace(start: number, stop: number, num?: number, endpoint?: boolean, opts?: TensorCreateOptions): Tensor;

Evenly spaced numbers over a specified interval.

Returns num evenly spaced samples over [start, stop]. With endpoint: true the last sample is exactly stop. Integer dtypes floor the samples (NumPy behavior), so linspace(-5, 5, 4, true, { dtype: "int32" }) is [-5, -2, 1, 5].

Parameters

start
number
Starting value of the sequence
stop
number
End value of the sequence
numoptional
number
Number of samples to generate (default: 50)
endpointoptional
boolean
If true, stop is the last sample. Otherwise, it is not included (default: true)
optsoptional
TensorCreateOptions
Tensor options (dtype, device)

Returns

TensorTensor of shape (num,)

Throws

  • InvalidParameterErrorIf num is not a non-negative integer
Example
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 logspace(start: number, stop: number, num?: number, base?: number, endpoint?: boolean, opts?: TensorCreateOptions): Tensor;

Numbers spaced evenly on a log scale.

In linear space, the sequence starts at base^start and ends with base^stop. Integer dtypes truncate the values toward zero.

Parameters

start
number
base^start is the starting value
stop
number
base^stop is the final value
numoptional
number
Number of samples to generate (default: 50)
baseoptional
number
The base of the log space (default: 10)
endpointoptional
boolean
If true, stop is the last sample (default: true)
optsoptional
TensorCreateOptions
Tensor options

Returns

TensorTensor of shape (num,)

Throws

  • InvalidParameterErrorIf num is not a non-negative integer
Example
import { logspace } from 'deepbox/ndarray'; const x = logspace(0, 3, 4);// [1, 10, 100, 1000]

ones

function ones(shape: Shape, opts?: TensorCreateOptions): Tensor;

Tensor of ones.

With dtype: "string" every element is the text "1".

Parameters

shape
Shape
Shape of the tensor
optsoptional
TensorCreateOptions
dtype (default: the configured default dtype) and device

Returns

Tensor

Example
ones([2, 2]); // [[1, 1], [1, 1]]

randn

function randn(shape: Shape, opts?: TensorCreateOptions): Tensor;

Return a tensor filled with random samples from a standard normal distribution.

Uses the library's seeded generator, so setSeed makes the output reproducible. Integer dtypes truncate the samples toward zero.

Parameters

shape
Shape
Shape of the output tensor
optsoptional
TensorCreateOptions
Additional tensor options

Returns

Tensor

Throws

  • DTypeErrorIf the dtype is bool, string or complex
Example
import { randn } from 'deepbox/ndarray'; const x = randn([2, 3]);// Random values from N(0, 1)

reshape

function reshape(t: Tensor, rawShape: Shape): Tensor;

Give a tensor a new shape with the same number of elements.

Returns a view that shares memory with t when its layout is contiguous. Otherwise (for example after transpose) the elements are copied into row-major order first, so writes to the result do not affect t.

Parameters

t
Tensor
Input tensor
rawShape
Shape
Target shape. One dimension may be -1, in which case it is inferred from the remaining dimensions.

Returns

TensorTensor with shape rawShape

Throws

  • ShapeErrorIf the shape has more than one -1, -1 cannot be inferred, or the element count does not match
  • DataValidationErrorIf a dimension is negative (other than a single -1), fractional or not finite
Example
const x = tensor([[1, 2, 3], [4, 5, 6]]);reshape(x, [3, 2]);   // [[1, 2], [3, 4], [5, 6]]reshape(x, [-1]);     // [1, 2, 3, 4, 5, 6]

slice

function slice(t: Tensor, ...ranges: SliceRange[]): Tensor;

Slice a tensor.

Each argument selects along one leading axis: a number picks a single index and drops that axis; a { start, end, step } range keeps the axis (NumPy slicing semantics, negative bounds count from the end, step may be negative). Axes without an argument are kept whole. The result is a copy.

Parameters

t
Tensor
Input tensor
ranges
SliceRange[]
One index or range per leading axis

Returns

TensorSliced tensor

Throws

  • ShapeErrorIf more ranges than dimensions are given
  • IndexErrorIf a single index is out of bounds
  • InvalidParameterErrorIf a step is zero or a bound is not an integer
Example
const t = tensor([[1, 2, 3], [4, 5, 6]]);slice(t, { start: 0, end: 1 });  // [[1, 2, 3]]slice(t, 0, { start: 1 });       // [2, 3]

tensor

function tensor(data: NestedArray | StringNestedArray | TypedArray, opts?: TensorCreateOptions): Tensor;

Parameters

data
NestedArray | StringNestedArray | TypedArray
optsoptional
TensorCreateOptions

Returns

Tensor

transpose

function transpose(t: Tensor, axes?: readonly number[]): Tensor;

Transpose tensor dimensions.

Reverses or permutes the axes of a tensor. The result is a view that shares memory with the input.

Parameters

t
Tensor
Input tensor
axesoptional
readonly number[]
Permutation of axes. If undefined, reverses all axes

Returns

TensorTransposed tensor (view)

Throws

  • ShapeErrorIf axes does not have one entry per dimension
  • InvalidParameterErrorIf axes contains a non-integer, an out-of-range axis or a duplicate
Example
import { transpose, tensor } from 'deepbox/ndarray'; const x = tensor([[1, 2], [3, 4]]);  // shape: (2, 2)const y = transpose(x);              // shape: (2, 2), values: [[1, 3], [2, 4]] const z = tensor([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]);  // shape: (2, 2, 2)const w = transpose(z, [2, 0, 1]);   // shape: (2, 2, 2), axes permuted

zeros

function zeros(shape: Shape, opts?: TensorCreateOptions): Tensor;

Tensor of zeros.

With dtype: "string" every element is the empty string.

Parameters

shape
Shape
Shape of the tensor
optsoptional
TensorCreateOptions
dtype (default: the configured default dtype) and device

Returns

Tensor

Example
zeros([2, 3]); // 2x3 tensor of 0

expandDims

function expandDims(t: Tensor, axis: number): Tensor;

Expand the shape by inserting a new axis.

Returns a view of the tensor with a new dimension of size 1 inserted at the specified position.

Complexity: O(ndim) - only manipulates shape metadata, no data copy

Parameters:

Parameters

t
Tensor
Input tensor
axis
number
Position where new axis is placed (can be negative) Returns: Tensor with expanded dimensions (view, no copy)

Returns

Tensor

Example
import { unsqueeze, tensor } from 'deepbox/ndarray'; const x = tensor([1, 2, 3]);     // shape: (3,)const y = unsqueeze(x, 0);       // shape: (1, 3)const z = unsqueeze(x, 1);       // shape: (3, 1)const w = unsqueeze(x, -1);      // shape: (3, 1)

squeeze

function squeeze(t: Tensor, axis?: Axis | readonly Axis[]): Tensor;

Remove single-dimensional entries from the shape.

Returns a view of the tensor with all dimensions of size 1 removed. If axis is specified, only removes dimensions at those positions.

Complexity: O(ndim) - only manipulates shape metadata, no data copy

Parameters:

Parameters

t
Tensor
Input tensor
axisoptional
Axis | readonly Axis[]
Axis to squeeze. If undefined, squeeze all axes of size 1 Returns: Tensor with squeezed dimensions (view, no copy)

Returns

Tensor

Throws

  • ShapeErrorIf an axis is specified and its dimension is not 1
  • InvalidParameterErrorIf an axis is out of range or listed twice
Example
import { squeeze, tensor } from 'deepbox/ndarray'; const x = tensor([[[1], [2], [3]]]);  // shape: (1, 3, 1)const y = squeeze(x);                  // shape: (3,)const z = squeeze(x, 2);               // shape: (1, 3)

unsqueeze

function unsqueeze(t: Tensor, axis: number): Tensor;

Expand the shape by inserting a new axis.

Returns a view of the tensor with a new dimension of size 1 inserted at the specified position.

Complexity: O(ndim) - only manipulates shape metadata, no data copy

Parameters:

Parameters

t
Tensor
Input tensor
axis
number
Position where new axis is placed (can be negative) Returns: Tensor with expanded dimensions (view, no copy)

Returns

Tensor

Example
import { unsqueeze, tensor } from 'deepbox/ndarray'; const x = tensor([1, 2, 3]);     // shape: (3,)const y = unsqueeze(x, 0);       // shape: (1, 3)const z = unsqueeze(x, 1);       // shape: (3, 1)const w = unsqueeze(x, -1);      // shape: (3, 1)
ndarray-tensor.ts
import { Complex, arange, eye, linspace, tensor, zeros } from "deepbox/ndarray"; const a = tensor([[1, 2], [3, 4]]);const exact = tensor([0.8, 0.2], { dtype: "float64" });const counts = tensor([1, 2, 3], { dtype: "int32" }); console.log(a.shape, a.dtype, exact.dtype, counts.dtype);console.log(arange(0, 1, 0.25).toString(), linspace(0, 1, 5).toString());console.log(a.reshape([4]).toString(), a.T.toString());console.log(zeros([2, 2]).toString(), eye(3).toString());console.log(new Complex(1, -2).toString());