Store only what is not zero
Many large matrices are almost all zeros. A grid for pricing an option has a row for each price level, and each row touches only its two neighbours. A matrix like that is called sparse. Storing every zero wastes memory and time. scipy.sparse keeps only the non-zero entries. The format csr_matrix (compressed sparse row) uses three lists. data holds the non-zero values row by row, indices holds the column of each value, and indptr says where each row starts and ends inside data: row is data[indptr[i]:indptr[i+1]]. The last number of indptr is the count of non-zeros, nnz.
Different formats suit different jobs. coo_matrix stores plain (row, column, value) triples and is the easy way to build a matrix. csr_matrix is fast for row slices and for the product , which costs about nnz multiplications instead of . csc_matrix is the same idea by columns, and dia_matrix stores diagonals, ideal for banded matrices. For a system , sparse.linalg.spsolve uses the zeros to be much faster than a dense solve. Sparse is not always better: if more than about a third of the entries are non-zero, the bookkeeping costs more than it saves. In finance, sparsity appears in pricing grids, in factor models where most loadings are zero, and when you keep only the strong correlations.
data=[5,1,2,3,4], indices=[0,3,2,0,3] and indptr=[0,2,3,3,5]. Row is empty because indptr[2]=indptr[3]=3, and nnz=5. Multiplying by adds up each row, giving with only multiplications. A tridiagonal matrix with , like a finite-difference pricing grid, has non-zeros out of entries, a density of . It needs about KB in CSR against MB dense. On real data, the correlations of stocks from the shared price file form a matrix. Keeping only entries with leaves of entries, , and the CSR copy takes KB against KB dense. At only remain.- Three lists:
data,indicesandindptrdescribe a CSR matrix, andindptr[-1]is the number of non-zeros. - Build in COO, compute in CSR: triples are easy to assemble, row-based storage is fast for products and solves.
- Sparse pays only when mostly zero: a dense matrix is better when many entries are non-zero.
Lab · what's graded
- Counting non-zeros10 pts
- How many values in a row10 pts
- The density of a grid10 pts
- A sparse product15 pts
- Which format for which job15 pts
- A tridiagonal system10 pts
- When sparse pays and when it does not30 pts