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,float32unless you callsetDtype. NumPy defaults tofloat64, sotensor([0.8])stores0.800000011920929. Pass{ dtype: "float64" }when decimals must be exact, for example when you compare results with NumPy or scikit-learn. Booleans givebooland strings givestring.- Nested arrays are copied. A typed array is wrapped without a copy, so the tensor and the array share memory (
float16andbfloat16are rounded into a new array instead).arangealso uses the default float dtype, so pass{ dtype: "int32" }when you want integers. reshape,transpose,squeezeandunsqueezereturn views that share memory when the layout allows it, andreshapecopies a non-contiguous input. On the CPU,slicereturns a copy, unlike NumPy slicing (on a device it returns a view).int64tensors are backed byBigInt64Array, so their elements arebigint.boolis stored asuint8.float16andbfloat16keep float32 host storage rounded to their precision.Complex,Complex64ArrayandComplex128Arrayexist as standalone types, because tensors cannot hold complex values yet.TensorandGradTensorshare one method surface (t.add(1).mul(2).sum(),t.T,t.matmul(w)), andAnyTensoris the unionTensor | GradTensor. See Autograd.
AnyTensor
typeUnion 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
typeRecursive type for nested number arrays.
Used to represent multi-dimensional data in JavaScript arrays.
type NestedArray = number | boolean | NestedArray[];SliceRange
typeA single index or a start/end/step range for tensor slicing.
type SliceRange = number | { readonly start?: number; readonly end?: number; readonly step?: number;};StringNestedArray
typeRecursive type for nested string arrays used in string tensor creation.
type StringNestedArray = string | StringNestedArray[];TensorCreateOptions
typeOptions for the tensor creation function.
readonly dtype?: DTypereadonly device?: Device
TensorOptions
typeOptions for tensor dtype and device configuration.
readonly dtype: DTypereadonly device: Device
Complex
An immutable complex number with real and imaginary parts.
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: numberreadonly im: numberstatic readonly ZERO: ComplexZero constant.
static readonly ONE: ComplexOne constant.
static readonly I: ComplexImaginary unit.
abs(): numberAbsolute value (modulus).
phase(): numberPhase angle (argument) in radians.
conj(): ComplexComplex conjugate.
add(other: Complex): ComplexAddition.
sub(other: Complex): ComplexSubtraction.
mul(other: Complex): ComplexMultiplication.
div(other: Complex): ComplexDivision using Smith's algorithm.
neg(): ComplexNegation.
exp(): ComplexComplex exponential.
log(): ComplexComplex natural logarithm (principal value).
sqrt(): ComplexComplex square root (principal value, branch cut along the negative real axis).
pow(n: Complex | number): ComplexComplex power.
equals(other: Complex, tol?: number): booleanCheck equality within an absolute tolerance on both parts.
toString(): stringString representation.
static fromPolar(r: number, theta: number): ComplexCreate 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.
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); // 2Members (19)
constructor(length: number)readonly length: numberNumber of complex elements.
readonly BYTES_PER_ELEMENT = 8Bytes per complex element (8 = 2 × 4).
readonly buffer: ArrayBufferreadonly byteOffset: numberreadonly byteLength: number[Symbol.toStringTag]: stringgetReal(index: number): numberGet the real part at
index.getImag(index: number): numberGet the imaginary part at
index.getComplex(index: number): ComplexGet the element at
indexas a Complex.setComplex(index: number, value: Complex): voidStore a complex value at
index.setRI(index: number, re: number, im: number): voidStore real and imaginary parts at
index.static fromComplexArray(values: readonly Complex[]): Complex64ArrayCreate from an array of Complex values.
static fromInterleaved(data: ArrayLike<number>): Complex64ArrayCreate from interleaved real/imaginary pairs
[re0, im0, re1, im1, ...].fill(value: Complex, start?: number, end?: number): thisFill the range
[start, end)with a complex value.slice(start?: number, end?: number): Complex64ArrayCopy of the range
[start, end).set(source: ArrayLike<number> | Complex64Array | Complex128Array, offset?: number): voidCopy 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.
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: numberNumber of complex elements.
readonly BYTES_PER_ELEMENT = 16Bytes per complex element (16 = 2 × 8).
readonly buffer: ArrayBufferreadonly byteOffset: numberreadonly byteLength: number[Symbol.toStringTag]: stringgetReal(index: number): numberGet the real part at
index.getImag(index: number): numberGet the imaginary part at
index.getComplex(index: number): ComplexGet the element at
indexas a Complex.setComplex(index: number, value: Complex): voidStore a complex value at
index.setRI(index: number, re: number, im: number): voidStore real and imaginary parts at
index.static fromComplexArray(values: readonly Complex[]): Complex128ArrayCreate from an array of Complex values.
static fromInterleaved(data: ArrayLike<number>): Complex128ArrayCreate from interleaved real/imaginary pairs
[re0, im0, re1, im1, ...].fill(value: Complex, start?: number, end?: number): thisFill the range
[start, end)with a complex value.slice(start?: number, end?: number): Complex128ArrayCopy of the range
[start, end).set(source: ArrayLike<number> | Complex64Array | Complex128Array, offset?: number): voidCopy 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.
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); // 2Members (18)
constructor(lengthOrData: number | ArrayLike<number> | ArrayBuffer, byteOffset?: number, length?: number)static readonly BYTES_PER_ELEMENT = 2Bytes per element (always 2).
readonly length: numberNumber of elements.
readonly BYTES_PER_ELEMENT = 2Bytes per element (always 2).
readonly buffer: ArrayBufferArrayBuffer backing the storage.
readonly byteOffset: numberByte offset into the buffer.
readonly byteLength: numberByte length of the storage.
[Symbol.toStringTag]: stringString tag.
static from(source: ArrayLike<number> | Iterable<number>): BFloat16ArrayCreate a BFloat16Array from an iterable of numbers.
static of(...values: number[]): BFloat16ArrayCreate a BFloat16Array with the given values.
at(index: number): number | undefinedGet the element at
index(negative counts from the end), orundefinedwhen out of range.set(source: ArrayLike<number>, offset?: number): voidCopy numbers from
sourceinto this array starting atoffset, rounding each to bfloat16.slice(start?: number, end?: number): BFloat16ArrayCreate a copy of a portion of the array.
subarray(begin?: number, end?: number): BFloat16ArrayCreate a view over a portion of the array that shares memory with it.
fill(value: number, start?: number, end?: number): thisFill the range
[start, end)with a value rounded to bfloat16.copyWithin(target: number, start: number, end?: number): thisCopy 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.
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); // 2Members (18)
constructor(lengthOrData: number | ArrayLike<number> | ArrayBuffer, byteOffset?: number, length?: number)static readonly BYTES_PER_ELEMENT = 2Bytes per element (always 2).
readonly length: numberNumber of elements.
readonly BYTES_PER_ELEMENT = 2Bytes per element (always 2).
readonly buffer: ArrayBufferArrayBuffer backing the storage.
readonly byteOffset: numberByte offset into the buffer.
readonly byteLength: numberByte length of the storage.
[Symbol.toStringTag]: stringString tag.
static from(source: ArrayLike<number> | Iterable<number>): Float16ArrayCreate a Float16Array from an iterable of numbers.
static of(...values: number[]): Float16ArrayCreate a Float16Array with the given values.
at(index: number): number | undefinedGet the element at
index(negative counts from the end), orundefinedwhen out of range.set(source: ArrayLike<number>, offset?: number): voidCopy numbers from
sourceinto this array starting atoffset, rounding each to float16.slice(start?: number, end?: number): Float16ArrayCreate a copy of a portion of the array.
subarray(begin?: number, end?: number): Float16ArrayCreate a view over a portion of the array that shares memory with it.
fill(value: number, start?: number, end?: number): thisFill the range
[start, end)with a value rounded to float16.copyWithin(target: number, start: number, end?: number): thisCopy 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).
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); // 2Members (105)
readonly shape: Sreadonly dtype: Dreadonly device: Devicereadonly strides: readonly number[]readonly offset: numberreadonly size: numberreadonly ndim: numberreadonly data: TensorData<D>Underlying host storage (TypedArray, or
string[]for string dtype).isDeviceTensor: booleantruewhen the tensor's storage lives in device memory (itsdatacannot be read synchronously).deviceBuffer: DeviceBuffer | nullThe device buffer backing this tensor, or
nullfor host tensors.T: TensorAxes reversed, as
transpose()with no argument (likenumpy.ndarray.T).requiresGrad: falseAlways
false: a plainTensordoes not track gradients.grad: nullAlways
null: a plainTensornever holds a gradient.dispose(): voidRelease 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): TensorElement-wise sum with a tensor or a number (functional form:
add).sub(other: number | Tensor): TensorElement-wise difference with a tensor or a number (functional form:
sub).mul(other: number | Tensor): TensorElement-wise product with a tensor or a number (functional form:
mul).div(other: number | Tensor): TensorElement-wise true division by a tensor or a number (functional form:
div).pow(exponent: number | Tensor): TensorElement-wise power (functional form:
pow).neg(): TensorElement-wise negation (functional form:
neg).abs(): TensorElement-wise absolute value (functional form:
abs).exp(): TensorElement-wise exponential (functional form:
exp).log(): TensorElement-wise natural logarithm (functional form:
log).sqrt(): TensorElement-wise square root (functional form:
sqrt).square(): TensorElement-wise square (functional form:
square).sin(): TensorElement-wise sine (functional form:
sin).cos(): TensorElement-wise cosine (functional form:
cos).tanh(): TensorElement-wise hyperbolic tangent (functional form:
tanh).sigmoid(): TensorElement-wise logistic sigmoid (functional form:
sigmoid).relu(): TensorElement-wise rectified linear unit (functional form:
relu).expm1(): TensorElement-wise
exp(x) - 1, accurate for smallx(functional form:expm1).log1p(): TensorElement-wise
log(1 + x), accurate for smallx(functional form:log1p).tan(): TensorElement-wise tangent (functional form:
tan).maximum(other: number | Tensor): TensorElement-wise larger of two tensors, or of a tensor and a number (functional form:
maximum).minimum(other: number | Tensor): TensorElement-wise smaller of two tensors, or of a tensor and a number (functional form:
minimum).leakyRelu(negativeSlope?: number): TensorLeaky ReLU (functional form:
leakyRelu).elu(alpha?: number): TensorExponential linear unit (functional form:
elu).selu(): TensorScaled exponential linear unit (functional form:
selu).gelu(options?: GeluApproximation | GeluOptions): TensorGaussian error linear unit (functional form:
gelu).softplus(): TensorSoftplus,
log(1 + exp(x))(functional form:softplus).mish(): TensorMish,
x * tanh(softplus(x))(functional form:mish).swish(): TensorSwish (SiLU),
x * sigmoid(x)(functional form:swish).logSigmoid(): TensorLog of the logistic function,
log(sigmoid(x))(functional form:logSigmoid).hardtanh(minVal?: number, maxVal?: number): TensorClamp to
[minVal, maxVal](functional form:hardtanh).tanhshrink(): Tensorx - tanh(x)(functional form:tanhshrink).softmax(axis?: Axis): TensorSoftmax along an axis (functional form:
softmax).logSoftmax(axis?: Axis): TensorLog-softmax along an axis (functional form:
logSoftmax).sum(axis?: Axis | readonly Axis[], keepdims?: boolean): TensorSum of elements over one axis, several axes, or all of them (functional form:
sum).mean(axis?: Axis | readonly Axis[], keepdims?: boolean): TensorMean of elements (functional form:
mean).max(axis?: Axis | readonly Axis[], keepdims?: boolean): TensorMaximum of elements (functional form:
max).min(axis?: Axis | readonly Axis[], keepdims?: boolean): TensorMinimum of elements (functional form:
min).prod(axis?: Axis | readonly Axis[], keepdims?: boolean): TensorProduct of elements (functional form:
prod).std(axis?: Axis | readonly Axis[], keepdims?: boolean, ddof?: number): TensorStandard deviation (functional form:
std).var(axis?: Axis | readonly Axis[], keepdims?: boolean, ddof?: number): TensorVariance (functional form:
variance).argmax(axis?: Axis, keepdims?: boolean): TensorIndex of the maximum (functional form:
argmax).argmin(axis?: Axis, keepdims?: boolean): TensorIndex of the minimum (functional form:
argmin).cumsum(axis?: Axis): TensorCumulative sum (functional form:
cumsum).matmul(other: Tensor): TensorMatrix product with another tensor (functional form:
matmul).dot(other: Tensor): TensorDot product (functional form:
dot).transpose(axes?: readonly number[]): TensorPermute the axes (functional form:
transpose).squeeze(axis?: Axis | readonly Axis[]): TensorRemove axes of size 1 (functional form:
squeeze).unsqueeze(axis: number): TensorInsert an axis of size 1 (functional form:
unsqueeze).gather(indices: Tensor, axis: Axis): TensorSelect entries along an axis with a 1-D index tensor (functional form:
gather).detach(): thisReturn the tensor itself.
backward(_grad?: Tensor): voidThrows, because a plain
Tensoris not part of a computation graph.clone(): TensorCopy of the tensor with its own contiguous storage (functional form:
clone).fill(value: number | bigint | boolean | string): thisSet every element to one value, in place, and return the tensor (like
torch.Tensor.fill_).clip(min?: number, max?: number): TensorLimit values to
[min, max](functional form:clip).eq(other: number | Tensor): TensorElement-wise equality, giving a
booltensor (functional form:equal).ne(other: number | Tensor): TensorElement-wise inequality (functional form:
notEqual).gt(other: number | Tensor): TensorElement-wise greater-than (functional form:
greater).ge(other: number | Tensor): TensorElement-wise greater-or-equal (functional form:
greaterEqual).lt(other: number | Tensor): TensorElement-wise less-than (functional form:
less).le(other: number | Tensor): TensorElement-wise less-or-equal (functional form:
lessEqual).isnan(): TensorElement-wise NaN test, giving a
booltensor (functional form:isnan).any(axis?: Axis | readonly Axis[], keepdims?: boolean): TensorTrue where any element is non-zero (functional form:
any).all(axis?: Axis | readonly Axis[], keepdims?: boolean): TensorTrue where all elements are non-zero (functional form:
all).round(decimals?: number): TensorRound half to even (functional form:
round).floor(): TensorRound down (functional form:
floor).ceil(): TensorRound up (functional form:
ceil).sort(axis?: Axis | undefined, descending?: boolean): TensorSorted copy along an axis (functional form:
sort).argsort(axis?: Axis | undefined, descending?: boolean): TensorIndices that would sort the tensor along an axis (functional form:
argsort).flip(axes?: Axis | readonly Axis[]): TensorReverse 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[]): TensorSlice this tensor along one or more axes.
at(...indices: number[]): ElementOf<D>Read a single element.
astype(dtype: DType): TensorReturn 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(): unknownConvert to nested JavaScript arrays (a bare scalar for 0-D tensors).
toString(maxElements?: number): stringReturn a human-readable string representation of this tensor.
roundToBFloat16
function roundToBFloat16(value: number): number;Round a number to the nearest representable bfloat16 value (ties to even).
Parameters
valuenumber
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
valuenumber
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
startnumber- Start of the interval, or the stop value when
stopis omitted stopoptionalnumber- End of the interval (exclusive)
stepoptionalnumber- Spacing between values (default: 1, must be non-zero)
optsoptionalTensorCreateOptions- dtype and device
Returns
Tensor
Throws
InvalidParameterErrorIfstepis zero or any argument is not finite
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
shapeShape- Shape of the tensor
optsoptionalTensorCreateOptions- 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
nnumber- Number of rows
moptionalnumber- Number of columns (default: n, making it square)
koptionalnumber- Index of the diagonal (default: 0, main diagonal; positive is above)
optsoptionalTensorCreateOptions- Tensor options
Returns
TensorTensor of shape (n, m)
Throws
InvalidParameterErrorIfkis not an integerDTypeErrorIf the dtype is string or complex
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
tTensor- 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
shapeShape- Shape of the tensor
valuenumber | string | boolean- Fill value
optsoptionalTensorCreateOptions- dtype (default: the configured default dtype) and device
Returns
Tensor
Throws
DTypeErrorIfvaluedoes not fit the dtype
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
tTensor- Input tensor (host tensor of any dtype, including string)
indicesTensor- 1D tensor of integer indices into
axis axisAxis- Axis along which to gather (negative counts from the end)
Returns
TensorGathered tensor (copy) with the dtype of t
Throws
DTypeErrorIfindicesis a string tensorInvalidParameterErrorIfindicesis not 1D or holds non-integersIndexErrorIf an index is outside[0, size of axis)
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
startnumber- Starting value of the sequence (non-zero, same sign as
stop) stopnumber- Final value of the sequence
numoptionalnumber- Number of samples (default: 50)
endpointoptionalboolean- If true, stop is the last sample (default: true)
optsoptionalTensorCreateOptions- Tensor options
Returns
TensorTensor of shape (num,)
Throws
InvalidParameterErrorIfstartorstopis zero, non-finite or of opposite sign, ornumis not a non-negative integer
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
startnumber- Starting value of the sequence
stopnumber- End value of the sequence
numoptionalnumber- Number of samples to generate (default: 50)
endpointoptionalboolean- If true, stop is the last sample. Otherwise, it is not included (default: true)
optsoptionalTensorCreateOptions- Tensor options (dtype, device)
Returns
TensorTensor of shape (num,)
Throws
InvalidParameterErrorIfnumis not a non-negative integer
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
startnumber- base^start is the starting value
stopnumber- base^stop is the final value
numoptionalnumber- Number of samples to generate (default: 50)
baseoptionalnumber- The base of the log space (default: 10)
endpointoptionalboolean- If true, stop is the last sample (default: true)
optsoptionalTensorCreateOptions- Tensor options
Returns
TensorTensor of shape (num,)
Throws
InvalidParameterErrorIfnumis not a non-negative integer
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
shapeShape- Shape of the tensor
optsoptionalTensorCreateOptions- dtype (default: the configured default dtype) and device
Returns
Tensor
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
shapeShape- Shape of the output tensor
optsoptionalTensorCreateOptions- Additional tensor options
Returns
Tensor
Throws
DTypeErrorIf the dtype is bool, string or complex
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
tTensor- Input tensor
rawShapeShape- 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,-1cannot be inferred, or the element count does not matchDataValidationErrorIf a dimension is negative (other than a single-1), fractional or not finite
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
tTensor- Input tensor
rangesSliceRange[]- One index or range per leading axis
Returns
TensorSliced tensor
Throws
ShapeErrorIf more ranges than dimensions are givenIndexErrorIf a single index is out of boundsInvalidParameterErrorIf a step is zero or a bound is not an integer
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
dataNestedArray | StringNestedArray | TypedArrayoptsoptionalTensorCreateOptions
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
tTensor- Input tensor
axesoptionalreadonly number[]- Permutation of axes. If undefined, reverses all axes
Returns
TensorTransposed tensor (view)
Throws
ShapeErrorIfaxesdoes not have one entry per dimensionInvalidParameterErrorIfaxescontains a non-integer, an out-of-range axis or a duplicate
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 permutedzeros
function zeros(shape: Shape, opts?: TensorCreateOptions): Tensor;Tensor of zeros.
With dtype: "string" every element is the empty string.
Parameters
shapeShape- Shape of the tensor
optsoptionalTensorCreateOptions- dtype (default: the configured default dtype) and device
Returns
Tensor
zeros([2, 3]); // 2x3 tensor of 0expandDims
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
tTensor- Input tensor
axisnumber- Position where new axis is placed (can be negative) Returns: Tensor with expanded dimensions (view, no copy)
Returns
Tensor
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
tTensor- Input tensor
axisoptionalAxis | 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 1InvalidParameterErrorIf an axis is out of range or listed twice
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
tTensor- Input tensor
axisnumber- Position where new axis is placed (can be negative) Returns: Tensor with expanded dimensions (view, no copy)
Returns
Tensor
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)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());Found a mistake? Open an issue.