02
Tensors
Math
Broadcasting
Tensor Operations
Deepbox provides 90+ element-wise operations that follow Deepbox broadcasting rules. This example demonstrates element-wise arithmetic (add, sub, mul, div), mathematical functions (sin, cos, exp, log, sqrt, abs), reductions along axes (sum, mean, max, min, std, variance), comparisons (greater, less, equal), logical operations (logicalAnd, logicalOr), and tensor manipulation (concatenate, stack, sort, argsort, dot). You will see how broadcasting automatically expands shapes — for example, adding a [3] vector to a [2, 3] matrix broadcasts the vector across each row. All operations return new tensors (immutable) and support axis-wise reduction with optional keepdims.
Deepbox Modules Used
deepbox/ndarrayWhat You Will Learn
- Element-wise arithmetic follows Deepbox broadcasting rules automatically
- 90+ math functions: trigonometric, exponential, rounding, etc.
- Reductions (sum, mean, max, min, std) support axis parameter and keepdims
- Comparison and logical operations return boolean tensors
- dot() performs matrix multiplication for 2D tensors
Source Code
02-tensor-operations/index.ts
1import {2 add, mul, sub, div, sum, mean, max, min,3 sqrt, abs, exp, log, sin, cos,4 greater, equal, logicalAnd,5 concatenate, stack, sort, argsort, dot, tensor6} from "deepbox/ndarray";78console.log("=== Tensor Operations ===\n");910const a = tensor([[1, 2, 3], [4, 5, 6]]);11const b = tensor([[7, 8, 9], [10, 11, 12]]);1213// Arithmetic (element-wise)14console.log("add:", add(a, b).toString());15console.log("mul:", mul(a, b).toString());1617// Broadcasting: [2,3] + [3] → broadcasts across rows18const row = tensor([10, 20, 30]);19console.log("broadcast add:", add(a, row).toString());2021// Math functions22console.log("sqrt:", sqrt(tensor([4, 9, 16, 25])).toString());23console.log("exp:", exp(tensor([0, 1, 2])).toString());2425// Reductions26console.log("sum(all):", sum(a).toString());27console.log("sum(axis=0):", sum(a, 0).toString()); // Column sums28console.log("mean(axis=1):", mean(a, 1).toString()); // Row means29console.log("max:", max(a).toString());3031// Comparisons32console.log("a > 3:", greater(a, tensor(3)).toString());3334// Matrix operations35const A = tensor([[1, 2], [3, 4]]);36const B = tensor([[5, 6], [7, 8]]);37console.log("dot:", dot(A, B).toString());3839// Sorting40console.log("sorted:", sort(tensor([3, 1, 4, 1, 5])).toString());Console Output
$ npx tsx 02-tensor-operations/index.ts
=== Tensor Operations ===
add: [[8, 10, 12], [14, 16, 18]]
mul: [[7, 16, 27], [40, 55, 72]]
broadcast add: [[11, 22, 33], [14, 25, 36]]
sqrt: [2, 3, 4, 5]
exp: [1, 2.718, 7.389]
sum(all): 21
sum(axis=0): [5, 7, 9]
mean(axis=1): [2, 5]
max: 6
a > 3: [[0, 0, 0], [1, 1, 1]]
dot: [[19, 22], [43, 50]]
sorted: [1, 1, 3, 4, 5]