Skip to content

deepbox/ndarray

Shape, Indexing & Set Ops

Reshaping, slicing, joining and splitting, inserting and deleting, and set and search helpers such as union1d, digitize and interp.

  • Indexing
  • Manipulation

Overview

  • reshape, transpose, squeeze, unsqueeze and expandDims return views when the memory layout allows it, so a write through one is visible in the other. slice is different from NumPy: on the CPU it returns a copy (on a device it returns a view).
  • slice(t, ...ranges) takes one entry per leading axis. An integer picks an index and drops the axis, and { start, end, step } keeps the axis (negative bounds and steps work). Axes without an entry are kept whole.
  • concatenate and stack take an array of tensors and an axis (default 0). split(t, count | indices, axis) returns an array of tensors. meshgrid defaults to "xy" indexing as NumPy does, and takes { indexing: "ij" } as a last argument.
  • union1d, intersect1d and setdiff1d return sorted unique values. digitize returns int32 bin indices and handles decreasing bins.

Types

1

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;};

Functions

29

column_stack

function column_stack(tensors: Tensor[]): Tensor;

Stack 1D arrays as columns into a 2D array.

Equivalent to numpy.column_stack() for 0D, 1D and 2D inputs. Each 1D tensor of length N becomes an [N, 1] column (a scalar becomes [1, 1]), 2D tensors are kept as they are, and the result is concatenated along axis 1. The input dtype is kept; tensors of different numeric dtypes are promoted to a common one.

Parameters

tensors
Tensor[]
Sequence of 0D, 1D or 2D tensors to stack as columns

Returns

Tensor2D tensor where each input is a column

Throws

  • InvalidParameterErrorIf tensors is empty
  • ShapeErrorIf an input has more than 2 dimensions or the row counts differ
  • DTypeErrorIf string and numeric tensors are mixed
Example
const a = tensor([1, 2, 3]);const b = tensor([4, 5, 6]);columnStack([a, b]);  // tensor([[1, 4], [2, 5], [3, 6]])

columnStack

function columnStack(tensors: Tensor[]): Tensor;

Stack 1D arrays as columns into a 2D array.

Equivalent to numpy.column_stack() for 0D, 1D and 2D inputs. Each 1D tensor of length N becomes an [N, 1] column (a scalar becomes [1, 1]), 2D tensors are kept as they are, and the result is concatenated along axis 1. The input dtype is kept; tensors of different numeric dtypes are promoted to a common one.

Parameters

tensors
Tensor[]
Sequence of 0D, 1D or 2D tensors to stack as columns

Returns

Tensor2D tensor where each input is a column

Throws

  • InvalidParameterErrorIf tensors is empty
  • ShapeErrorIf an input has more than 2 dimensions or the row counts differ
  • DTypeErrorIf string and numeric tensors are mixed
Example
const a = tensor([1, 2, 3]);const b = tensor([4, 5, 6]);columnStack([a, b]);  // tensor([[1, 4], [2, 5], [3, 6]])

concatenate

function concatenate(tensors: Tensor[], axis?: Axis): Tensor;

Concatenate tensors along an existing axis.

All tensors must have the same number of dimensions, the same dtype and the same shape except along axis. Mixed dtypes are rejected rather than promoted; convert with astype first. The result is always a new tensor, also when a single tensor is passed.

Complexity: O(n) where n is total number of elements

Parameters

tensors
Tensor[]
Array of tensors to concatenate
axisoptional
Axis
Axis along which to concatenate (default: 0)

Returns

TensorConcatenated tensor

Throws

  • InvalidParameterErrorIf tensors is empty or axis is out of range
  • ShapeErrorIf ndim or the non-concatenation dimensions differ
  • DTypeErrorIf the dtypes differ
Example
const a = tensor([[1, 2], [3, 4]]);const b = tensor([[5, 6]]);const c = concatenate([a, b], 0);  // [[1, 2], [3, 4], [5, 6]]

delete_

