Example 01
beginner
01
Tensors
Basics

Tensor Basics

Tensors are the core data structure in Deepbox — the core data structure in Deepbox. This example teaches you how to create tensors from nested JavaScript arrays, TypedArrays, and factory functions like zeros(), ones(), eye(), arange(), and linspace(). You will inspect tensor properties (shape, dtype, ndim, size), access individual elements with .at(), convert tensors back to nested arrays with .toArray(), and understand how dtype inference works. The example also demonstrates creating tensors with explicit dtypes (int32, float64, bool) and using randn() for random initialization. This is the foundation for every other operation in Deepbox.

Deepbox Modules Used

deepbox/ndarray

What You Will Learn

  • Create tensors from nested arrays, scalars, and TypedArrays
  • Use factory functions: zeros(), ones(), eye(), full(), arange(), linspace(), randn()
  • Inspect properties: shape, dtype, ndim, size
  • Access elements with .at() and convert back with .toArray()
  • Control dtype explicitly via options or let Deepbox infer it

Source Code

01-tensor-basics/index.ts
1import {2  arange, eye, full, linspace, ones, randn, tensor, zeros3} from "deepbox/ndarray";45console.log("=== Tensor Basics ===\n");67// Create from nested arrays8const a = tensor([[1, 2, 3], [4, 5, 6]]);9console.log("Shape:", a.shape);   // [2, 3]10console.log("DType:", a.dtype);   // float3211console.log("Size:", a.size);     // 612console.log("Ndim:", a.ndim);     // 21314// Access elements15console.log("a[0,1] =", a.at(0, 1)); // 21617// Factory functions18const z = zeros([3, 3]);         // 3×3 of zeros19const o = ones([2, 4]);          // 2×4 of ones20const I = eye(3);                // 3×3 identity21const f = full([2, 2], 7);      // 2×2 filled with 722const r = arange(0, 10, 2);     // [0, 2, 4, 6, 8]23const l = linspace(0, 1, 5);    // [0, 0.25, 0.5, 0.75, 1]24const n = randn([2, 3]);        // 2×3 standard normal2526// Explicit dtypes27const ints = tensor([1, 2, 3], { dtype: "int32" });28const bools = tensor([true, false, true]);29console.log("int32:", ints.dtype);30console.log("bool:", bools.dtype);

Console Output

$ npx tsx 01-tensor-basics/index.ts
=== Tensor Basics ===

Shape: [2, 3]
DType: float32
Size: 6
Ndim: 2
a[0,1] = 2
int32: int32
bool: bool