26
Tensors
Sparse Matrix Operations
Demonstrates CSR (Compressed Sparse Row) matrix operations. Memory-efficient representation for matrices with many zeros. This example uses deepbox/ndarray and focuses on CSRMatrix (fromCOO, add, scale, multiply, matvec, matmul, transpose, toDense), tensor.
Deepbox Modules Used
deepbox/ndarrayWhat You Will Learn
- Use deepbox/ndarray for CSRMatrix (fromCOO, add, scale, multiply, matvec, matmul, transpose, toDense), tensor.
- Demonstrates CSR (Compressed Sparse Row) matrix operations. Memory-efficient representation for matrices with many zeros.
Source Files
index.ts
1/**2 * Sparse Matrix Operations Example3 * Demonstrates CSR (Compressed Sparse Row) matrix operations4 */56import { CSRMatrix, tensor } from "deepbox/ndarray";78const expectFloat64Array = (value: unknown): Float64Array => {9 if (!(value instanceof Float64Array)) {10 throw new Error("Expected Float64Array");11 }12 return value;13};1415console.log("=== Sparse Matrix Operations ===\n");1617// Create a sparse matrix using COO (Coordinate) format18console.log("1. Creating sparse matrices");19// Matrix:20// [1, 0, 0, 2]21// [0, 3, 0, 0]22// [0, 0, 4, 0]23// [5, 0, 0, 6]24const sparse = CSRMatrix.fromCOO({25 rows: 4,26 cols: 4,27 rowIndices: new Int32Array([0, 0, 1, 2, 3, 3]),28 colIndices: new Int32Array([0, 3, 1, 2, 0, 3]),29 values: new Float64Array([1, 2, 3, 4, 5, 6]),30});31console.log(" Created 4x4 sparse matrix with 6 non-zero elements");32console.log(` Sparsity: ${((1 - sparse.nnz / (sparse.rows * sparse.cols)) * 100).toFixed(1)}%`);3334// Element access35console.log("\n2. Element access");36console.log(` Element at (0,0): ${sparse.get(0, 0)}`);37console.log(` Element at (0,3): ${sparse.get(0, 3)}`);38console.log(` Element at (1,1): ${sparse.get(1, 1)}`);3940// Arithmetic operations41console.log("\n3. Sparse matrix addition");42// Matrix:43// [0, 1, 0, 0]44// [2, 0, 0, 0]45// [0, 0, 0, 3]46// [0, 4, 0, 0]47const sparse2 = CSRMatrix.fromCOO({48 rows: 4,49 cols: 4,50 rowIndices: new Int32Array([0, 1, 2, 3]),51 colIndices: new Int32Array([1, 0, 3, 1]),52 values: new Float64Array([1, 2, 3, 4]),53});54const sum = sparse.add(sparse2);55console.log(` Result has ${sum.nnz} non-zero elements`);5657console.log("\n4. Scalar multiplication");58const scaled = sparse.scale(2);59console.log(` Scaled matrix has ${scaled.nnz} non-zero elements`);60console.log(` Element at (0,0): ${scaled.get(0, 0)} (was ${sparse.get(0, 0)})`);6162console.log("\n5. Element-wise multiplication (Hadamard product)");63const product = sparse.multiply(sparse2);64console.log(` Product has ${product.nnz} non-zero elements`);6566// Matrix-vector multiplication67console.log("\n6. Matrix-vector multiplication");68const vec = tensor([1, 2, 3, 4]);69const result = sparse.matvec(vec);70const resultData = expectFloat64Array(result.data);71console.log(` Result: [${Array.from(resultData).join(", ")}]`);7273// Matrix-matrix multiplication74console.log("\n7. Matrix-matrix multiplication");75// Matrix B (4x2):76// [1, 0]77// [0, 1]78// [1, 1]79// [0, 1]80const B = tensor([81 [1, 0],82 [0, 1],83 [1, 1],84 [0, 1],85]);86const matmul = sparse.matmul(B);87console.log(` Result shape: [${matmul.shape.join(", ")}]`);88console.log(` Result is a dense tensor`);8990// Transpose91console.log("\n8. Transpose");92const transposed = sparse.transpose();93console.log(` Original: ${sparse.rows}x${sparse.cols}`);94console.log(` Transposed: ${transposed.rows}x${transposed.cols}`);95console.log(` Non-zero elements preserved: ${transposed.nnz}`);9697// Convert back to dense98console.log("\n9. Convert to dense");99const densified = sparse.toDense();100console.log(" Converted back to dense tensor");101console.log(` Shape: [${densified.shape.join(", ")}]`);102103console.log("\n=== Benefits of Sparse Matrices ===");104console.log("- Memory efficient for matrices with many zeros");105console.log("- Faster operations when sparsity is high");106console.log("- Common in scientific computing, ML, and graph algorithms");107Console Output
$ npx tsx 26-sparse-matrices/index.ts
Console output showing sparse matrix creation, element access, arithmetic, matrix-vector/matrix multiplication, transpose, and dense conversion