function delete_(t: Tensor, indices: number | number[], axis?: Axis): Tensor;

Delete elements from a tensor along an axis.

Follows numpy.delete. If axis is undefined the input is flattened first. Negative indices count from the end and repeated indices are deleted once. Uses trailing underscore to avoid collision with the JS delete keyword.

Complexity: O(n) where n is input size

Parameters

t
Tensor
Input tensor
indices
number | number[]
Index or array of indices of elements to delete
axisoptional
Axis
Axis along which to delete. If undefined, tensor is flattened.

Returns

TensorNew tensor with specified elements removed

Throws

  • InvalidParameterErrorIf an index is not an integer in [-n, n - 1] for axis size n
Example
const a = tensor([1, 2, 3, 4, 5]);delete_(a, 2);           // [1, 2, 4, 5]delete_(a, [0, 3]);      // [2, 3, 5] const b = tensor([[1, 2], [3, 4], [5, 6]]);delete_(b, 1, 0);        // [[1, 2], [5, 6]]

digitize

function digitize(x: Tensor, bins: Tensor, right?: boolean): Tensor;

Return the indices of the bins to which each value in the input array belongs.

Details

Equivalent to numpy.digitize(x, bins, right).

For increasing bins, with right false (default), the bin index i satisfies bins[i-1] <= x < bins[i]; with right true it satisfies bins[i-1] < x <= bins[i]. For decreasing bins the inequalities are reversed: bins[i-1] > x >= bins[i] and bins[i-1] >= x > bins[i]. Values below the first bin get index 0 and values past the last get bins.length (for increasing bins). NaN is placed after the last increasing bin, and at index 0 for decreasing bins. An empty bins maps everything to 0.

The indices are returned as an int32 tensor.

Parameters

x
Tensor
Input tensor of values to be binned
bins
Tensor
1D monotonically increasing or decreasing array of bin edges (no NaN)
rightoptional
boolean
If true, intervals are closed on the right (default: false)

Returns

Tensorint32 tensor of bin indices (same shape as x)

Throws

  • ShapeErrorIf bins is not 1D
  • InvalidParameterErrorIf bins is not monotonic or contains NaN
Example
const x = tensor([0.5, 1.5, 2.5, 3.5]);const bins = tensor([1, 2, 3]);digitize(x, bins);  // tensor([0, 1, 2, 3])

gcd

function gcd(a: Tensor, b: Tensor): Tensor;

Element-wise greatest common divisor.

Both inputs are cast to integers (floats are truncated toward zero) and the result is always non-negative, with gcd(0, 0) = 0. Inputs broadcast against each other under NumPy rules. If either input is int64 the result is int64, otherwise int32.

Parameters

a
Tensor
First tensor
b
Tensor
Second tensor (broadcastable with a)

Returns

TensorTensor of GCD values with dtype int32 (int64 if an input is int64)

Throws

  • DTypeErrorIf an input has string or complex dtype
  • ShapeErrorIf the shapes do not broadcast
  • DataValidationErrorIf an input is NaN or infinite, or a result does not fit the output dtype
Example
const a = tensor([12, 15, 20]);const b = tensor([8, 10, 25]);gcd(a, b); // [4, 5, 5]

gradient

function gradient(f: Tensor, spacing?: number | Tensor): Tensor;

Return the numerical gradient of a 1D array using central finite differences.

Interior points use second-order central differences. Boundary points use first-order one-sided differences.

Equivalent to numpy.gradient(f, *varargs) for 1D arrays with the default edge_order=1.

Parameters

f
Tensor
Input 1D tensor
spacingoptional
number | Tensor
Scalar spacing between samples (default: 1.0, must be positive and finite), or a 1D tensor with the coordinate of every sample (consecutive coordinates must differ)

Returns

TensorTensor of the same shape as f containing the numerical gradient. Its dtype is the float dtype of f (promoted with the spacing tensor when one is given; float32 for integer or bool input)

