observations (x, y)
│
▼
fit ──► parameters (slope, intercept)
│
▼
predict(x) ──► predictions
│
▼
evaluate(y, predictions) ──► MSE + checks
baseline = np.full_like(y, y.mean()) # mean-only baseline to compare against
Training MSE checks the implementation, not generalization (that needs held-out data).
Instructor walkthrough: solution notebook §1. Population factors cancel:
def fit_linear_py(x_values, y_values):
if not x_values or len(x_values) != len(y_values):
raise ValueError("x and y need equal non-zero lengths")
x_mean = mean_py(x_values)
y_mean = mean_py(y_values)
numerator = sum(
(x_i - x_mean) * (y_i - y_mean)
for x_i, y_i in zip(x_values, y_values)
)
denominator = sum((x_i - x_mean) ** 2 for x_i in x_values)
if denominator == 0.0:
raise ValueError("x must vary")
slope = numerator / denominator
intercept = y_mean - slope * x_mean
return slope, intercept
Time: 30 minutes · Work: pairs · Implement in session01_starter.ipynb:
fit_linear_numpy(x, y) -> (slope, intercept)
predict_numpy(x, slope, intercept) -> predictions
mse_numpy(y, predictions) -> mse
Completion checks:
assert predictions_np.shape == y.shape == (50,)
assert np.isfinite([slope_np, intercept_np, mse_value_np]).all()
assert mse_value_np < mse_numpy(y, np.full_like(y, y.mean()))
Expected: slope ≈ 2.5242, intercept ≈ 0.5373, MSE ≈ 2.2939.
Also test invalid inputs: empty, mismatched, 2-D, or constant x.
After 10 minutes: shapes
x_centered = x - x.mean()
y_centered = y - y.mean()
After 20 minutes: parameters
slope_np = np.mean(x_centered * y_centered) / np.mean(x_centered**2)
intercept_np = y.mean() - slope_np * x.mean()
Final check
The model MSE should beat the mean baseline MSE, approximately 51.4769.
def fit_linear_numpy(x, y):
x = np.asarray(x, dtype=np.float64)
y = np.asarray(y, dtype=np.float64)
if x.ndim != 1 or y.ndim != 1 or x.shape != y.shape or x.size == 0:
raise ValueError("x and y need equal non-zero 1D shapes")
x_centered = x - x.mean()
denominator = np.mean(x_centered**2)
if denominator == 0.0:
raise ValueError("x must vary")
slope = np.mean(x_centered * (y - y.mean())) / denominator
intercept = y.mean() - slope * x.mean()
return float(slope), float(intercept)
slope_np, intercept_np = fit_linear_numpy(x, y)
predictions_np = intercept_np + slope_np * x
mse_value_np = np.mean((y - predictions_np) ** 2)
# (slope, intercept, MSE) ≈ (2.5242, 0.5373, 2.2939)
design = np.column_stack([x, np.ones_like(x)])
(slope_ls, intercept_ls), *_ = np.linalg.lstsq(
design, y, rcond=None
)
assert design.shape == (50, 2)
assert np.allclose(
[slope_np, intercept_np], [slope_ls, intercept_ls],
rtol=1e-12, atol=1e-12,
)
lstsq solves the least-squares problem directly. Do not form an explicit inverse just to obtain these coefficients.
A plot checks structure; numerical assertions check values.
Answer individually before discussing:
def predict(x, slope, intercept): return ...; for x.shape == (50,), what is the output shape?column_stack([x, ones_like(x)]), and why include ones?(50, 1) predictions from (50,) targets?default_rng(42), and why compare MSE with a mean baseline?lstsq, and name one invariant to check first.Be ready to justify each answer using shapes or the workflow contract.
return intercept + slope * x; output shape (50,).(50, 2); the ones multiply the intercept.(50, 50), a silent and serious bug.default_rng(42) reproduces data; the model must beat a constant.lstsq; check shapes and finiteness first.reproduce → validate → fit → predict → compare → verify/plot → interpret
Next: held-out validation, then optimization and regularization.
Not part of the 180-minute lesson. Use these slides after class or when a question comes up.
uvReference only, not part of the 180-minute lesson.
pybind11 exposes C code to Python.Rule of thumb: keep hot loops in compiled kernels (NumPy, Numba, or a binding), not in pure Python.
Reference only.
Compiled languages (C, C++, Rust, …) are translated to machine code before running. They are fast at runtime, but you recompile after each change.
Interpreted languages (Python, JavaScript, R, …) are run directly by an interpreter or virtual machine. They are easier to test and debug, there is no manual compile step, but raw loops are usually slower.
Python trades a little raw speed for much shorter, easier-to-read code. That is exactly why we delegate the hot loops to libraries like NumPy.
Python's dot product:
x = [1, 2, 3]
y = [4, 5, 6]
dot = sum(x_i * y_i for x_i, y_i in zip(x, y))
print(dot) # 32
python my_script.py
The same dot in C++ needs a separate compile step first:
g++ dot.cpp -o dot && ./dot
uvEnvironment setup (uv init, uv sync, uv run, lockfiles, and the full toolbox) is covered in the Python tooling & environments part that follows. The short version for this course: uv sync, then always uv run ….
Use when stuck, not as a cover-to-cover read:
A companion reference on running, managing, and shipping Python. Separate from the 3-hour lesson and not timed.
venv, uv, conda, …)uv workflow for this courseThe most common Python is CPython: an interpreter written in C that compiles your source to bytecode and runs it on a virtual machine.
.py file.| Way | Command / tool | Best for |
|---|---|---|
| Script | python hello.py |
a whole program end to end |
| Notebook | Jupyter .ipynb |
exploring, mixing text + code, fast feedback |
| REPL | python (interactive session) |
tiny experiments, checking one expression |
For short questions use the REPL. For a finished pipeline use a script. For today's guided practice use the notebooks.
A script runs top to bottom; its state resets each run. Great for reproducibility and automation.
A notebook holds cells you run in any order, and its outputs persist. Great for exploration, but order-dependent state can bite you:
cell order is not guaranteed to match "top to bottom"
Rule: explore in a notebook, commit a script for anything you re-run or hand to someone else.
Find the interpreter and its version:
which python # path of the python on your PATH
python --version # e.g. Python 3.12.11
Inside a virtual environment these point at the environment's interpreter instead of the system one. That is exactly the point.
Different projects need different versions of the same packages.
numpy 1.26numpy 2.0Installing both "globally" is how you break your own machine. The fix is isolated environments: each project gets its own interpreter + dependency set.
A lock file (uv.lock, poetry.lock, requirements.txt) records the exact versions so anyone can rebuild the same environment.
| Tool | Role |
|---|---|
venv |
built-in, minimal virtual environment (python -m venv) |
| pip | installs packages from PyPI into the current environment |
uv |
fast venv + pip + version/lockfile in one tool (used here) |
| pyenv | switch between multiple Python versions |
| conda / mamba / pixi | environments + compiled/scientific packages, beyond Python only |
| Poetry / PDM | full project manager: deps + build + lockfile |
You do not need all of these. Pick one workflow and stay consistent.
venv, the built-in baselinepython -m venv .venv # create an isolated environment in .venv
source .venv/bin/activate # activate it (Windows: .venv\Scripts\activate)
pip install numpy # installs only inside this environment
Common pitfall: forgetting to activate, so pip installs to the system interpreter. uv avoids most of this by defaulting to the project environment.
uv, one fast tool with a lockfileuv manages the environment, resolves versions, and records a uv.lock.
uv sync # create env + install pinned deps from uv.lock
uv add numpy # add a dep, update uv.lock
uv run python hello.py # run in the project env regardless of activation
uv run jupyter lab # start the teaching notebooks
Reproducible and fast; this is the workflow this repository uses.
uv init, create a new projectuv init my_project
This creates a standard layout:
my_project/
├── pyproject.toml # metadata + direct dependencies
├── .python-version # the Python version for this project
├── main.py # a "Hello, world!" example entry point
├── README.md
└── .gitignore
It also initializes a git repo (.git/) and a uv.lock appears on the first uv sync.
uv python and uv add, set up the projectPick a Python version and add libraries:
uv python install 3.12
uv add numpy
uv add records the dependency in pyproject.toml and resolves uv.lock.
Inside the project you will find:
pyproject.toml # metadata + direct dependencies
uv.lock # exact resolved versions (commit this)
.python-version # the Python version (3.12 for this course)
Anyone can run uv sync from a clean clone and get the same environment. That is what "reproducible" means.
.python-version and uv.lock matterWithout pinned versions, "it works on my machine" is a coin flip.
# wrong: whatever is installed
uv run python script.py
# right: the exact locked environment
uv sync --locked # fail if uv.lock would change
uv run python script.py
Reproducibility = deterministic data, pinned languages, pinned tools, pinned versions.
which python, uv, and PATH in one line of mental modelwhich python tells you the first match on PATH..venv/bin (or Scripts) ahead of the system interpreter.uv run uses the project interpreter without you activating anything.So the golden habit for this course: uv sync once, then always uv run …. No manual activation needed.
uv documentationSkim when needed; do not read like a book.
Presenter cue: spend 2 minutes launching, then 7 minutes on pair coding. Move to the hint after 3 minutes of coding. Require both assertions and at least one invalid-input check.
Debrief cue: ask why the length check must happen before zip. Use the remaining 2 minutes to connect list arithmetic to NumPy vectorization.
Presenter cue: spend 2 minutes launching, then 7 minutes on pair work. Require students to write the expected shapes before coding. Move to the hint after 3 minutes of coding.
Debrief cue: ask which axis was consumed and why keepdims preserves broadcastability. The pairwise extension is for fast finishers only.
Presenter cue: spend 3 minutes launching. At minute 10 move to the first hint; at minute 20 reveal the parameter formulas. Stop at 30 minutes and continue with the supplied solution.
Debrief cue: check shapes, invalid inputs, and baseline comparison before discussing exact coefficients. Preserve the following 10-minute solver and numerical-practice block.
Assessment cue: require individual answers before pair discussion. Do not reveal the answers slide early.