Example 01
beginner
01
Tensors

Tensor Basics

Learn the fundamentals of creating and manipulating tensors (N-dimensional arrays). Tensors are the core data structure in Deepbox. This example uses deepbox/ndarray and focuses on tensor, zeros, ones, eye, arange, linspace, reshape.

Deepbox Modules Used

deepbox/ndarray

What You Will Learn

  • Use deepbox/ndarray for tensor, zeros, ones, eye, arange, linspace, reshape.
  • Learn the fundamentals of creating and manipulating tensors (N-dimensional arrays). Tensors are the core data structure in Deepbox.

Source Files

index.ts
1/**2 * Example 01: Tensor Basics3 *4 * Learn the fundamentals of creating and manipulating tensors (N-dimensional arrays).5 * Tensors are the core data structure in Deepbox.6 */78import { arange, eye, linspace, ones, reshape, tensor, zeros } from "deepbox/ndarray";910console.log("=== Tensor Basics ===\n");1112// 1. Creating tensors from JavaScript arrays13const vector = tensor([1, 2, 3, 4, 5]);14console.log("1D Tensor (vector):");15console.log(vector.toString());16console.log(`Shape: [${vector.shape}], Size: ${vector.size}\n`);1718// 2. Create a 2D tensor (matrix)19const matrix = tensor([20  [1, 2, 3],21  [4, 5, 6],22]);23console.log("2D Tensor (matrix):");24console.log(matrix.toString());25console.log(`Shape: [${matrix.shape}], Size: ${matrix.size}\n`);2627// 3. Create a 3D tensor (higher dimensional)28const tensor3d = tensor([29  [30    [1, 2],31    [3, 4],32  ],33  [34    [5, 6],35    [7, 8],36  ],37]);38console.log("3D Tensor:");39console.log(`Shape: [${tensor3d.shape}], Size: ${tensor3d.size}\n`);4041// 4. Special tensor creation functions42const zeroMatrix = zeros([3, 3]);43console.log("3x3 Zero Matrix:");44console.log(`${zeroMatrix.toString()}\n`);4546const onesMatrix = ones([2, 4]);47console.log("2x4 Ones Matrix:");48console.log(`${onesMatrix.toString()}\n`);4950// 5. Create identity matrix (diagonal of ones)51const identity = eye(4);52console.log("4x4 Identity Matrix:");53console.log(`${identity.toString()}\n`);5455// 6. Create range of values with step56const range = arange(0, 10, 2); // start, stop, step57console.log("Range [0, 10) with step 2:");58console.log(`${range.toString()}\n`);5960// 7. Create linearly spaced values61const linspaced = linspace(0, 1, 5); // start, stop, num_points62console.log("5 values linearly spaced between 0 and 1:");63console.log(`${linspaced.toString()}\n`);6465// 8. Reshape tensors to different dimensions66const flat = tensor([1, 2, 3, 4, 5, 6]);67const reshaped = reshape(flat, [2, 3]);68console.log("Reshaped [6] -> [2, 3]:");69console.log(`${reshaped.toString()}\n`);7071console.log("✓ Tensor basics complete!");72

Console Output

$ npx tsx 01-tensor-basics/index.ts
Console output showing tensor creation, shapes, sizes, and reshaping operations