Throws

  • ShapeErrorIf f or the spacing tensor is not 1D, or their lengths differ
  • InvalidParameterErrorIf f has fewer than 2 elements, the scalar spacing is not a positive finite number, or the coordinates contain repeated or non-finite steps
Example
const f = tensor([1, 2, 4, 7, 11]);gradient(f);         // tensor([1, 1.5, 2.5, 3.5, 4])gradient(f, 0.5);    // tensor([2, 3, 5, 7, 8])

hstack

function hstack(tensors: Tensor[]): Tensor;

Stack tensors horizontally (column-wise).

Equivalent to numpy.hstack(). Scalars are promoted to length-1 vectors. 1D tensors are concatenated along axis 0, everything else along axis 1. The input dtype is kept; tensors of different numeric dtypes are promoted to a common one.

Parameters

tensors
Tensor[]
Sequence of tensors to stack

Returns

TensorHorizontally stacked tensor

Throws

  • InvalidParameterErrorIf tensors is empty
  • ShapeErrorIf the other dimensions do not match
  • DTypeErrorIf string and numeric tensors are mixed
Example
const a = tensor([1, 2]);const b = tensor([3, 4]);hstack([a, b]);  // tensor([1, 2, 3, 4]) const c = tensor([[1], [2]]);const d = tensor([[3], [4]]);hstack([c, d]);  // tensor([[1, 3], [2, 4]])

insert

function insert(t: Tensor, indices: number | number[], values: number | string | Tensor, axis?: Axis): Tensor;

Insert values into a tensor along an axis before given indices.

Details

Follows numpy.insert. If axis is undefined the input is flattened first. Negative indices count from the end. With several indices, the i-th value (along axis) is inserted before the i-th index as given, and values are broadcast over the other dimensions. With a single index, every value along the insertion axis is inserted there in order, so insert(tensor([1, 2, 3]), 1, tensor([9, 8])) gives [1, 9, 8, 2, 3].

The result has the dtype of t; inserted values are converted to it.

Complexity: O(n + m) where n is input size and m is the size of the inserted data

Parameters

t
Tensor
Input tensor
indices
number | number[]
Index or array of indices before which values are inserted
values
number | string | Tensor
Values to insert: a number, a string (string tensors only), or a Tensor
axisoptional
Axis
Axis along which to insert. If undefined, tensor is flattened.

Returns

TensorNew tensor with values inserted

Throws

  • InvalidParameterErrorIf an index is not an integer in [-n, n] for axis size n
  • ShapeErrorIf values cannot be broadcast to the insertion slab
  • DTypeErrorIf string and numeric data are mixed
Example
const a = tensor([1, 2, 3, 4]);insert(a, 2, 99);          // [1, 2, 99, 3, 4]insert(a, [1, 3], 99);     // [1, 99, 2, 3, 99, 4] const b = tensor([[1, 2], [3, 4]]);insert(b, 1, tensor([5, 6]), 0);  // [[1, 2], [5, 6], [3, 4]]

interp

function interp(x: Tensor, xp: Tensor, fp: Tensor, left?: number, right?: number): Tensor;

One-dimensional linear interpolation.

Details

Returns the one-dimensional piecewise linear interpolant to a function with given discrete data points (xp, fp), evaluated at x.

Equivalent to numpy.interp(x, xp, fp, left, right). A value equal to xp[0] or xp[-1] returns fp[0] or fp[-1]; left and right apply only strictly outside [xp[0], xp[-1]]. A NaN in x gives NaN.

Complexity: O(n * log(m)) where n = len(x), m = len(xp)

Parameters

x
Tensor
The x-coordinates at which to evaluate the interpolated values
xp
Tensor
The x-coordinates of the data points, must be increasing (repeated values allowed)
fp
Tensor
The y-coordinates of the data points, same length as xp
leftoptional
number
Value to return for x < xp[0] (default: fp[0])
rightoptional
number
Value to return for x > xp[-1] (default: fp[-1])

Returns

