Sub topic 7
Why the matrix is sparse and how it is stored
This chapter assumes you can read a document-term matrix (rows are documents, columns are vocabulary terms, cells are counts) and that you know basic NumPy. You don't need to know SciPy. By the end you should be able to explain why these matrices are mostly zeros, read the three arrays inside a scikit-learn result, estimate memory use, and avoid operations that make a sparse matrix dense.
Why almost every cell is zero
A document uses only a few of the words in the vocabulary. A typical news article has a few hundred distinct words. The vocabulary of a corpus of news articles can hold hundreds of thousands. Each row of the document-term matrix therefore has a handful of nonzero cells and a very large number of zeros.
Word frequencies make this worse. In natural language a small set of words (the, of, and) appears everywhere, and most other words are rare. Many terms occur in only one or two documents. Adding documents keeps adding new rare terms, so the vocabulary grows faster than the length of any one document.
The tiny three-document corpus used earlier is not very sparse. The 3 x 8 matrix has 14 nonzero cells out of 24. The effect appears at realistic sizes, as the table shows.
| Corpus | Documents | Vocabulary | Distinct words per document | Share of nonzero cells |
|---|---|---|---|---|
| Toy example | 3 | 8 | 4 to 5 | about 58% |
| Product reviews | 100,000 | 50,000 | about 60 | about 0.1% |
| News articles | 100,000 | 200,000 | about 100 | about 0.05% |
The cost of a dense matrix
A dense matrix stores every cell, zeros included. Take the news example: 100,000 x 200,000 cells at 8 bytes each is 160 GB. That does not fit in the memory of most machines.
A sparse matrix stores only the nonzero cells and where they are. With about 100 nonzero cells per document there are 10 million nonzero values in total. Each needs 8 bytes for the value and 4 for its column position, roughly 120 MB. That is more than 1,000 times smaller, and it also makes many operations faster because they skip the zeros.
Compressed sparse row format
scikit-learn vectorizers return a scipy.sparse.csr_matrix. CSR stands for compressed sparse row. It keeps three one-dimensional arrays:
data: the nonzero values, row by row.indices: the column index of each value indata.indptr: for each row, the position indatawhere that row starts. It has one more entry than there are rows, and the last entry equals the total number of stored values.
The nonzero values of row i are data[indptr[i]:indptr[i+1]]. Their columns are indices[indptr[i]:indptr[i+1]].
from sklearn.feature_extraction.text import CountVectorizer
docs = [
"the cat sat on the mat",
"the dog sat on the log",
"the cat chased the dog",
]
vec = CountVectorizer()
X = vec.fit_transform(docs)
print(type(X).__name__)
print(X.shape, X.nnz)
print(f"density: {X.nnz / (X.shape[0] * X.shape[1]):.2f}")
print("data: ", X.data)
print("indices:", X.indices)
print("indptr: ", X.indptr)The output is:
csr_matrix
(3, 8) 14
density: 0.58
data: [1 1 1 1 2 1 1 1 1 2 1 1 1 2]
indices: [0 4 5 6 7 2 3 5 6 7 0 1 2 7]
indptr: [ 0 5 10 14]The vocabulary is cat, chased, dog, log, mat, on, sat, the, so column 0 is "cat" and column 7 is "the". Row 0 spans indptr[0]:indptr[1], which is positions 0 to 4. Its columns are 0, 4, 5, 6, 7 (cat, mat, on, sat, the) with counts 1, 1, 1, 1, 2. That matches the dense row [1 0 0 0 1 1 1 2].
Reading and building a CSR matrix yourself
The arrays are plain NumPy arrays, so you can decode a row into words without making it dense. The second half of this example rebuilds the same matrix from the three arrays.
import numpy as np
from scipy.sparse import csr_matrix
from sklearn.feature_extraction.text import CountVectorizer
docs = [
"the cat sat on the mat",
"the dog sat on the log",
"the cat chased the dog",
]
vec = CountVectorizer()
X = vec.fit_transform(docs)
names = vec.get_feature_names_out()
row = X[1]
for col, value in zip(row.indices, row.data):
print(names[col], value)
manual = csr_matrix((X.data, X.indices, X.indptr), shape=X.shape)
print(np.array_equal(manual.toarray(), X.toarray()))The loop prints dog, log, on, sat and the with their counts. The final line prints True.
Choosing a sparse format
SciPy offers several sparse formats. Each suits a different job.
| Format | Best for | Weak at |
|---|---|---|
| CSR | Row slicing, so picking documents; matrix-vector products; feeding scikit-learn models | Slicing columns; adding new nonzero cells |
| CSC | Column slicing, so picking terms; some solvers | Row slicing |
| COO | Building a matrix from (row, column, value) triples | Arithmetic and slicing |
| LIL | Setting individual cells step by step | Speed on large matrices |
For text features, stay with CSR. Vectorizers produce it, and most estimators accept it. If you need to select columns many times, convert once with X.tocsc().
Operations that destroy sparsity
Sparsity is easy to lose by accident. Three habits to avoid:
- Calling
.toarray()or.todense()on the full matrix. - Centering features by subtracting the mean. Every zero becomes a nonzero number.
StandardScalertherefore refuses sparse input withwith_mean=True. Usewith_mean=False, or skip scaling, since TF-IDF rows are already normalized. - Adding a constant to the matrix, for example
X + 1. SciPy raises an error for this on purpose.
Dense output is also a trap in debugging. To inspect a result, print X.shape, X.nnz and a few decoded rows instead of the whole matrix.
What affects the size
Memory is roughly proportional to nnz, not to the vocabulary size. This explains how settings change cost:
- A larger vocabulary adds columns but costs little if the new terms are rare.
- N-grams raise
nnzquickly, because each document produces many more distinct features. - Pruning with
min_dfandmax_featureslowers the column count and oftennnz. Both are covered in a later chapter. - Default dtypes are
int64for counts andfloat64for TF-IDF. Passingdtype=np.float32to the vectorizer halves the size ofdata.
Exercise
A CSR matrix has 3 rows. Row 0 has 3 nonzero cells, row 1 is entirely zero, and row 2 has 2 nonzero cells. What are nnz and indptr, and what is the length of data?
Show answer
nnz is 5, indptr is [0, 3, 3, 5], and data has length 5. Each entry of indptr is the cumulative count of stored values up to the start of that row. Row 1 is empty, so indptr[1] and indptr[2] are equal.
Exercise
A corpus has 50,000 documents and a vocabulary of 100,000 terms. Each document has about 80 distinct terms. Estimate the memory of the dense int64 matrix and of the CSR matrix, counting 8 bytes per value and 4 bytes per column index, and ignoring indptr.
Show answer
The dense matrix has 50,000 x 100,000 = 5 billion cells at 8 bytes, which is 40 GB. The CSR matrix stores 50,000 x 80 = 4 million values at 12 bytes each, which is about 48 MB. That is roughly 800 times smaller.