Example 26
advanced
26
Sparse
Memory Efficiency
Linear Algebra

Sparse Matrix Operations

When a matrix is mostly zeros (>90% sparsity), storing it as a dense tensor wastes enormous memory. Deepbox's CSRMatrix class uses Compressed Sparse Row format — only non-zero values, their column indices, and row pointers are stored. This example creates a sparse matrix from COO (coordinate) format, performs arithmetic (add, subtract, scale, element-wise multiply), matrix-vector multiplication (matvec), sparse-sparse matrix multiplication (matmul), transposition, and conversion back to dense. You will see that a 1000×1000 matrix with 1% density uses ~100x less memory in CSR format. This is essential for large-scale graph algorithms, recommendation systems, and NLP document-term matrices.

Deepbox Modules Used

deepbox/ndarray

What You Will Learn

  • CSR format stores only non-zero values — huge memory savings for sparse data
  • CSRMatrix.fromCOO() creates from coordinate triplets (row, col, value)
  • matvec() multiplies sparse matrix by dense vector efficiently
  • toDense() converts back when you need the full matrix
  • Use for adjacency matrices, document-term matrices, and feature matrices with many zeros

Source Code

26-sparse-matrices/index.ts
1import { CSRMatrix } from "deepbox/ndarray";2import { tensor } from "deepbox/ndarray";34console.log("=== Sparse Matrices ===\n");56const sparse = CSRMatrix.fromCOO({7  rows: 4, cols: 4,8  rowIndices: new Int32Array([0, 0, 1, 2, 3, 3]),9  colIndices: new Int32Array([0, 2, 1, 2, 0, 3]),10  values: new Float64Array([1, 2, 3, 4, 5, 6]),11});1213console.log("Shape:", sparse.shape);14console.log("NNZ:", sparse.nnz);  // 6 non-zero entries15console.log("Density:", (sparse.nnz / (4 * 4) * 100).toFixed(1) + "%");1617// Convert to dense for inspection18console.log("\nDense:");19console.log(sparse.toDense().toString());2021// Arithmetic22const scaled = sparse.scale(2);23console.log("\nScaled ×2 (NNZ:", scaled.nnz + "):");24console.log(scaled.toDense().toString());2526// Matrix-vector multiplication27const v = tensor([1, 2, 3, 4]);28const result = sparse.matvec(v);29console.log("\nmatvec:", result.toString());3031// Transpose32console.log("\nTranspose NNZ:", sparse.transpose().nnz);

Console Output

$ npx tsx 26-sparse-matrices/index.ts
=== Sparse Matrices ===

Shape: [4, 4]
NNZ: 6
Density: 37.5%

Dense:
[[1, 0, 2, 0],
 [0, 3, 0, 0],
 [0, 0, 4, 0],
 [5, 0, 0, 6]]

Scaled ×2 (NNZ: 6):
[[2, 0, 4, 0],
 [0, 6, 0, 0],
 [0, 0, 8, 0],
 [10, 0, 0, 12]]

matvec: [7, 6, 12, 29]

Transpose NNZ: 6