TensorTensor of interpolated values, same shape as x. Its dtype is the promoted float dtype of x, xp and fp (float32 when all are integer or bool)

Throws

  • ShapeErrorIf xp or fp is not 1D, or their lengths differ
  • InvalidParameterErrorIf xp is empty, contains NaN, or is not increasing
Example
const xp = tensor([0, 1, 2, 3]);const fp = tensor([0, 1, 4, 9]);const x = tensor([0.5, 1.5, 2.5]);const y = interp(x, xp, fp);  // tensor([0.5, 2.5, 6.5])

intersect1d

function intersect1d(a: Tensor, b: Tensor): Tensor;

Compute the sorted, unique intersection of two 1D tensors.

NaN never matches another NaN (as in NumPy), so NaN is not part of the result. The result is float64, or int64 when one input is int64 and the other holds integers.

Parameters

a
Tensor
First 1D tensor
b
Tensor
Second 1D tensor

Returns

TensorSorted 1D tensor containing the unique intersection of elements

Throws

  • DTypeErrorIf an input has string or complex dtype
  • InvalidParameterErrorIf an input is not 1D
Example
intersect1d(tensor([1, 2, 3, 4]), tensor([2, 4, 6])); // [2, 4]

lcm

function lcm(a: Tensor, b: Tensor): Tensor;

Element-wise least common multiple.

Both inputs are cast to integers (floats are truncated toward zero) and the result is always non-negative, with lcm(x, 0) = 0. Inputs broadcast against each other under NumPy rules. If either input is int64 the result is int64, otherwise int32.

Parameters

a
Tensor
First tensor
b
Tensor
Second tensor (broadcastable with a)

Returns

TensorTensor of LCM values with dtype int32 (int64 if an input is int64)

Throws

  • DTypeErrorIf an input has string or complex dtype
  • ShapeErrorIf the shapes do not broadcast
  • DataValidationErrorIf an input is NaN or infinite, or a result does not fit the output dtype
Example
const a = tensor([4, 6, 12]);const b = tensor([6, 8, 15]);lcm(a, b); // [12, 24, 60]

repeat

function repeat(t: Tensor, repeats: number | readonly number[], axis?: Axis): Tensor;

Repeat elements of a tensor along an axis.

Each element is repeated consecutively. repeats is either one count used for every element, or an array with one count per element along the axis (a one-element array is broadcast). Without axis the tensor is flattened first and the result is 1-D.

Complexity: O(n * repeats) where n is input size

Parameters

t
Tensor
Input tensor
repeats
number | readonly number[]
Number of times to repeat each element, or one count per element
axisoptional
Axis
Axis along which to repeat (default: flatten first)

Returns

TensorTensor with repeated elements

Throws

  • InvalidParameterErrorIf a count is negative or not an integer, the array length does not match the axis length, or axis is out of range
Example
const t = tensor([1, 2, 3]);repeat(t, 2);           // [1, 1, 2, 2, 3, 3]repeat(t, [0, 2, 1]);   // [2, 2, 3]

setdiff1d

function setdiff1d(a: Tensor, b: Tensor): Tensor;

Compute the sorted set difference of two 1D tensors.

Returns the unique elements of a that are not in b. NaN never matches another NaN (as in NumPy), so a NaN in a is always kept. The result is float64, or int64 when one input is int64 and the other holds integers.

Parameters

a
Tensor
First 1D tensor
b
Tensor
Second 1D tensor

Returns

TensorSorted 1D tensor of unique elements in a not in b

Throws

  • DTypeErrorIf an input has string or complex dtype
  • InvalidParameterErrorIf an input is not 1D
Example
setdiff1d(tensor([1, 2, 3, 4]), tensor([2, 4])); // [1, 3]

split

function split(t: Tensor, indices_or_sections: number | number[], axis?: Axis): Tensor[];

Split tensor into multiple sub-tensors along an axis.

Details

