Sparse matrices and spatial distances
Quick answer
A sparse matrix stores selected entries and their positions instead of every cell. CSR (compressed sparse row) stores values, column indices and row pointers. It helps when most entries are zero, as with token counts. SciPy spatial.distance computes distances between feature vectors. Match dimensions and units before interpreting a distance. Examples use local Python 3.13.5, SciPy 1.17.0, NumPy 2.3.5 and Matplotlib 3.10.8 as applicable. All fixtures are synthetic; ByteMind library execution is unverified.
Multiply sparse feature counts
Each row is a document and each column a token count. Apply a fixed weight vector without converting the matrix to dense.
import numpy as npfrom scipy.sparse import csr_arrayA = csr_array([[0, 2, 0], [1, 0, 3]])w = np.array([1, 2, 4])print(A.shape, A.nnz)print((A @ w).tolist())print(A.indptr.tolist())Expected output:
(2, 3) 3[4, 13][0, 1, 3]Only three entries are stored. Row pointers mark the start and end of each row’s stored entries. Here nnz equals the number of nonzero values; explicitly stored zeros can also count in nnz.
Compare feature vectors
Use cdist for cross-set distances between rows. Each query has two features in comparable units.
from scipy.spatial.distance import cdistqueries = [[0., 0.], [3., 4.]]centers = [[0., 0.], [0., 4.]]print(cdist(queries, centers, metric='euclidean').tolist())print(cdist(queries, centers, metric='cityblock').tolist())Expected output:
[[0.0, 4.0], [5.0, 3.0]][[0.0, 4.0], [7.0, 3.0]]Euclidean distance uses the square root of squared differences; cityblock (Manhattan) sums absolute differences. The result has one row per query and one column per center.
Common mistakes
Sparse is not always smaller or faster: indices have overhead, and some operations densify. Use @ for matrix multiplication with sparse arrays; * is elementwise. Do not confuse missing measurements with structural zero values. cdist returns a dense pairwise matrix, so its memory grows with both set sizes. Scale features using training data when their units differ.
Practice and next steps
Predict the weight score for [0, 0, 2]. Explain why changing meters to centimeters can alter nearest-neighbor comparisons. The separate pure-Python exercise assesses the underlying calculation, not library execution.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Sparse matrices and spatial distances — knowledge check
Apply scientific computing and visualization reasoning to synthetic examples.
Which operator multiplies a sparse array by a vector as a matrix?
What does CSR indptr encode?
Manhattan distance between (0,0) and (3,4)?
cdist compares 4 queries with 3 centers. What is its shape?
What is a risk of calling toarray on a huge sparse input?