Sub topic 7
Why the Matrix Is Sparse and How It Is Stored
This chapter assumes you understand Python lists, NumPy arrays, document-term matrices, and the basic idea of counting words. You will learn why text matrices contain mostly zeros and how sparse storage avoids wasting memory.
Why text matrices are sparse
A document-term matrix has one row per document and one column per vocabulary term. Each cell stores a term's count, or a derived weight such as TF-IDF.
A collection may contain thousands of terms, but each document uses only a small fraction of them. For example, a document about cats may contain cat and sleep, but not most of the vocabulary. Its row therefore contains many zeros.
A matrix is called sparse when most of its values are zero. A matrix with mostly nonzero values is called dense.
Consider this matrix:
| Document | cat | dog | tree | ocean |
|---|---|---|---|---|
| D1 | 2 | 0 | 0 | 0 |
| D2 | 0 | 1 | 1 | 0 |
| D3 | 0 | 0 | 0 | 3 |
Only four of twelve values are nonzero. Storing all twelve values is unnecessary. Sparse storage keeps the nonzero values and enough information to locate them.
How sparse storage works
A common format is compressed sparse row (CSR). CSR stores three arrays:
datastores the nonzero values.indicesstores the column index of each value.indptrmarks where each row starts and ends indata.
For the matrix above, the nonzero values in row order are:
data:[2, 1, 1, 3]indices:[0, 1, 2, 3]indptr:[0, 1, 3, 4]
The first row uses entries from positions 0 through 0. The second uses positions 1 through 2. The third uses position 3.
import numpy as np
from scipy.sparse import csr_matrix
X = csr_matrix([
[2, 0, 0, 0],
[0, 1, 1, 0],
[0, 0, 0, 3],
])
print(X.data)
print(X.indices)
print(X.indptr)
print(X.toarray())CountVectorizer and TfidfVectorizer return sparse matrices by default. This makes them practical for large collections, where converting every matrix to a dense NumPy array could consume a large amount of memory.
Choosing a sparse format
CSR is efficient for reading or processing complete rows, so it suits document vectors and many machine learning models. Compressed sparse column (CSC) stores the same idea by columns and can be useful for column-based operations.
Use .toarray() only for small matrices or inspection. For a large text dataset, it may allocate more memory than your machine can provide.
Exercise
Why does CSR storage need the indptr array?
Show answer
It records the start and end positions of each row's nonzero values in the data and indices arrays.