If indices_or_sections is an integer, the tensor is split into that many equal parts (the axis length must be divisible by it). If it is an array, it lists the indices at which to split; the indices must be integers in [0, axisLength] in non-decreasing order, and the result has one more part than there are indices. The parts are copies, not views.

Complexity: O(n) where n is total number of elements

Parameters

t
Tensor
Input tensor
indices_or_sections
number | number[]
Number of sections or array of split indices
axisoptional
Axis
Axis along which to split (default: 0)

Returns

Tensor[]Array of sub-tensors

Throws

  • InvalidParameterErrorIf the sections or indices are invalid, or axis is out of range
Example
const t = tensor([1, 2, 3, 4, 5, 6]);const parts = split(t, 3);  // [tensor([1, 2]), tensor([3, 4]), tensor([5, 6])]const parts2 = split(t, [2, 4]);  // [tensor([1, 2]), tensor([3, 4]), tensor([5, 6])]

stack

function stack(tensors: Tensor[], axis?: Axis): Tensor;

Stack tensors along a new axis.

All tensors must have exactly the same shape and dtype. The result has one more dimension than the inputs, with size tensors.length at axis.

Complexity: O(n) where n is total number of elements

Parameters

tensors
Tensor[]
Array of tensors to stack
axisoptional
Axis
Position of the new axis in the result, -(ndim + 1) to ndim (default: 0)

Returns

TensorStacked tensor

Throws

  • InvalidParameterErrorIf tensors is empty or axis is out of range
  • ShapeErrorIf the shapes differ
  • DTypeErrorIf the dtypes differ
Example
const a = tensor([1, 2, 3]);const b = tensor([4, 5, 6]);const c = stack([a, b], 0);  // [[1, 2, 3], [4, 5, 6]]const d = stack([a, b], 1);  // [[1, 4], [2, 5], [3, 6]]

tile

function tile(t: Tensor, reps: number[]): Tensor;

Repeat tensor along axes by tiling.

Details

Constructs a tensor by repeating the input the given number of times along each axis. If reps has fewer entries than the tensor has dimensions it is padded with ones on the left; if the tensor has fewer dimensions than reps has entries, the tensor is treated as having leading axes of size 1. A repetition count of 0 produces an empty tensor.

Complexity: O(n * product(reps)) where n is input size

Parameters

t
Tensor
Input tensor
reps
number[]
Number of repetitions along each axis

Returns

TensorTiled tensor

Throws

  • InvalidParameterErrorIf reps is empty or contains a negative or non-integer value
Example
const t = tensor([[1, 2], [3, 4]]);const tiled = tile(t, [2, 3]);// [[1, 2, 1, 2, 1, 2],//  [3, 4, 3, 4, 3, 4],//  [1, 2, 1, 2, 1, 2],//  [3, 4, 3, 4, 3, 4]]

trapezoid

function trapezoid(y: Tensor, x?: Tensor, dx?: number): number;

Integrate a 1D signal using the composite trapezoidal rule.

Equivalent to numpy.trapezoid(y, x, dx) (formerly numpy.trapz) for 1D input. The terms are added with compensated summation, so long inputs do not accumulate rounding error.

Parameters

y
Tensor
1D tensor of function values
xoptional
Tensor
Optional 1D sample points corresponding to y values. If not provided, spacing is uniform with step dx.
dxoptional
number
Spacing between sample points when x is not given (default: 1.0)

Returns

numberScalar result of the integration (0 when y has fewer than 2 samples)

Throws

  • ShapeErrorIf y or x is not 1D, or their lengths differ
Example
const y = tensor([1, 2, 3, 4]);trapz(y);           // 7.5 (dx=1)trapz(y, undefined, 0.5);  // 3.75 (dx=0.5) const x = tensor([0, 1, 3, 5]);const y2 = tensor([1, 2, 3, 4]);trapz(y2, x);       // 13.5 (non-uniform spacing)

trapz

function trapz(y: Tensor, x?: Tensor, dx?: number): number;

