Vectorized linear algebra and random generators
Quick answer
Vectorized code applies numerical operations to arrays rather than explicitly looping over Python elements. Matrix multiplication (@) contracts compatible inner dimensions, while * multiplies element by element. NumPy’s Generator produces pseudorandom values for controlled experiments; a seed initializes its state, not a guarantee of identical results across all library versions or hardware.
Predict several samples together
For X with shape (n, d) and weights w with shape (d,), X @ w gives one score per row. Add scalar b using broadcasting. np.linalg.norm computes a vector norm here; the earlier linear algebra chapter explains its meaning.
import numpy as npx = np.array([[2, 1], [4, 3], [0, 5]], dtype=np.float64)w = np.array([3, -1], dtype=np.float64)b = 2.0print((x @ w + b).tolist())print((x * w).tolist())print(round(float(np.linalg.norm(w)), 3))Expected output (local NumPy 2.3.5):
[7.0, 11.0, -3.0][[6.0, -1.0], [12.0, -3.0], [0.0, -5.0]]3.162The first prediction is 23 + 1(-1) + 2 = 7. Elementwise multiplication retains both feature contributions instead of summing them.
Control random generator state
Construct two separate generators from the same seed for a reproducibility check. .integers(low, high, size=...) draws integers with an exclusive upper bound by default. Compare arrays using np.array_equal rather than relying on the truth value of an array.
import numpy as npa = np.random.default_rng(42)b = np.random.default_rng(42)x = a.integers(0, 10, size=(2, 3))y = b.integers(0, 10, size=(2, 3))print(x.shape, np.array_equal(x, y))print(bool(np.all((x >= 0) & (x < 10))))print(np.array_equal(a.integers(0, 10, size=5), b.integers(0, 10, size=5)))Expected output (local NumPy 2.3.5):
(2, 3) TrueTrueTrueBoth streams consume the same calls in the same order in this environment. Independent generators with identical seeds produce matching streams, not independent statistical samples.
Common mistakes
* does not implement matrix multiplication. Do not broadcast a bias of the wrong shape: adding (n, 1) to (n,) yields (n, n). Use np.linalg.solve for suitable square nonsingular systems rather than forming an inverse; for other systems choose a method appropriate to rank and shape. Vectorization often reduces Python overhead but can allocate large temporaries; np.vectorize is mostly a convenience wrapper, not an automatic speedup. Record NumPy version, generator algorithm, seed, call order and dtype; benchmark representative shapes instead of promising a fixed speed gain.
Practice and next steps
Calculate two linear scores by hand and compare with X @ w + b. For the chapter project, fit a standardizer on training rows, transform held-out rows, and compare vectorized results with a loop. Next: pandas data handling and tabular quality.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Vectorized linear algebra and random generators — knowledge check
Apply array reasoning to new synthetic feature tables.
What is the shape of X @ w if X is (5, 3) and w is (3,)?
For row [2, 4], weights [3, -1] and bias 5, what is the score?
What does X * w return for X (5, 3), w (3,)?
What do separate default_rng instances with equal seeds and identical calls demonstrate locally?
Why might a vectorized algorithm still use too much memory?