SciPy
01 / 02

Linear Algebra, Sparse & Spatial

Linear Algebra, Sparse & Spatial

Solving Linear Systems

from scipy import linalg
import numpy as np

A = np.array([[3, 1], [1, 2]])
b = np.array([9, 8])

# solve() — faster AND more numerically stable than computing inv(A) @ b,
# especially for ill-conditioned matrices
x = linalg.solve(A, b)

# inv() explicitly computes the inverse — more expensive and less accurate
# for this purpose, avoid unless you actually need the inverse itself
# x_bad = linalg.inv(A) @ b

# Sanity-check numerical reliability before trusting a solve on sensitive data
condition_number = linalg.cond(A)  # high = close to singular, results less trustworthy

Sparse Matrices

from scipy.sparse import csr_matrix

# A one-hot encoded feature matrix: 10,000 columns, a handful nonzero per row.
# Storing this DENSE wastes memory/compute proportional to the FULL size —
# sparse formats only store the nonzero values and their positions.
sparse_features = csr_matrix(dense_one_hot_array)
print(sparse_features.data.nbytes)  # tiny compared to the dense equivalent

# Most scikit-learn estimators accept sparse matrices directly as input

Spatial & Interpolation

from scipy.spatial.distance import cdist
from scipy.interpolate import interp1d

# Pairwise distances between two sets of points
distances = cdist(points_a, points_b)

# Estimate values between known data points
f = interp1d(x_known, y_known, kind='cubic')
y_estimated = f(2.5)

from scipy.signal import find_peaks
peak_indices, _ = find_peaks(noisy_signal, height=0.5)

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free