Python Master Course V2 — 122. Linear Algebra for Data and Models
What you will be able to do
- Interpret vectors, matrices and dot products
- Apply matrix multiplication, norms and projections
- Use least-squares solving and recognize unstable systems
Prerequisites: 121: NumPy arrays; Basic arithmetic and school algebra; introduce notation explicitly.
Your local workspace
Use CPython 3.11 or newer; Python 3.12 or 3.13 is a practical baseline. This lesson uses only your CPU and artificial data. Create a new folder named lesson122, open a terminal there, and keep all named files inside it. Do not use real customer records. Commands marked shell belong in the terminal; Python belongs in the named .py files. Run commands from this folder unless a step explicitly changes directories.
Create an isolated environment with python -m venv .venv. On macOS/Linux activate it with source .venv/bin/activate; in Windows PowerShell use .venv\Scripts\Activate.ps1. If activation is restricted, invoke .venv\Scripts\python.exe directly rather than changing security settings. Use the interpreter that your installation calls python or python3 consistently. Installation needs internet access once; all lesson exercises run locally.
python -m pip install numpy pytestThe examples target the documented APIs linked below. Record your installed versions with python -m pip freeze when preserving a result. Expected outputs describe what the supplied deterministic examples should produce; they are not a claim that your environment has already passed a test.
Linear algebra describes combinations of measurements
A vector is an ordered collection of numbers. It may represent a point, a direction, a row of features or a set of coefficients; its meaning comes from the problem. A matrix arranges numbers in rows and columns. In this lesson, X has one row per observation and one column per feature, while beta contains one coefficient per feature. The prediction X @ beta is therefore one number per observation.
The dot product multiplies corresponding entries and adds them. If a feature vector is [1, 3] and coefficients are [2, 4], its prediction is 1*2 + 3*4 = 14. The leading feature 1 lets a coefficient act as an intercept. NumPy's * multiplies elementwise, whereas @ performs the dot or matrix product appropriate to operand dimensions. Check dimensions before calculating: (n, p) @ (p,) produces (n,).
A norm measures size. The Euclidean norm is the square root of the sum of squared entries, corresponding to ordinary geometric length. A residual vector is observed values minus predictions. Its norm summarizes discrepancy in the original units; the sum of squared residuals has squared units. Neither by itself says whether a model will predict new observations well.
Least squares chooses coefficients that minimize squared residuals. Usually there are more observations than coefficients, and no line passes through every point. numpy.linalg.lstsq solves this problem without requiring you to construct an inverse. Explicitly calculating inverse(X.T @ X) is both unnecessary and potentially less stable. If columns are dependent, different coefficients can represent the same predictions; rank and singular values help reveal that ambiguity.
Fit a line and verify the geometry
import numpy as np
x = np.array([0.0, 1.0, 2.0, 3.0])
y = np.array([1.0, 3.0, 5.0, 7.0])
X = np.column_stack([np.ones_like(x), x])
beta, reported_residuals, rank, singular_values = np.linalg.lstsq(X, y, rcond=None)
predicted = X @ beta
residual = y - predicted
print(X.shape)
print([round(float(value), 6) for value in beta])
print(rank)
print(bool(np.allclose(predicted, y, rtol=1e-12, atol=1e-12)))
print(f"{np.linalg.norm(residual):.6f}")Expected output
(4, 2)
[1.0, 2.0]
2
True
0.000000The displayed zero is rounded numerical error, not a claim of exact arithmetic. Compute residuals yourself when reporting them: lstsq may return an empty residual-summary array for some rank or shape cases even when residuals can be calculated. The returned rank here is two because the constant and varying x columns provide independent directions.
import numpy as np
vector = np.array([3.0, 4.0])
unit_direction = np.array([1.0, 0.0])
projection = np.dot(vector, unit_direction) * unit_direction
remainder = vector - projection
print(float(np.linalg.norm(vector)))
print(projection.tolist())
print(float(np.dot(remainder, unit_direction)))Expected output
5.0
[3.0, 0.0]
0.0Projection keeps the component along a chosen unit direction. The remainder is perpendicular to it, which the zero dot product checks. With a non-unit direction u, divide by dot(u, u); a zero vector cannot define a direction. This geometry explains why least-squares residuals are orthogonal to the fitted column space, up to numerical tolerance.
Guided lab: compare independent and nearly dependent columns
Save conditioning.py. Both designs have four rows and two columns. In the first, columns describe an intercept and a changing measurement. In the second, the second column is almost a copy of the first. The condition number measures sensitivity of this matrix problem in a specified norm. A very large value warns that small input changes can produce large coefficient changes; it is not a universal pass/fail cutoff independent of units and purpose.
import numpy as np
x = np.array([0.0, 1.0, 2.0, 3.0])
good = np.column_stack([np.ones_like(x), x])
near = np.column_stack([np.ones_like(x), 1.0 + 1e-8 * x])
y = np.array([1.0, 3.0, 5.0, 7.0])
perturbed = y + np.array([0.0, 0.0, 0.0, 1e-5])
print(bool(np.linalg.cond(near) > np.linalg.cond(good)))
for label, design in [("independent", good), ("nearly dependent", near)]:
original = np.linalg.lstsq(design, y, rcond=None)[0]
changed = np.linalg.lstsq(design, perturbed, rcond=None)[0]
print(label)
print("coefficient change:", np.linalg.norm(changed - original))
print("prediction change:", np.linalg.norm(design @ changed - design @ original))The first printed boolean should be True. The following numerical diagnostics are measurements from your environment, so inspect and record them rather than copying a promised decimal transcript. Compare coefficient sensitivity with prediction sensitivity: unstable coefficients can partly cancel and still yield similar fitted predictions on the observed design.
Add a perfectly duplicated column and inspect rank. Explain why two separate coefficients cannot be uniquely interpreted when their features are identical. Then center and scale the original x values, refit and translate predictions back. Scaling can improve numerical conditioning caused by units, but cannot recover genuinely missing independent information.
Write tests for the known exact line, wrong target length and non-finite inputs. For a reusable fitting function, validate two-dimensional X, one-dimensional y, matching observation counts and finite values before invoking the solver. Numerical library exceptions are useful diagnostics, but clear boundary checks make your own contract easier to understand.
What a fitted coefficient does and does not mean
A coefficient is attached to the exact feature representation used. A distance coefficient measured per kilometer changes numerically if distance is expressed in meters. Correlated or nearly dependent features make separate coefficient interpretations fragile. A fitted line through observational data also does not establish causality; the arithmetic cannot remove confounding by itself.
Residual size on the same observations used for fitting is training fit. A perfect synthetic line is intentionally easy and says nothing about future noisy data. Later lessons separate training and held-out evaluation. Here the goal is to understand dimensions, projection and sensitivity before treating a numerical solver as a model-building shortcut.
Questions worth asking
Why add a column of ones?
It provides an intercept term. Multiplying that column by its coefficient adds the same baseline to every prediction. Without it, the fitted relationship is constrained through the origin, which is a different model and may contradict the problem.
Why is @ different from *?
For matrices, @ combines rows and columns through sums of products. * multiplies matching entries element by element, with broadcasting where allowed. Both may execute without errors while meaning different things, so shapes and intended algebra must guide the choice.
Can an empty residuals result mean perfect fit?
Not necessarily. lstsq returns its residual summary only under certain shape and rank conditions. Compute y – X @ beta directly to inspect actual residuals, then interpret them with the model and numerical tolerance.
Why avoid explicitly inverting X.T @ X?
The normal-equation construction can worsen conditioning and inversion is unnecessary for solving least squares. A solver handles the numerical problem more appropriately and reports rank information. Prefer solving for coefficients rather than building an inverse as an intermediate artifact.
Does a large condition number mean every prediction is useless?
No. It warns about sensitivity, especially of coefficients, under perturbations. Some combinations or predictions may remain relatively stable. Inspect the actual use case, feature scaling and perturbation behavior rather than applying an unexplained threshold mechanically.
Can scaling fix duplicate features?
No. Scaling changes units and may improve numerical balance, but two identical columns still contain redundant information. Removing or redefining redundant features requires a modeling decision and cannot be solved by multiplying them by constants.
Practice, then compare your solution
1. Predict by hand
For features [1, 5] and coefficients [2, 3], compute the prediction.
Worked solution and reasoning
The dot product is 1*2 + 5*3 = 17. The first term is the intercept and the second is the contribution from the measured feature. A hand calculation is a useful independent check for array code.
2. Rank defect
What happens if every x value equals 2?
Worked solution and reasoning
The x column is twice the constant column, so the two columns are dependent. Intercept and slope cannot be identified separately from those observations. Many coefficient pairs give the same constant prediction.
Mastery checkpoint
Draw the dimensions of X, beta, predictions and residuals. Reproduce the exact-line example, demonstrate projection and explain the near-dependent design diagnostics. Use a least-squares solver, inspect rank and distinguish numerical fit from predictive or causal evidence.
Official documentation and next steps
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.