Integrate a 1D signal using the composite trapezoidal rule.

Equivalent to numpy.trapezoid(y, x, dx) (formerly numpy.trapz) for 1D input. The terms are added with compensated summation, so long inputs do not accumulate rounding error.

Parameters

y
Tensor
1D tensor of function values
xoptional
Tensor
Optional 1D sample points corresponding to y values. If not provided, spacing is uniform with step dx.
dxoptional
number
Spacing between sample points when x is not given (default: 1.0)

Returns

numberScalar result of the integration (0 when y has fewer than 2 samples)

Throws

  • ShapeErrorIf y or x is not 1D, or their lengths differ
Example
const y = tensor([1, 2, 3, 4]);trapz(y);           // 7.5 (dx=1)trapz(y, undefined, 0.5);  // 3.75 (dx=0.5) const x = tensor([0, 1, 3, 5]);const y2 = tensor([1, 2, 3, 4]);trapz(y2, x);       // 13.5 (non-uniform spacing)

union1d

function union1d(a: Tensor, b: Tensor): Tensor;

Compute the sorted, unique union of two 1D tensors.

NaN values collapse into a single NaN that sorts last, as in NumPy. The result is float64, or int64 when one input is int64 and the other holds integers.

Parameters

a
Tensor
First 1D tensor
b
Tensor
Second 1D tensor

Returns

TensorSorted 1D tensor containing the unique union of elements

Throws

  • DTypeErrorIf an input has string or complex dtype
  • InvalidParameterErrorIf an input is not 1D
Example
union1d(tensor([1, 2, 3]), tensor([2, 3, 4])); // [1, 2, 3, 4]

vstack

function vstack(tensors: Tensor[]): Tensor;

Stack tensors vertically (row-wise).

Equivalent to numpy.vstack(). Tensors with fewer than two dimensions are promoted first (a 1D tensor of length N becomes a [1, N] row, a scalar becomes [1, 1]), then everything is concatenated along axis 0. The input dtype is kept; tensors of different numeric dtypes are promoted to a common one.

Parameters

tensors
Tensor[]
Sequence of tensors to stack

Returns

TensorVertically stacked tensor

Throws

  • InvalidParameterErrorIf tensors is empty
  • ShapeErrorIf the trailing dimensions do not match
  • DTypeErrorIf string and numeric tensors are mixed
Example
const a = tensor([1, 2, 3]);const b = tensor([4, 5, 6]);vstack([a, b]);  // tensor([[1, 2, 3], [4, 5, 6]])

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

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]]

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]

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

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-shape.ts
import {  concatenate,  delete_,  digitize,  hstack,  insert,  meshgrid,  repeat,  reshape,  slice,  split,  stack,  tensor,  tile,  union1d,} from "deepbox/ndarray"; const x = tensor([[1, 2, 3], [4, 5, 6]]);console.log(slice(x, { start: 0, end: 2 }, { start: 1, end: 3 }).toString());console.log(slice(x, 0).toString()); // an integer drops the axisconsole.log(reshape(x, [3, 2]).toString());console.log(stack([tensor([1, 2]), tensor([3, 4])]).toString());console.log(concatenate([tensor([1, 2]), tensor([3, 4])]).toString());console.log(split(tensor([1, 2, 3, 4]), 2).map((t) => t.toString()));console.log(repeat(tensor([1, 2]), 2).toString());console.log(tile(tensor([[1, 2]]), [2, 1]).toString());console.log(insert(tensor([1, 3, 4]), 1, tensor([2])).toString());console.log(delete_(tensor([1, 2, 3, 4]), 2).toString());console.log(hstack([tensor([[1], [2]]), tensor([[3], [4]])]).toString());console.log(meshgrid(tensor([0, 1]), tensor([10, 20])).map((t) => t.toString()));console.log(union1d(tensor([3, 1, 2]), tensor([2, 5])).toString());console.log(digitize(tensor([0.5, 2.5, 7]), tensor([1, 3, 5])).toString());