deepbox/ndarray
Sparse, FFT & Advanced Ops
CSRMatrix, einsum, FFTs, convolution and window functions, NaN-aware reductions, unique, advanced indexing, and im2col helpers.
- Sparse
- FFT
- einsum
Overview
CSRMatrixstores float64 values in compressed sparse row form. Build one withCSRMatrix.fromDenseorCSRMatrix.fromCOO. It supportsadd,sub,scale,multiply,matvec,matmulwith a dense tensor,spmm,transposeandtoDense.deepbox/linalgcan solve sparse systems.- FFT functions return
{ real, imag }tensors, because tensors cannot hold complex values yet.ifftandirffttake the two parts as separate arguments.normis"backward"(default),"ortho"or"forward", as in NumPy, andrfftkeeps only the non-negative frequencies. einsumsupports explicit and implicit subscripts, any number of operands, repeated labels (diagonals and traces) and...broadcasting. It accumulates in float64. The result isfloat32when every operand isfloat32,int32when every operand isint32, andfloat64otherwise.convolveandcorrelatetake 1-D inputs, follow NumPy and returnfloat64. Thenan*reductions skip NaN.uniquereturns an object withvaluesand, depending on options,indices,inverseandcounts.dropoutMask,im2colandcol2imare low-level helpers used by thennlayers, and application code rarely needs them.
ConvolveMode
typeBoundary handling for convolve and correlate.
type ConvolveMode = "full" | "same" | "valid";CrossOptions
interfaceOptions of cross.
readonly axis?: AxisAxis that holds the three vector components (default: -1).
HistogramOptions
interfaceOptions of histogram.
readonly density?: booleanReturn the probability density instead of counts (the histogram integrates to 1).
readonly weights?: TensorWeight of each sample; must have the same shape as the input.
LikeOptions
interfaceOptions shared by the *_like creation functions.
readonly dtype?: DTypeResult dtype.
PadMode
typePadding modes accepted by pad.
- "constant": fill with a constant value - "reflect": mirror the tensor without repeating the edge value - "symmetric": mirror the tensor including the edge value - "replicate" (alias "edge"): repeat the edge value - "circular" (alias "wrap"): wrap around to the opposite side
type PadMode = "constant" | "reflect" | "symmetric" | "replicate" | "edge" | "circular" | "wrap";PadWidth
typePadding amounts accepted by pad.
type PadWidth = number | readonly [ number, number] | ReadonlyArray<readonly [ number, number]>;UniqueOptions
interfaceOptions of unique.
readonly returnIndex?: booleanAlso return the index of the first occurrence of each unique value (int32).
readonly returnInverse?: booleanAlso return the indices that rebuild the input from the unique values (int32).
readonly returnCounts?: booleanAlso return how many times each unique value occurs (int32).
readonly axis?: AxisFind unique sub-tensors along this axis instead of unique elements of the flattened input.
UniqueOutput
typeUniqueResult with the fields requested through the literal options made required.
type UniqueOutput<O extends UniqueOptions> = UniqueResult & (O extends { readonly returnIndex: true;} ? { indices: Tensor;} : unknown) & (O extends { readonly returnInverse: true;} ? { inverse: Tensor;} : unknown) & (O extends { readonly returnCounts: true;} ? { counts: Tensor;} : unknown);UniqueResult
interfaceResult of unique when called with an options object.
values: TensorSorted unique values (or sub-tensors), same dtype as the input.
indices?: TensorFirst-occurrence index of each unique value; present with
returnIndex.inverse?: TensorPosition of each input element (or sub-tensor) in
values; present withreturnInverse.counts?: TensorNumber of occurrences of each unique value; present with
returnCounts.
WindowOptions
typeOptions shared by the window functions.
readonly periodic?: booleanBuild the periodic window (length
nof ann + 1point symmetric window with the last point dropped) instead of the symmetric one.
FFTNorm
typeNormalization mode of an FFT, matching NumPy's norm argument.
- "backward" (default): the forward transform is unscaled and the inverse is scaled by 1/n. - "ortho": both directions are scaled by 1/sqrt(n) (unitary transform). - "forward": the forward transform is scaled by 1/n and the inverse is unscaled.
type FFTNorm = "backward" | "ortho" | "forward";FFTResult
interfaceResult of an FFT operation: real and imaginary parts as separate tensors.
real: Tensorimag: Tensor
CSRMatrixInit
typeInitialization data for constructing a CSRMatrix.
readonly data: Float64Arrayreadonly indices: Int32Arrayreadonly indptr: Int32Arrayreadonly shape: Shape
CSRMatrix
Compressed Sparse Row (CSR) matrix representation.
CSR format stores a sparse matrix using three arrays: - data: Non-zero values in row-major order - indices: Column indices of non-zero values - indptr: Row pointers (indptr[i] to indptr[i+1] gives the range of data/indices for row i)
This format is efficient for: - Row slicing - Matrix-vector products - Arithmetic operations
The constructor stores the arrays it is given without copying. Column indices within a row should be strictly increasing (canonical form, see CSRMatrix.hasCanonicalFormat); all methods also give the right result for unsorted rows or repeated column indices, treating repeated entries as a sum as SciPy does, but get and getCol are faster on canonical input. Results produced by the arithmetic methods are always canonical.
Only entries that are stored take part in matvec, matmul, multiply and spmm, so a NaN or Infinity in the dense operand does not propagate through a structural zero.
import { CSRMatrix } from 'deepbox/ndarray'; // Create a 3x3 sparse matrix with values at (0,0)=1, (1,2)=2, (2,1)=3const sparse = CSRMatrix.fromCOO({ rows: 3, cols: 3, rowIndices: new Int32Array([0, 1, 2]), colIndices: new Int32Array([0, 2, 1]), values: new Float64Array([1, 2, 3])}); // Convert to dense for operationsconst dense = sparse.toDense();Members (28)
constructor(init: CSRMatrixInit)readonly data: Float64Arrayreadonly indices: Int32Arrayreadonly indptr: Int32Arrayreadonly shape: Shapennz: numberNumber of stored entries (explicitly stored zeros included).
rows: numberNumber of rows in the matrix
cols: numberNumber of columns in the matrix
hasCanonicalFormat: booleanWhether column indices are strictly increasing within every row (sorted, no repeated entries).
toDense(): TensorConvert the sparse matrix to a dense Tensor.
static fromDense(dense: Tensor): CSRMatrixCreate a CSR matrix from a dense 2D tensor, storing every entry that is not exactly zero.
canonicalize(): CSRMatrixReturn an equivalent matrix in canonical form: columns sorted within each row and repeated entries summed.
add(other: CSRMatrix): CSRMatrixAdd two sparse matrices element-wise.
sub(other: CSRMatrix): CSRMatrixSubtract another sparse matrix element-wise.
scale(scalar: number): CSRMatrixMultiply all elements by a scalar value.
multiply(other: CSRMatrix): CSRMatrixElement-wise multiplication (Hadamard product) with another sparse matrix.
matvec(vector: Tensor | Float64Array): TensorMatrix multiplication with a dense vector.
matmul(dense: Tensor): TensorMatrix multiplication with a dense matrix.
transpose(): CSRMatrixTranspose the sparse matrix.
get(row: number, col: number): numberGet a specific element from the matrix.
copy(): CSRMatrixCreate a copy of this matrix.
spmm(other: CSRMatrix): CSRMatrixSparse-sparse matrix multiplication.
sliceRows(start: number, end: number): CSRMatrixExtract a contiguous range of rows as a new CSRMatrix.
getRow(row: number): Float64ArrayExtract a single row as a 1D dense Float64Array.
getCol(col: number): Float64ArrayExtract a single column as a 1D dense Float64Array.
static eye(n: number): CSRMatrixCreate a sparse identity matrix.
static diag(values: Float64Array): CSRMatrixCreate a sparse diagonal matrix from values.
static fromCOO(args: { readonly rows: number; readonly cols: number; readonly rowIndices: Int32Array; readonly colIndices: Int32Array; readonly values: Float64Array; readonly sort?: boolean; }): CSRMatrixCreate a sparse matrix from COO (Coordinate List) format.
col2im
function col2im(cols: Tensor, inputShape: Shape, kernelSize: [ number, number ], stride: [ number, number ], padding: [ number, number ]): Tensor;Column to Image operation (col2im).
Rearranges columns back into image blocks, summing values where windows overlap. This is the adjoint of im2col and is used for gradients. The output keeps the dtype of cols.
Parameters
colsTensor- Column tensor of shape (batch, outH * outW, channels * kH * kW)
inputShapeShape- Shape of the original image (batch, channels, height, width)
kernelSize[ number, number ]- Size of the kernel [kH, kW]
stride[ number, number ]- Stride [sH, sW]
padding[ number, number ]- Padding [pH, pW]
Returns
TensorGradient tensor of shape inputShape
Throws
ShapeErrorIfcolsis not 3-D,inputShapedoes not have 4 entries, or the column shape does not match the geometryDTypeErrorIfcolshas string dtypeInvalidParameterErrorIf a parameter is invalid or the kernel does not fit the image
im2col
function im2col(input: Tensor, kernelSize: [ number, number ], stride: [ number, number ], padding: [ number, number ]): Tensor;Image to Column operation (im2col).
Rearranges image blocks into columns. Positions that fall in the padding are zero. The output keeps the input dtype.
Parameters
inputTensor- Input tensor of shape (batch, channels, height, width)
kernelSize[ number, number ]- Size of the kernel [kH, kW]
stride[ number, number ]- Stride [sH, sW]
padding[ number, number ]- Padding [pH, pW]
Returns
TensorOutput tensor of shape (batch, outH * outW, channels * kH * kW)
Throws
ShapeErrorIfinputis not 4-DDTypeErrorIfinputhas string dtypeInvalidParameterErrorIf a parameter is invalid or the kernel does not fit the input
const x = tensor([[[[1, 2, 3], [4, 5, 6], [7, 8, 9]]]]); // (1, 1, 3, 3)im2col(x, [2, 2], [1, 1], [0, 0]).shape; // [1, 4, 4]einsum
function einsum(subscripts: string, ...tensors: Tensor[]): Tensor;Einstein summation convention.
Details
Supports explicit ("ij,jk->ik") and implicit ("ij,jk") subscripts, any number of operands, repeated labels within one operand (diagonals and traces), and ... for broadcast dimensions. Dimensions of size 1 broadcast against larger dimensions that share their label, as in NumPy.
Common patterns: - "ij,jk->ik" (matrix multiply) - "ii->i" (diagonal) - "ii->" (trace) - "ij->ji" (transpose) - "i,i->" (dot product) - "ij,j->i" (matrix-vector multiply) - "...ij,...jk->...ik" (batched matrix multiply)
In implicit mode the output holds the labels that appear exactly once, in alphabetical order (uppercase before lowercase), preceded by any ellipsis dimensions.
The result is float32 when every operand is float32, int32 when every operand is int32, and float64 otherwise. Products are accumulated in float64. int64 operands are converted to doubles (exact up to 2^53).
Parameters
subscriptsstring- Subscript string in Einstein notation
tensorsTensor[]- Input tensors
Returns
TensorResult tensor
Throws
InvalidParameterErrorIf the subscripts are malformed or do not match the operand countShapeErrorIf an operand's rank does not match its subscript or label sizes conflictDTypeErrorIf an operand has string dtype
const a = tensor([[1, 2], [3, 4]]);einsum("ij,jk->ik", a, a); // [[7, 10], [15, 22]]einsum("ii->", a); // 5argwhere
function argwhere(t: Tensor): Tensor;Indices of the nonzero elements as one int32 matrix (like np.argwhere). Row i holds the coordinates of the i-th nonzero element in row-major order. NaN counts as nonzero. A 0-d tensor gives shape [1, 0] when it is nonzero and [0, 0] otherwise.
Parameters
tTensor- Input tensor
Returns
Tensorint32 tensor of shape [count, t.ndim]
Throws
DTypeErrorIfthas string dtype
argwhere(tensor([[0, 2], [3, 0]])); // [[0, 1], [1, 0]]atleast1d
function atleast1d(t: Tensor): Tensor;Ensure the input is at least 1-D. Scalars become shape [1]; higher-dimensional tensors pass through unchanged (the same tensor is returned).
Parameters
tTensor
Returns
Tensor
atleast2d
function atleast2d(t: Tensor): Tensor;Ensure the input is at least 2-D. Scalars become shape [1,1]; 1-D tensors become shape [1,n]; others pass through unchanged (the same tensor is returned).
Parameters
tTensor
Returns
Tensor
bartlettWindow
function bartlettWindow(n: number, options?: WindowOptions): Tensor;Bartlett (triangular) window with zero end points.
Matches np.bartlett(n).
Parameters
nnumber- Number of points; a positive integer
optionsoptionalWindowOptions{ periodic: true }for the periodic form
Returns
Tensorfloat64 tensor of shape [n]
Throws
InvalidParameterErrorIfnis not a positive integer
bartlettWindow(5); // [0, 0.5, 1, 0.5, 0]bincount
function bincount(t: Tensor, minlength?: number, weights?: Tensor): Tensor;Count the occurrences of each value in a tensor of non-negative integers (flattened). The result is a float64 tensor of length max(max(t) + 1, minlength), or the sum of weights per value when given.
Parameters
tTensor- Input tensor of non-negative integers
minlengthoptionalnumber- Minimum output length (default: 0)
weightsoptionalTensor- Optional weight per element, same number of elements as
t
Returns
TensorTensor of counts
Throws
InvalidParameterErrorIfthas a negative or non-integer value, orminlengthis invalidShapeErrorIfweightsdoes not have the same size ast
blackmanWindow
function blackmanWindow(n: number, options?: WindowOptions): Tensor;Blackman window.
w[i] = 0.42 - 0.5 * cos(2 * pi * i / (n - 1)) + 0.08 * cos(4 * pi * i / (n - 1)). Matches np.blackman(n).
Parameters
nnumber- Number of points; a positive integer
optionsoptionalWindowOptions{ periodic: true }for the periodic form
Returns
Tensorfloat64 tensor of shape [n]
Throws
InvalidParameterErrorIfnis not a positive integer
blackmanWindow(5); // [-1.4e-17, 0.34, 1, 0.34, -1.4e-17]booleanIndex
function booleanIndex(t: Tensor, mask: Tensor): Tensor;Select elements from a tensor using a boolean mask. Returns a 1-D tensor of elements where the mask is true (nonzero, NaN included).
The mask is matched to t element by element in row-major order, so it must have the same number of elements as t (normally the same shape).
Parameters
tTensor- Input tensor
maskTensor- Boolean mask tensor (same shape as t)
Returns
Tensor1-D tensor of selected elements, in row-major order
Throws
ShapeErrorIftandmaskhave a different number of elements
const a = tensor([1, 2, 3, 4, 5]);const m = tensor([1, 0, 1, 0, 1], { dtype: 'bool' });booleanIndex(a, m); // [1, 3, 5]broadcastTo
function broadcastTo(t: Tensor, shape: Shape): Tensor;Broadcast a tensor to a target shape.
The result is a zero-copy view: broadcast axes get stride 0, so all elements along them alias the same buffer entry (like NumPy's broadcast_to). Call clone to get independent memory.
Parameters
tTensor- Input tensor
shapeShape- Target shape
Returns
TensorBroadcast view of the tensor
Throws
ShapeErrorIf the target has fewer dimensions or an axis cannot be broadcastInvalidParameterErrorIf the target shape has a negative or non-integer entry
clone
function clone(t: Tensor): Tensor;Create a deep copy of a tensor with its own data buffer.
The returned tensor shares no data with the original and is always contiguous with offset 0, even when the input is a strided view.
Parameters
tTensor- Input tensor
Returns
TensorDeep copy of the tensor
const a = tensor([1, 2, 3]);const b = clone(a);contiguous
function contiguous(t: Tensor): Tensor;Return a contiguous tensor. A tensor that is already contiguous and starts at offset 0 is returned as is (no copy); any other tensor is materialized into a new contiguous copy.
Parameters
tTensor- Input tensor
Returns
TensorContiguous tensor
convolve
function convolve(a: Tensor, v: Tensor, mode?: ConvolveMode): Tensor;Discrete linear convolution of two 1-D tensors.
Matches np.convolve(a, v, mode). The result is a float64 tensor.
- "full" (default): every overlap, length a.size + v.size - 1 - "same": length max(a.size, v.size), centered with respect to "full" - "valid": only complete overlaps, length max(a.size, v.size) - min(a.size, v.size) + 1
Parameters
aTensor- First 1-D input
vTensor- Second 1-D input
modeoptionalConvolveMode- Output size, default
"full"
Returns
Tensorfloat64 tensor
Throws
InvalidParameterErrorIf an input is not a non-empty 1-D numeric tensor ormodeis unknown
convolve(tensor([1, 2, 3]), tensor([0, 1, 0.5])); // [0, 1, 2.5, 4, 1.5]copy
function copy(t: Tensor): Tensor;Create an explicit deep copy of a tensor (alias for clone).
Parameters
tTensor- Input tensor
Returns
TensorDeep copy of the tensor
correlate
function correlate(a: Tensor, v: Tensor, mode?: ConvolveMode): Tensor;Cross-correlation of two 1-D tensors.
Matches np.correlate(a, v, mode): c[k] = sum_n a[n + k] * v[n], which is convolve(a, reversed(v), mode). The result is a float64 tensor.
Parameters
aTensor- First 1-D input
vTensor- Second 1-D input
modeoptionalConvolveMode- Output size, default
"full"(see convolve)
Returns
Tensorfloat64 tensor
Throws
InvalidParameterErrorIf an input is not a non-empty 1-D numeric tensor ormodeis unknown
correlate(tensor([1, 2, 3]), tensor([0, 1, 0.5])); // [0.5, 2, 3.5, 3, 0]countNonzero
function countNonzero(t: Tensor, axis?: Axis | readonly Axis[], keepdims?: boolean): Tensor;Count the nonzero elements (like np.count_nonzero). NaN counts as nonzero.
Parameters
tTensor- Input tensor
axisoptionalAxis | readonly Axis[]- Axis or axes to count along (default: all axes)
keepdimsoptionalboolean- Keep the counted axes as size-1 dimensions
Returns
Tensorint32 tensor of counts; 0-d when every axis is counted without keepdims
Throws
DTypeErrorIfthas string dtypeInvalidParameterErrorIf an axis is out of range or repeated
const a = tensor([[1, 0, 3], [0, 0, 5]]);countNonzero(a); // 3countNonzero(a, 0); // [1, 0, 2]cross
function cross(a: Tensor, b: Tensor, options?: CrossOptions | Axis): Tensor;Compute the cross product of 3-element vectors (like np.cross).
Details
The vectors lie along axis (default: the last axis), which must have length 3 in both inputs. All other axes are batch axes that broadcast against each other under NumPy rules, so [N, 3] with [3] or [N, 1, 3] with [M, 3] work. The result has the broadcast batch shape and the vectors along the same axis position.
The result dtype is the promoted dtype of the inputs: float32 inputs give float32, float64 gives float64 (float16 with bfloat16 gives float32). Integer inputs give integer results (uint8, int32, or int64) that wrap on overflow, as in NumPy; bool counts as int32.
Parameters
aTensor- First tensor with
a.shape[axis] === 3 bTensor- Second tensor with
b.shape[axis] === 3 optionsoptionalCrossOptions | Axis{ axis }, or the axis number itself (default: -1)
Returns
TensorCross product a x b
Throws
ShapeErrorIf an input is 0-d, the cross axis does not have length 3, or the batch axes do not broadcastInvalidParameterErrorIfaxisis out of rangeDTypeErrorIf an input has string dtype
cross(tensor([1, 0, 0]), tensor([0, 1, 0])); // [0, 0, 1] // Batched: every row of `a` crossed with the same vector.cross(tensor([[1, 0, 0], [0, 1, 0]]), tensor([0, 0, 1])); // [[0, -1, 0], [1, 0, 0]] // Vectors stored along axis 0.cross(tensor([[1, 0], [0, 1], [0, 0]]), tensor([[0, 0], [0, 0], [1, 1]]), { axis: 0 });detach
function detach(t: Tensor): Tensor;Create a copy of a tensor detached from any computation graph. Equivalent to clone: plain tensors carry no graph.
Parameters
tTensor- Input tensor
Returns
TensorDetached copy of the tensor
diag
function diag(t: Tensor, k?: number): Tensor;Extract a diagonal or construct a diagonal matrix.
- If input is 1-D, returns a 2-D square matrix with the input on the k-th diagonal. - If input is 2-D, returns a copy of the k-th diagonal as a 1-D tensor.
Parameters
tTensor- Input tensor (1-D or 2-D)
koptionalnumber- Diagonal offset (0 = main, positive = above, negative = below)
Returns
TensorDiagonal tensor
Throws
ShapeErrorIf the input is not 1-D or 2-DInvalidParameterErrorIfkis not an integer
diag(tensor([1, 2, 3])); // [[1, 0, 0], [0, 2, 0], [0, 0, 3]]diag(tensor([[1, 2], [3, 4]])); // [1, 4]diagonal
function diagonal(t: Tensor, k?: number): Tensor;Extract the k-th diagonal from a 2-D tensor. The result is a copy.
Parameters
tTensor- Input 2-D tensor
koptionalnumber- Diagonal offset (0 = main, positive = above, negative = below)
Returns
Tensor1-D tensor of diagonal elements (empty if |k| exceeds the matrix size)
Throws
ShapeErrorIf the input is not 2-DInvalidParameterErrorIfkis not an integer
emptyLike
function emptyLike(t: Tensor, options?: LikeOptions): Tensor;Create a zero-filled tensor with the same shape as the input tensor. JavaScript typed arrays are always zero-initialized, so unlike NumPy's empty_like the contents are well defined.
Parameters
tTensor- Reference tensor
optionsoptionalLikeOptionsdtypeoverrides the result dtype (default: the dtype oft)
Returns
TensorNew tensor (zero-initialized)
fancyIndex
function fancyIndex(t: Tensor, indices: Tensor, axis?: Axis): Tensor;Select elements from a tensor using integer index arrays (like np.take).
The result has the shape of t with axis replaced by the shape of indices. A 0-d indices tensor selects a single entry and keeps the axis with size 1. Negative indices count from the end of the axis.
Parameters
tTensor- Input tensor
indicesTensor- Integer-valued index tensor (bool tensors are rejected; use booleanIndex)
axisoptionalAxis- Axis along which to index (default: 0)
Returns
TensorTensor with selected elements, same dtype as t
Throws
IndexErrorIf an index is out of bounds foraxisInvalidParameterErrorIf an index is not an integerDTypeErrorIfindiceshas bool dtype
fft
function fft(t: Tensor, n?: number, axis?: number, norm?: FFTNorm): FFTResult;Compute the one-dimensional discrete Fourier transform along one axis.
Parameters
tTensor- Real-valued input tensor.
noptionalnumber- Length of the transformed axis. A shorter input is zero-padded and a longer one is cropped. Default: the input length along
axis. axisoptionalnumber- Axis to transform (negative values count from the end). Default: -1.
normoptionalFFTNorm- Normalization mode. Default:
"backward".
Returns
FFTResultObject with real and imag tensors; the transformed axis has length n.
Throws
DTypeErrorIfthas string dtype.ShapeErrorIftis 0-D.InvalidParameterErrorIfnis not a positive integer oraxisis invalid.
import { fft, tensor } from "deepbox/ndarray"; const { real, imag } = fft(tensor([1, 0, 0, 0]));// real = [1, 1, 1, 1], imag = [0, 0, 0, 0]fft2
function fft2(t: Tensor, axes?: readonly [ number, number ], norm?: FFTNorm): FFTResult;Compute the 2-dimensional discrete Fourier transform.
Parameters
tTensor- Real-valued input with at least 2 dimensions.
axesoptionalreadonly [ number, number ]- The two axes to transform. Default: the last two,
[-2, -1]. normoptionalFFTNorm- Normalization mode. Default:
"backward".
Returns
FFTResultObject with real and imag tensors of the same shape as t.
const { real, imag } = fft2(tensor([[1, 0], [0, 0]]));// real = [[1, 1], [1, 1]], imag = zerosfftfreq
function fftfreq(n: number, d?: number): Tensor;Sample frequencies of an n-point FFT: [0, 1, ..., ceil(n/2) - 1, -floor(n/2), ..., -1] / (n * d).
Parameters
nnumber- Window length (positive integer).
doptionalnumber- Sample spacing (non-zero). Default: 1.
Returns
Tensor1-D float64 tensor of length n.
fftfreq(4); // [0, 0.25, -0.5, -0.25]fftn
function fftn(t: Tensor, axes?: number[], norm?: FFTNorm): FFTResult;Compute the n-dimensional discrete Fourier transform.
The 1-D transform is applied along each listed axis in turn. If axes is omitted, every axis is transformed.
Parameters
tTensor- Real-valued input tensor.
axesoptionalnumber[]- Axes to transform (negative values count from the end). Default: all axes.
normoptionalFFTNorm- Normalization mode. Default:
"backward".
Returns
FFTResultObject with real and imag tensors of the same shape as t.
const { real } = fftn(tensor([[1, 0], [0, 0]]));fftshift
function fftshift(t: Tensor, axes?: number[]): Tensor;Shift the zero-frequency component to the center of the spectrum.
Parameters
tTensor- Input tensor (for example one half of an fft result).
axesoptionalnumber[]- Axes to shift. Default: all axes.
Returns
TensorShifted copy of t.
fftshift(fftfreq(4)); // [-0.5, -0.25, 0, 0.25]flip
function flip(t: Tensor, axes?: Axis | readonly Axis[]): Tensor;Reverse the order of elements along the given axes. The result is a copy.
Parameters
tTensor- Input tensor
axesoptionalAxis | readonly Axis[]- Axis or axes along which to flip. If undefined, flip all axes.
Returns
TensorFlipped tensor
Throws
InvalidParameterErrorIf an axis is out of range or listed twice
flip(tensor([1, 2, 3])); // [3, 2, 1]flip(tensor([[1, 2], [3, 4]]), [1]); // [[2, 1], [4, 3]]flipLr
function flipLr(t: Tensor): Tensor;Flip a tensor left-right (reverse the order of columns, axis 1).
Parameters
tTensor- Input tensor with at least 2 dimensions
Returns
TensorHorizontally flipped tensor
Throws
ShapeErrorIf the input has fewer than 2 dimensions
flipUd
function flipUd(t: Tensor): Tensor;Flip a tensor up-down (reverse the order of rows, axis 0).
Parameters
tTensor- Input tensor with at least 1 dimension
Returns
TensorVertically flipped tensor
Throws
ShapeErrorIf the input is a scalar
fullLike
function fullLike(t: Tensor, fillValue: number | bigint, options?: LikeOptions): Tensor;Create a tensor filled with a specified value, matching the shape of the input.
The value is converted to the result dtype: bool stores 1 for any non-zero value (NaN included), integer dtypes truncate toward zero and reject NaN and infinities, and int64 stores a BigInt.
Parameters
tTensor- Reference tensor
fillValuenumber | bigint- Value to fill the tensor with
optionsoptionalLikeOptionsdtypeoverrides the result dtype (default: the dtype oft)
Returns
TensorNew tensor filled with the specified value
Throws
DTypeErrorIf the resulting dtype is stringInvalidParameterErrorIf a non-finite value is stored in an integer dtype
const a = tensor([[1, 2], [3, 4]]);const f = fullLike(a, 7); // [[7, 7], [7, 7]]hammingWindow
function hammingWindow(n: number, options?: WindowOptions): Tensor;Hamming window.
w[i] = 0.54 - 0.46 * cos(2 * pi * i / (n - 1)). Matches np.hamming(n).
Parameters
nnumber- Number of points; a positive integer
optionsoptionalWindowOptions{ periodic: true }for the periodic form
Returns
Tensorfloat64 tensor of shape [n]
Throws
InvalidParameterErrorIfnis not a positive integer
hammingWindow(5); // [0.08, 0.54, 1, 0.54, 0.08]hannWindow
function hannWindow(n: number, options?: WindowOptions): Tensor;Hann window (raised cosine).
w[i] = 0.5 - 0.5 * cos(2 * pi * i / (n - 1)). Matches np.hanning(n).
Parameters
nnumber- Number of points; a positive integer
optionsoptionalWindowOptions{ periodic: true }for the periodic form
Returns
Tensorfloat64 tensor of shape [n]
Throws
InvalidParameterErrorIfnis not a positive integer
hannWindow(5); // [0, 0.5, 1, 0.5, 0]histogram
function histogram(t: Tensor, bins?: number | readonly number[], range?: readonly [ number, number ], options?: HistogramOptions): { counts: Tensor; binEdges: Tensor; };Compute the histogram of a tensor (flattened).
Bins are half-open [left, right) except the last one, which also includes its right edge. NaN samples and samples outside the range are ignored. When no range is given the bins span the data minimum to maximum (0 to 1 for empty data); a range with equal ends is widened by 0.5 on each side.
Parameters
tTensor- Input tensor
binsoptionalnumber | readonly number[]- Number of equal-width bins (default: 10), or a non-decreasing list of bin edges
rangeoptionalreadonly [ number, number ][min, max]range for equal-width bins (ignored whenbinsis a list of edges)optionsoptionalHistogramOptionsdensityandweights
Returns
{ counts: Tensor; binEdges: Tensor; }Object with float64 counts (or densities) and binEdges tensors
Throws
InvalidParameterErrorIfbinsorrangeis invalid, or the data range is not finiteShapeErrorIfweightsdoes not match the shape oft
const { counts, binEdges } = histogram(tensor([1, 2, 2, 3, 10]), 3, [0, 12]);// counts: [4, 0, 1], binEdges: [0, 4, 8, 12]ifft
function ifft(real: Tensor, imag: Tensor, n?: number, axis?: number, norm?: FFTNorm): FFTResult;Compute the one-dimensional inverse discrete Fourier transform along one axis.
Parameters
realTensor- Real part of the input spectrum.
imagTensor- Imaginary part of the input spectrum (same shape as
real). noptionalnumber- Length of the transformed axis. Default: the input length along
axis. axisoptionalnumber- Axis to transform. Default: -1.
normoptionalFFTNorm- Normalization mode. Default:
"backward"(the inverse is scaled by1/n).
Returns
FFTResultObject with real and imag tensors.
Throws
DTypeErrorIf an input has string dtype.ShapeErrorIf an input is 0-D or the two parts differ in shape.
const spectrum = fft(tensor([1, 2, 3, 4]));const { real } = ifft(spectrum.real, spectrum.imag);// real is approximately [1, 2, 3, 4]ifft2
function ifft2(real: Tensor, imag: Tensor, axes?: readonly [ number, number ], norm?: FFTNorm): FFTResult;Compute the 2-dimensional inverse discrete Fourier transform.
Parameters
realTensor- Real part of the 2-D spectrum (at least 2 dimensions).
imagTensor- Imaginary part of the 2-D spectrum (same shape as
real). axesoptionalreadonly [ number, number ]- The two axes to transform. Default:
[-2, -1]. normoptionalFFTNorm- Normalization mode. Default:
"backward".
Returns
FFTResultObject with real and imag tensors of the same shape as the input.
ifftn
function ifftn(real: Tensor, imag: Tensor, axes?: number[], norm?: FFTNorm): FFTResult;Compute the n-dimensional inverse discrete Fourier transform.
Parameters
realTensor- Real part of the n-D spectrum.
imagTensor- Imaginary part of the n-D spectrum (same shape as
real). axesoptionalnumber[]- Axes to transform. Default: all axes.
normoptionalFFTNorm- Normalization mode. Default:
"backward".
Returns
FFTResultObject with real and imag tensors of the same shape as the input.
ifftshift
function ifftshift(t: Tensor, axes?: number[]): Tensor;Inverse of fftshift.
Parameters
tTensor- Input tensor.
axesoptionalnumber[]- Axes to shift. Default: all axes.
Returns
TensorShifted copy of t.
indexSelect
function indexSelect(input: Tensor, dim: Axis, index: Tensor): Tensor;Select elements along a dimension using an index tensor.
Returns a new tensor that indexes the input tensor along dimension dim using the entries in index (a 1-D integer tensor). The result keeps the dtype of input. Negative indices are not accepted.
Equivalent to PyTorch's torch.index_select(input, dim, index).
Parameters
inputTensor- The input tensor
dimAxis- The dimension to index along
indexTensor- 1-D tensor of indices to select
Returns
TensorA new tensor with the selected elements
Throws
ShapeErrorIfindexis not 1-DIndexErrorIf an index is outside[0, size)fordimInvalidParameterErrorIfdimis out of range or an index is not an integer
const x = tensor([[1, 2, 3], [4, 5, 6]]);const idx = tensor([0, 2], { dtype: 'int32' });const result = indexSelect(x, 1, idx); // [[1, 3], [4, 6]]irfft
function irfft(real: Tensor, imag: Tensor, n?: number, axis?: number, norm?: FFTNorm): FFTResult;Compute the inverse of rfft: a real signal from a one-sided spectrum.
The imaginary parts of the DC term and, for even n, the Nyquist term are ignored, as in NumPy. The returned imag tensor is all zeros; it is kept so the result has the same { real, imag } form as the other transforms.
Parameters
realTensor- Real part of the one-sided spectrum (length
floor(n/2) + 1alongaxis). imagTensor- Imaginary part of the one-sided spectrum (same shape as
real). noptionalnumber- Length of the output axis. Default:
2 * (m - 1)for an input lengthm. axisoptionalnumber- Axis to transform. Default: -1.
normoptionalFFTNorm- Normalization mode. Default:
"backward".
Returns
FFTResultObject with real (the signal) and a zero imag tensor of shape [..., n].
const { real, imag } = rfft(tensor([1, 2, 3, 4]));irfft(real, imag).real; // [1, 2, 3, 4]isin
function isin(a: Tensor, values: Tensor | readonly number[] | readonly string[], invert?: boolean): Tensor;Test whether each element of a is in values.
Returns a boolean tensor of the same shape as a. NaN is never a member (NaN never equals NaN, as in NumPy). String tensors can be tested against a string tensor or a list of strings; int64 values are compared exactly.
Parameters
aTensor- Input tensor
valuesTensor | readonly number[] | readonly string[]- Values to test against (a tensor or an array)
invertoptionalboolean- If true, return the negation (
anot invalues)
Returns
TensorBoolean tensor with the shape of a
Throws
DTypeErrorIf string and numeric inputs are mixed
isin(tensor([1, 2, 3, 4]), [2, 4]); // [0, 1, 0, 1]kaiserWindow
function kaiserWindow(n: number, beta?: number, options?: WindowOptions): Tensor;Kaiser window.
w[i] = I0(beta * sqrt(1 - r^2)) / I0(beta) with r = 2 * i / (n - 1) - 1, where I0 is the modified Bessel function of order zero. Matches np.kaiser(n, beta). Larger beta gives a narrower main lobe and lower side lobes; beta = 0 is the rectangular window.
Parameters
nnumber- Number of points; a positive integer
betaoptionalnumber- Shape parameter; a finite number (default 12)
optionsoptionalWindowOptions{ periodic: true }for the periodic form
Returns
Tensorfloat64 tensor of shape [n]
Throws
InvalidParameterErrorIfnis not a positive integer orbetais not finite
kaiserWindow(8, 5); // [0.0367, 0.2707, 0.6517, 0.9552, 0.9552, 0.6517, 0.2707, 0.0367]meshgrid
function meshgrid(...args: [ ...Tensor[], ...[ { readonly indexing?: "xy" | "ij"; } ] ] | Tensor[]): Tensor[];Return coordinate matrices from coordinate vectors.
Details
Make N-D coordinate arrays for vectorized evaluations of N-D scalar/vector fields over N-D grids, given one-dimensional coordinate arrays x1, x2, ..., xn. Each output keeps the dtype of its input vector.
Supports "xy" (default, Cartesian) and "ij" (matrix) indexing. With "xy" the first two output axes are swapped: the outputs have shape [len(x2), len(x1), len(x3), ...].
Parameters
args[ ...Tensor[], ...[ { readonly indexing?: "xy" | "ij"; } ] ] | Tensor[]- 1-D coordinate tensors, optionally followed by
{ indexing }
Returns
Tensor[]Array of N-D tensors, one for each input
Throws
ShapeErrorIf an input is not 1-DInvalidParameterErrorIfindexingis neither"xy"nor"ij"
const x = tensor([1, 2, 3]);const y = tensor([4, 5]);const [X, Y] = meshgrid(x, y);// X shape: [2, 3], Y shape: [2, 3]moveaxis
function moveaxis(t: Tensor, source: number | readonly number[], destination: number | readonly number[]): Tensor;Move axes of a tensor to new positions. Other axes keep their relative order. The result is a zero-copy view that shares the input's buffer.
Parameters
tTensor- Input tensor
sourcenumber | readonly number[]- Original positions of axes to move
destinationnumber | readonly number[]- Destination positions for each axis
Returns
TensorTensor view with moved axes
Throws
InvalidParameterErrorIf the lists differ in length, an axis is out of range, or an axis is repeated insourceor indestination
moveaxis(zeros([2, 3, 4]), 0, -1).shape; // [3, 4, 2]nanmax
function nanmax(t: Tensor, axis?: Axis | readonly Axis[], keepdims?: boolean): Tensor;Maximum of elements, ignoring NaN. A slice without non-NaN values (including an empty slice) gives NaN. The result is always float64.
Parameters
tTensor- Input tensor
axisoptionalAxis | readonly Axis[]- Axis or axes to reduce (default: all)
keepdimsoptionalboolean- Keep reduced axes as size-1 dimensions
Returns
Tensorfloat64 tensor of maxima
Throws
DTypeErrorIfthas string dtypeInvalidParameterErrorIf an axis is out of range or repeated
nanmean
function nanmean(t: Tensor, axis?: Axis | readonly Axis[], keepdims?: boolean): Tensor;Mean of elements, ignoring NaN. A slice without non-NaN values gives NaN. The result is always float64.
Parameters
tTensor- Input tensor
axisoptionalAxis | readonly Axis[]- Axis or axes to reduce (default: all)
keepdimsoptionalboolean- Keep reduced axes as size-1 dimensions
Returns
Tensorfloat64 tensor of means
Throws
DTypeErrorIfthas string dtypeInvalidParameterErrorIf an axis is out of range or repeated
nanmin
function nanmin(t: Tensor, axis?: Axis | readonly Axis[], keepdims?: boolean): Tensor;Minimum of elements, ignoring NaN. A slice without non-NaN values (including an empty slice) gives NaN. The result is always float64.
Parameters
tTensor- Input tensor
axisoptionalAxis | readonly Axis[]- Axis or axes to reduce (default: all)
keepdimsoptionalboolean- Keep reduced axes as size-1 dimensions
Returns
Tensorfloat64 tensor of minima
Throws
DTypeErrorIfthas string dtypeInvalidParameterErrorIf an axis is out of range or repeated
nanstd
function nanstd(t: Tensor, axis?: Axis | readonly Axis[], keepdims?: boolean, ddof?: number): Tensor;Standard deviation of elements, ignoring NaN. Computed in two passes, so it does not suffer from the cancellation of E[x^2] - mean^2. A slice with count - ddof <= 0 non-NaN values gives NaN. The result is always float64.
Parameters
tTensor- Input tensor
axisoptionalAxis | readonly Axis[]- Axis or axes to reduce (default: all)
keepdimsoptionalboolean- Keep reduced axes as size-1 dimensions
ddofoptionalnumber- Delta degrees of freedom; the divisor is
count - ddof(default: 0, population standard deviation, like NumPy)
Returns
Tensorfloat64 tensor of standard deviations
Throws
DTypeErrorIfthas string dtypeInvalidParameterErrorIf an axis is out of range or repeated, orddofis negative or not finite
nansum
function nansum(t: Tensor, axis?: Axis | readonly Axis[], keepdims?: boolean): Tensor;Sum of elements, treating NaN as zero. The sum of an empty or all-NaN slice is 0. Uses compensated summation. The result is always float64.
Parameters
tTensor- Input tensor
axisoptionalAxis | readonly Axis[]- Axis or axes to reduce (default: all)
keepdimsoptionalboolean- Keep reduced axes as size-1 dimensions
Returns
Tensorfloat64 tensor of sums
Throws
DTypeErrorIfthas string dtypeInvalidParameterErrorIf an axis is out of range or repeated
nonzero
function nonzero(t: Tensor): Tensor[];Indices of the nonzero elements, one int32 tensor per dimension (like np.nonzero). NaN counts as nonzero. The indices are in row-major order, so nonzero(t) can be used directly to index t element by element.
Parameters
tTensor- Input tensor
Returns
Tensor[]Array with t.ndim int32 tensors of shape [count]; entry d holds the index along axis d of every nonzero element
Throws
ShapeErrorIftis 0-d (use argwhere or reshape to 1-D first)DTypeErrorIfthas string dtype
const [rows, cols] = nonzero(tensor([[0, 2], [3, 0]]));// rows: [0, 1], cols: [1, 0]onesLike
function onesLike(t: Tensor, options?: LikeOptions): Tensor;Create a tensor of ones with the same shape as the input tensor.
Parameters
tTensor- Reference tensor
optionsoptionalLikeOptionsdtypeoverrides the result dtype (default: the dtype oft)
Returns
TensorNew tensor filled with ones
Throws
DTypeErrorIf the resulting dtype is string
const a = tensor([[1, 2], [3, 4]]);const o = onesLike(a); // [[1, 1], [1, 1]]pad
function pad(t: Tensor, padWidth: PadWidth, mode?: PadMode, constantValue?: number | bigint): Tensor;Pad a tensor.
Parameters
tTensor- Input tensor
padWidthPadWidth- Padding as
[[before0, after0], [before1, after1], ...]with one pair per axis. A single pair, or a single-element list of pairs, applies to every axis, and a number pads every side of every axis by that amount. modeoptionalPadMode- Padding mode:
'constant','reflect','symmetric','replicate'(alias'edge') or'circular'(alias'wrap') constantValueoptionalnumber | bigint- Fill value for constant mode (default: 0). Converted to the dtype of
t(booleans store 1 for any non-zero value)
Returns
TensorPadded tensor
Throws
InvalidParameterErrorIf the mode is unknown, a pad width is negative or not an integer, or a non-constant mode would extend an empty axis
pad(tensor([1, 2, 3]), [[2, 1]]); // [0, 0, 1, 2, 3, 0]putAlongAxis
function putAlongAxis(arr: Tensor, indices: Tensor, values: Tensor | number | bigint, axis?: Axis | null): Tensor;Put values into a copy of arr along an axis at the positions given by indices (like np.put_along_axis, with the same index and broadcasting rules as takeAlongAxis).
Details
Unlike NumPy, which modifies arr in place and returns nothing, this function leaves arr unchanged and returns the updated copy, as scatter does. values broadcasts to the broadcast shape of the indices; a plain number or bigint is accepted and converted to the dtype of arr. When an index repeats, the last value written wins (row-major order).
With axis = null, arr is flattened for the operation, indices must be 1-D, and the result has the shape of arr.
Parameters
arrTensor- Tensor to update (not modified)
indicesTensor- Integer positions along
axis(same number of dimensions asarr) valuesTensor | number | bigint- Values to write: a tensor broadcastable to the index shape, or a scalar
axisoptionalAxis | null- Axis to index along (default: -1), or
nullto use the flattenedarr
Returns
TensorNew tensor with the shape and dtype of arr
Throws
ShapeErrorIf the dimensions differ, the other axes do not broadcast, orvaluesdoes not broadcast to the index shapeIndexErrorIf an index is out of bounds foraxisInvalidParameterErrorIf an index is not an integer oraxisis out of rangeDTypeErrorIf a tensor has string dtype, orindiceshas bool dtype
const a = tensor([[10, 30, 20], [60, 40, 50]]);const idx = tensor([[0], [2]]);putAlongAxis(a, idx, 99, 1); // [[99, 30, 20], [60, 40, 99]]rfft
function rfft(t: Tensor, n?: number, axis?: number, norm?: FFTNorm): FFTResult;Compute the one-dimensional FFT of real input, keeping only the non-negative frequencies.
The spectrum of a real signal is Hermitian-symmetric, so the transformed axis has length floor(n / 2) + 1.
Parameters
tTensor- Real-valued input tensor.
noptionalnumber- Length of the underlying FFT. Default: the input length along
axis. axisoptionalnumber- Axis to transform. Default: -1.
normoptionalFFTNorm- Normalization mode. Default:
"backward".
Returns
FFTResultObject with real and imag tensors of shape [..., floor(n/2) + 1] (along axis).
const { real, imag } = rfft(tensor([1, 2, 3, 4]));// real = [10, -2, -2], imag = [0, 2, 0]rfftfreq
function rfftfreq(n: number, d?: number): Tensor;Sample frequencies of an n-point rfft: [0, 1, ..., floor(n/2)] / (n * d).
Parameters
nnumber- Window length (positive integer).
doptionalnumber- Sample spacing (non-zero). Default: 1.
Returns
Tensor1-D float64 tensor of length floor(n / 2) + 1.
roll
function roll(t: Tensor, shift: number | readonly number[], axis?: Axis | readonly Axis[]): Tensor;Roll tensor elements along the given axis. Elements that roll beyond the last position are re-introduced at the first. The result is a copy.
With several axes, shift is either one number applied to every axis or a list with one shift per axis (NumPy semantics). Without axis the tensor is rolled as if flattened and keeps its shape.
Parameters
tTensor- Input tensor
shiftnumber | readonly number[]- Number of places to shift (positive = toward end)
axisoptionalAxis | readonly Axis[]- Axis or axes along which to roll (default: roll the flattened tensor)
Returns
TensorRolled tensor
Throws
InvalidParameterErrorIf a shift is not an integer, orshiftandaxislengths disagree
roll(tensor([1, 2, 3, 4, 5]), 2); // [4, 5, 1, 2, 3]rot90
function rot90(t: Tensor, k?: number): Tensor;Rotate a 2-D tensor by 90 degrees counter-clockwise, k times.
Parameters
tTensor- Input 2-D tensor
koptionalnumber- Number of 90° rotations (default 1). Negative values rotate clockwise.
Returns
TensorRotated copy of the tensor
Throws
ShapeErrorIf the input is not 2-DInvalidParameterErrorIfkis not an integer
scatter
function scatter(t: Tensor, dim: Axis, index: Tensor, src: Tensor): Tensor;Scatter values into a copy of a tensor at specified indices along an axis. This is the inverse of gather: for a 3-D tensor and dim = 0 the result satisfies out[index[i][j][k]][j][k] = src[i][j][k].
t, index and src must have the same number of dimensions, index must not be larger than src along any axis, and not larger than t along every axis except dim. Negative indices count from the end of the axis. When an index repeats, the last write wins. Values of src are converted to the dtype of t.
Parameters
tTensor- Input tensor (left unchanged)
dimAxis- Dimension along which to scatter
indexTensor- Integer-valued index tensor
srcTensor- Source values tensor
Returns
TensorNew tensor with scattered values
Throws
ShapeErrorIf the shapes are inconsistentIndexErrorIf an index is out of bounds fordimInvalidParameterErrorIf an index is not an integer
searchsorted
function searchsorted(sortedArr: Tensor, values: Tensor, side?: "left" | "right"): Tensor;Find indices where elements should be inserted to maintain order.
NaN sorts after every other value (NumPy convention), so searching for NaN returns the length of the array unless the array itself ends in NaNs. The array is not checked for being sorted. The indices are returned as int32.
Parameters
sortedArrTensor- 1-D sorted tensor
valuesTensor- Values to insert (any shape)
sideoptional"left" | "right"'left'(default): first suitable index,'right': last suitable index
Returns
Tensorint32 tensor of insertion indices with the shape of values
Throws
ShapeErrorIfsortedArris not 1-DInvalidParameterErrorIfsideis not'left'or'right'
swapaxes
function swapaxes(t: Tensor, axis1: number, axis2: number): Tensor;Swap two axes of a tensor. The result is a zero-copy view that shares the input's buffer.
Parameters
tTensor- Input tensor
axis1number- First axis
axis2number- Second axis
Returns
TensorTensor view with swapped axes
Throws
InvalidParameterErrorIf an axis is out of range
takeAlongAxis
function takeAlongAxis(arr: Tensor, indices: Tensor, axis?: Axis | null): Tensor;Take values from arr along an axis at the positions given by indices (like np.take_along_axis). It is the companion of argsort, argmax and similar functions that return per-axis positions.
Details
arr and indices must have the same number of dimensions. Every axis except axis broadcasts between the two (a size-1 axis stretches), and the result has the length of indices along axis: out[i][j][k] = arr[i][indices[i][j][k]][k] for axis = 1. Negative indices count from the end of the axis. Integer-valued float indices are accepted.
With axis = null, arr is flattened first and indices must be 1-D.
Parameters
arrTensor- Source tensor
indicesTensor- Integer positions along
axis(same number of dimensions asarr) axisoptionalAxis | null- Axis to index along (default: -1), or
nullto use the flattenedarr
Returns
TensorNew tensor with the dtype of arr and the broadcast shape described above
Throws
ShapeErrorIf the dimensions differ or the other axes do not broadcastIndexErrorIf an index is out of bounds foraxisInvalidParameterErrorIf an index is not an integer oraxisis out of rangeDTypeErrorIfarrorindiceshas string dtype, orindiceshas bool dtype
const a = tensor([[10, 30, 20], [60, 40, 50]]);const order = argsort(a, 1); // [[0, 2, 1], [1, 2, 0]]takeAlongAxis(a, order, 1); // [[10, 20, 30], [40, 50, 60]]tril
function tril(t: Tensor, k?: number): Tensor;Return the lower triangular part of a tensor, with elements above the k-th diagonal zeroed. For tensors with more than two axes the last two axes are treated as the matrix and the leading axes as a batch.
Parameters
tTensor- Input tensor with at least 2 dimensions
koptionalnumber- Diagonal offset (0 = main diagonal)
Returns
TensorLower triangular tensor
Throws
ShapeErrorIf the input has fewer than 2 dimensionsInvalidParameterErrorIfkis not an integer
tril(tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]));// [[1, 0, 0], [4, 5, 0], [7, 8, 9]]triu
function triu(t: Tensor, k?: number): Tensor;Return the upper triangular part of a tensor, with elements below the k-th diagonal zeroed. For tensors with more than two axes the last two axes are treated as the matrix and the leading axes as a batch.
Parameters
tTensor- Input tensor with at least 2 dimensions
koptionalnumber- Diagonal offset (0 = main diagonal)
Returns
TensorUpper triangular tensor
Throws
ShapeErrorIf the input has fewer than 2 dimensionsInvalidParameterErrorIfkis not an integer
triu(tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]));// [[1, 2, 3], [0, 5, 6], [0, 0, 9]]unique
function unique<const O extends UniqueOptions>(t: Tensor, options: O): UniqueOutput<O>;Parameters
tTensoroptionsO
Returns
UniqueOutput<O>
where
function where(condition: Tensor, x: Tensor, y: Tensor): Tensor;Conditional element selection: returns elements from x where condition is true, and from y where condition is false.
All three tensors must be broadcastable to a common shape. The condition is evaluated as boolean: 0 is false, every other value (including NaN) is true. x and y must have the same dtype.
Complexity: O(n) where n is the number of elements in the output
Parameters
conditionTensor- Boolean condition tensor
xTensor- Values where condition is true
yTensor- Values where condition is false
Returns
TensorTensor with selected elements
Throws
DTypeErrorIf any input has string dtype, orxandydiffer in dtypeShapeErrorIf the shapes cannot be broadcast together
const cond = tensor([1, 0, 1, 0], { dtype: 'bool' });const x = tensor([10, 20, 30, 40]);const y = tensor([1, 2, 3, 4]);const result = where(cond, x, y); // [10, 2, 30, 4]zerosLike
function zerosLike(t: Tensor, options?: LikeOptions): Tensor;Create a tensor of zeros with the same shape as the input tensor.
Parameters
tTensor- Reference tensor
optionsoptionalLikeOptionsdtypeoverrides the result dtype (default: the dtype oft)
Returns
TensorNew tensor filled with zeros (empty strings for string dtype)
const a = tensor([[1, 2], [3, 4]]);const z = zerosLike(a); // [[0, 0], [0, 0]]dropoutMask
function dropoutMask(shape: Shape, p: number, scale: number, dtype: NumericDType, device: Device): Tensor;Generate a tensor of Bernoulli samples scaled by a constant.
Details
Each element is independently drawn: it equals scale with probability (1 - p) and 0 with probability p. This is the mask used by inverted dropout: non-dropped elements are pre-scaled by 1 / (1 - p).
Draws come from the library's shared random stream, so setSeed makes the mask reproducible. For integer dtypes scale is converted like astype does (truncated toward zero); bool masks hold 1 where scale is non-zero.
Parameters
shapeShape- Output tensor shape
pnumber- Probability of an element being zero (drop probability), in
[0, 1) scalenumber- Value assigned to kept elements (typically
1 / (1 - p)), must be finite dtypeNumericDType- Numeric dtype for the output tensor
deviceDevice- Target device
Returns
TensorTensor of the given shape filled with 0 or scale
Throws
InvalidParameterErrorIfpis outside[0, 1)orscaleis not finite
These older spellings still work in 1.x. New code should use the names above.
atleast_1dPrefer atleast1d.atleast_2dPrefer atleast2d.broadcast_toPrefer broadcastTo.empty_likePrefer emptyLike.fliplrPrefer flipLr.flipudPrefer flipUd.full_likePrefer fullLike.index_selectPrefer indexSelect.ones_likePrefer onesLike.zeros_likePrefer zerosLike.
import { CSRMatrix, convolve, einsum, fft, ifft, nanmean, tensor, unique,} from "deepbox/ndarray"; const dense = tensor([ [1, 0, 0], [0, 2, 3],]);const sparse = CSRMatrix.fromDense(dense);console.log(sparse.nnz, sparse.matvec(tensor([1, 1, 1])).toString());console.log(sparse.toDense().toString()); console.log(einsum("ij,jk->ik", dense, tensor([[1], [2], [3]])).toString()); const signal = tensor([1, 2, 3, 4]);const spectrum = fft(signal); // { real, imag }console.log(spectrum.real.toString(), spectrum.imag.toString());console.log(ifft(spectrum.real, spectrum.imag).real.toString()); console.log(convolve(tensor([1, 2, 3]), tensor([0, 1, 0.5])).toString());console.log(nanmean(tensor([1, Number.NaN, 3])).toString());console.log(unique(tensor([3, 1, 1, 2]), { returnCounts: true }).counts?.toString());Found a mistake? Open an issue.