From 2902e34256c5748dd2bf552a03979408b80e8e89 Mon Sep 17 00:00:00 2001 From: Eric Date: Mon, 6 Apr 2026 15:54:41 -0400 Subject: [PATCH] NN lecture updates - add noisy data fit to README - add noisy data notebook - add noisy standalone python script - References and edits to README --- 05-neural-networks/README.md | 90 ++++++----- 05-neural-networks/nn_noisy.py | 163 +++++++++++++++++++ 05-neural-networks/nn_noisy_workshop.ipynb | 179 +++++++++++++++++++++ 3 files changed, 388 insertions(+), 44 deletions(-) create mode 100644 05-neural-networks/nn_noisy.py create mode 100644 05-neural-networks/nn_noisy_workshop.ipynb diff --git a/05-neural-networks/README.md b/05-neural-networks/README.md index d4b81c7..d4cca36 100644 --- a/05-neural-networks/README.md +++ b/05-neural-networks/README.md @@ -19,9 +19,9 @@ Build a neural network from scratch to understand the core mechanics behind LLMs --- -Everything we've done in this workshop is **machine learning** (ML) — the practice of training models to learn patterns from data rather than programming rules by hand. LLMs are one (very large) example of ML, built on neural networks. Throughout this workshop, we've used ML terms like *model weights*, *training loss*, *gradient descent*, and *overfitting* — often without defining them precisely. In Part I, we watched nanoGPT's training loss decrease over 2000 iterations. In Part II, we saw that models have many millions (even billions) of parameters. In Parts III and IV, we used embedding models that map text into vectors — another ML technique. +Everything we've done in this workshop is **machine learning** (ML) — the practice of training models to learn patterns from data rather than programming rules by hand. LLMs are one (very large) example of ML built on neural networks. Throughout this workshop, we've used ML terms like *model weights*, *training loss*, *gradient descent*, and *overfitting*, often without defining them precisely. In Part I, we watched nanoGPT's training loss decrease over 2000 iterations. In Part II, we saw that models have many millions (even billions) of parameters. In Parts III and IV, we used embedding models that map text into vectors — another ML technique. -In this section, we step back from language and build a neural network ourselves — small enough to understand every weight, but powerful enough to learn a real physical relationship. The goal is to make the ML concepts behind LLMs concrete. +In this section, we step back from language and build a neural network ourselves. It will be small enough to understand every weight, but powerful enough to "learn" a real physical relationship. The goal is to make the ML concepts behind LLMs concrete. Our task: fit the ideal gas heat capacity $C^*_p(T)$ of nitrogen gas using data from the [NIST Chemistry WebBook](https://webbook.nist.gov/). This is a function that chemical engineers know well. Textbooks like *Chemical, Biochemical, and Engineering Thermodynamics* (a UD favorite) typically fit it with a polynomial: @@ -34,6 +34,17 @@ Can a neural network learn this relationship directly from data? All dependencies (`numpy`, `torch`, `matplotlib`) are installed by `uv sync`. (See the main [README](../README.md).) +### Notebooks and scripts + +The hands-on work for this section lives in two Jupyter notebooks: + +- **`nn_workshop.ipynb`** — build and train the network (polynomial baseline, numpy from scratch, PyTorch) +- **`nn_noisy_workshop.ipynb`** — add noise, observe overfitting, learn about train/validation splits and early stopping + +Open them with `jupyter notebook` or in VS Code. The notebooks are designed to be worked through in class, with discussion prompts at key points. + +Standalone Python scripts (`nn_numpy.py`, `nn_torch.py`, `nn_noisy.py`) contain the same code as the notebooks in a clean, single-file format. These are useful as a reference. + ## 2. The data The file `data/n2_cp.csv` contains 35 data points: the isobaric heat capacity of N₂ gas at 1 bar from 300 K to 2000 K, from the NIST WebBook. @@ -69,7 +80,7 @@ Here's what happens at each step: $$z_j = w_j \cdot x + b_j \qquad a_j = \tanh(z_j)$$ -where $w_j$ and $b_j$ are the weight and bias for neuron $j$. The activation function (here, `tanh`) introduces **nonlinearity**. Without it, stacking layers would just produce another linear function, no matter how many layers we use. +where $w_j$ and $b_j$ are the weight and bias for neuron $j$. The activation function (here, `tanh`) acts on the pre-activation value $z_j$ and introduces **nonlinearity**. Without it, stacking layers would just produce another linear function, no matter how many layers we use. **Step 2: Output layer.** The output is a weighted sum of the hidden activations: @@ -80,9 +91,9 @@ This is a linear combination. There is no activation on the output, since we wan ### Counting parameters With 10 hidden neurons: -- `W1`: 10 weights (input -> hidden) +- `W1`: 10 weights, $w_j$ (input -> hidden) - `b1`: 10 biases (hidden) -- `W2`: 10 weights (hidden -> output) +- `W2`: 10 weights, $W_j$ (hidden -> output) - `b2`: 1 bias (output) - **Total: 31 parameters** @@ -97,11 +108,11 @@ Training means finding the values of all 31 parameters that make the network's p ### Loss function -We need a number that says "how wrong is the network?" for a given set of paratmers. The **mean squared error** (MSE) is a natural choice here: +We need a number that says "how wrong is the network?" for a given set of parameters. The **mean squared error** (MSE) is a natural choice here: $$L = \frac{1}{N} \sum_{i=1}^{N} (\hat{y}_i - y_i)^2$$ -This is the same kind of loss we watched decrease during nanoGPT training in Part I (though nanoGPT uses cross-entropy loss, which is appropriate for classification over a vocabulary). +This is the same MSE you've used in non-linear curve fitting — the sum of squared residuals divided by the number of points. The only difference is that here the "model" is a neural network instead of a polynomial or equation of state. It is also the same kind of loss we watched decrease during nanoGPT training in Part I (though nanoGPT uses cross-entropy loss, which is appropriate for classification over a vocabulary). ### Backpropagation @@ -126,46 +137,26 @@ One full pass through these three steps (forward -> loss -> backward -> update) In nanoGPT, the training loop in `train.py` does exactly the same thing, but with the AdamW optimizer (a fancier version of gradient descent) and batches of data instead of the full dataset. -## 5. Running the numpy version +## 5. The numpy version -```bash -python nn_numpy.py -``` +Work through sections 1–3 of `nn_workshop.ipynb` to build and train the network from scratch in numpy. You should see the training loss drop rapidly in the first 1000 epochs before leveling off, and the network's prediction closely tracking the NIST data points. ``` Epoch 0 Loss: 0.283941 Epoch 500 Loss: 0.001253 Epoch 1000 Loss: 0.000412 -Epoch 1500 Loss: 0.000178 -Epoch 2000 Loss: 0.000082 -Epoch 2500 Loss: 0.000040 -Epoch 3000 Loss: 0.000021 -Epoch 3500 Loss: 0.000012 -Epoch 4000 Loss: 0.000008 -Epoch 4500 Loss: 0.000005 +... Epoch 4999 Loss: 0.000004 - -Final loss: 0.000004 -Network: 1 input -> 10 hidden (tanh) -> 1 output -Total parameters: 31 ``` -The script produces a plot (`nn_fit.png`) showing the fit and the training loss curve. You should see the network's prediction closely tracking the NIST data points, and the loss dropping rapidly in the first 1000 epochs before leveling off. - -> **Exercise 1:** Read through `nn_numpy.py` carefully. Identify where each of the following happens: (a) forward pass, (b) loss calculation, (c) backpropagation, (d) gradient descent update. Annotate your copy with comments. +> **Exercise 1:** Read through the numpy training cells carefully. Identify where each of the following happens: (a) forward pass, (b) loss calculation, (c) backpropagation, (d) gradient descent update. > **Exercise 2:** Change the number of hidden neurons `H`. Try 2, 5, 10, 20, 50. How does the fit change? How many parameters does each network have? At what point does adding more neurons stop helping? ## 6. The PyTorch version -Now look at `nn_torch.py`. It does the same thing, but in about half the code: - -```bash -python nn_torch.py -``` - -Compare the two scripts side by side. The key differences: +Now work through section 4 of `nn_workshop.ipynb`. The same network, but in about half the code. Compare the numpy and PyTorch cells side by side. The key differences: | | numpy version | PyTorch version | |---|---|---| @@ -177,17 +168,9 @@ Compare the two scripts side by side. The key differences: PyTorch's `loss.backward()` computes all the gradients we wrote out by hand, automatically. This is called **automatic differentiation**. It's what makes training networks with millions of parameters feasible. -The `nn.Sequential` definition: +The `nn.Sequential` definition uses the same PyTorch building blocks as nanoGPT's `model.py` (`nn.Linear` layers and activation functions), just with more layers, attention mechanisms, and a much larger vocabulary. -```python -model = nn.Sequential( - nn.Linear(1, H), # input -> hidden (W1, b1) - nn.Tanh(), # activation - nn.Linear(H, 1), # hidden -> output (W2, b2) -) -``` - -looks simple here, but it uses the same PyTorch building blocks as nanoGPT's `model.py` (`nn.Linear` layers and activation functions) just with more layers, attention mechanisms, and a much larger vocabulary. +Section 5 of the notebook compares all three approaches (polynomial, numpy NN, PyTorch NN) on the same plot, and section 6 tests how they extrapolate outside the training range. > **Exercise 3:** In the PyTorch version, replace `nn.Tanh()` with `nn.ReLU()` or `nn.Sigmoid()`. How does the fit change? Why might different activation functions work better for different problems? @@ -204,7 +187,7 @@ Both scripts normalize the input ($T$) and output ($C_p$) to the range [0, 1] be Try it yourself: -> **Exercise 5:** Comment out the normalization in `nn_numpy.py` (use `T_raw` and `Cp_raw` directly). What happens to the training loss? Can you fix it by changing the learning rate? +> **Exercise 5:** In the notebook, comment out the normalization (use `T_raw` and `Cp_raw` directly). What happens to the training loss? Can you fix it by changing the learning rate? ## 8. Overfitting @@ -215,6 +198,24 @@ With 31 parameters and 35 data points, our network is close to the edge. What ha This is **overfitting** — the network memorizes the training data but fails to generalize. It's the same concept we discussed in Part I when nanoGPT's validation loss started increasing while the training loss kept decreasing. +### Overfitting with noisy data + +The clean NIST data masks the overfitting problem. The network learns a smooth function because the data *is* smooth. Real experimental data has noise. What happens then? + +Open **`nn_noisy_workshop.ipynb`** to explore this. The notebook adds Gaussian noise to the $C_p$ data and introduces a **train/validation split**: 26 points for training, 9 held out for validation. + +Watch the two loss curves as you work through it. Training loss keeps dropping as the network gets better and better at fitting the noisy training points. But at some point, the **validation loss stops decreasing and starts increasing**. This is the overfitting signal: the network is learning the noise, not the underlying physics. + +The epoch where validation loss is lowest is where you'd want to stop training. This is **early stopping**, and it's exactly what nanoGPT's `train.py` does in our LLM lesson. The program saves a checkpoint whenever the validation loss reaches a new minimum. If training runs too long past that point, the model gets worse at predicting new data, even as it gets better at memorizing the training data. + +> **Exercise 7:** Work through `nn_noisy_workshop.ipynb` with the default `noise_scale = 0.02`. Where does the validation loss start increasing? How does the best-model fit compare to the true NIST data? + +> **Exercise 8:** Increase `noise_scale` to 0.05 and then 0.1. How does the fit change? At what noise level does the network produce clearly unphysical predictions? + +> **Exercise 9:** With `noise_scale = 0.05`, try increasing `H` to 50. The network now has 151 parameters for 26 training points. Does overfitting get better or worse? Why? + +> **Exercise 10:** Compare the final model (trained to the end) with the best model (saved at the lowest validation loss). The notebook does this in section 6. Which is closer to the true curve? Why? + In practice, we combat overfitting with: - More data - Regularization (dropout — remember this parameter from nanoGPT?) @@ -252,5 +253,6 @@ The fundamental loop — forward pass, compute loss, backpropagate, update weigh ### Reading -- The "backpropagation" chapter in Goodfellow, Bengio & Courville, *Deep Learning* (2016), freely available at https://www.deeplearningbook.org/ +- Zhang, Lipton, Li & Smola, *Dive into Deep Learning* — interactive, with runnable code in PyTorch: https://d2l.ai +- Goodfellow, Bengio & Courville, *Deep Learning* (2016), freely available at https://www.deeplearningbook.org/ - 3Blue1Brown, *Neural Networks* video series: https://www.youtube.com/playlist?list=PLZHQObOWTQDNU6R1_67000Dx_ZCJB-3pi — excellent visual intuition for how neural networks learn diff --git a/05-neural-networks/nn_noisy.py b/05-neural-networks/nn_noisy.py new file mode 100644 index 0000000..bbb0872 --- /dev/null +++ b/05-neural-networks/nn_noisy.py @@ -0,0 +1,163 @@ +# nn_noisy.py +# +# What happens when we train a neural network on noisy data? +# This script adds Gaussian noise to the Cp data, trains with a +# train/validation split, and plots both loss curves to show overfitting. +# +# CHEG 667-013 +# E. M. Furst + +import torch +import torch.nn as nn +import numpy as np +import matplotlib.pyplot as plt + +# ── Load data ───────────────────────────────────────────────── + +data = np.loadtxt("data/n2_cp.csv", delimiter=",", skiprows=1) +T_raw = data[:, 0] +Cp_raw = data[:, 1] + +# ── Add noise ───────────────────────────────────────────────── + +noise_scale = 0.02 # kJ/kg/K — try 0.01, 0.02, 0.05, 0.1 +rng = np.random.default_rng(seed=42) +Cp_noisy = Cp_raw + rng.normal(scale=noise_scale, size=Cp_raw.size) + +# ── Train/validation split ──────────────────────────────────── +# +# Hold out every 4th point for validation. This gives us 26 training +# points and 9 validation points — enough to see the overfitting signal. + +val_mask = np.zeros(len(T_raw), dtype=bool) +val_mask[::4] = True +train_mask = ~val_mask + +T_train, Cp_train = T_raw[train_mask], Cp_noisy[train_mask] +T_val, Cp_val = T_raw[val_mask], Cp_noisy[val_mask] + +# ── Normalize to [0, 1] using training set statistics ───────── + +T_min, T_max = T_train.min(), T_train.max() +Cp_min, Cp_max = Cp_train.min(), Cp_train.max() + +def normalize_T(T): + return (T - T_min) / (T_max - T_min) + +def normalize_Cp(Cp): + return (Cp - Cp_min) / (Cp_max - Cp_min) + +def denormalize_Cp(Cp_norm): + return Cp_norm * (Cp_max - Cp_min) + Cp_min + +X_train = torch.tensor(normalize_T(T_train), dtype=torch.float32).reshape(-1, 1) +Y_train = torch.tensor(normalize_Cp(Cp_train), dtype=torch.float32).reshape(-1, 1) +X_val = torch.tensor(normalize_T(T_val), dtype=torch.float32).reshape(-1, 1) +Y_val = torch.tensor(normalize_Cp(Cp_val), dtype=torch.float32).reshape(-1, 1) + +# ── Define the network ──────────────────────────────────────── + +H = 10 # try 10, 20, 50 — watch what happens + +model = nn.Sequential( + nn.Linear(1, H), + nn.Tanh(), + nn.Linear(H, 1), +) + +n_params = sum(p.numel() for p in model.parameters()) +print(f"Network: 1 -> {H} (tanh) -> 1") +print(f"Parameters: {n_params}") +print(f"Training points: {len(T_train)}") +print(f"Validation points: {len(T_val)}") +print(f"Noise scale: {noise_scale} kJ/kg/K\n") + +# ── Training ────────────────────────────────────────────────── + +optimizer = torch.optim.Adam(model.parameters(), lr=0.01) +loss_fn = nn.MSELoss() + +epochs = 10000 +log_interval = 1000 +train_losses = [] +val_losses = [] +best_val_loss = float('inf') +best_epoch = 0 + +for epoch in range(epochs): + # --- Training step --- + model.train() + Y_pred = model(X_train) + train_loss = loss_fn(Y_pred, Y_train) + + optimizer.zero_grad() + train_loss.backward() + optimizer.step() + + # --- Validation step (no gradient computation) --- + model.eval() + with torch.no_grad(): + val_pred = model(X_val) + val_loss = loss_fn(val_pred, Y_val) + + train_losses.append(train_loss.item()) + val_losses.append(val_loss.item()) + + # Track the best validation loss — same idea as nanoGPT's train.py + if val_loss.item() < best_val_loss: + best_val_loss = val_loss.item() + best_epoch = epoch + + if epoch % log_interval == 0 or epoch == epochs - 1: + print(f"Epoch {epoch:5d} Train: {train_loss.item():.6f} " + f"Val: {val_loss.item():.6f}") + +print(f"\nBest validation loss: {best_val_loss:.6f} at epoch {best_epoch}") + +# ── Results ─────────────────────────────────────────────────── + +T_fine = torch.linspace(0, 1, 200).reshape(-1, 1) +model.eval() +with torch.no_grad(): + Cp_pred_norm = model(T_fine) + +T_fine_K = T_fine.numpy() * (T_max - T_min) + T_min +Cp_pred = denormalize_Cp(Cp_pred_norm.numpy()) + +# ── Plot ────────────────────────────────────────────────────── + +fig, axes = plt.subplots(1, 3, figsize=(16, 5)) + +# Left: the fit +ax = axes[0] +ax.plot(T_train, Cp_train, 'ko', markersize=6, label='Train (noisy)') +ax.plot(T_val, Cp_val, 'bs', markersize=6, label='Validation (noisy)') +ax.plot(T_raw, Cp_raw, 'g--', linewidth=1, alpha=0.7, label='True (NIST)') +ax.plot(T_fine_K, Cp_pred, 'r-', linewidth=2, label=f'NN ({H} neurons)') +ax.set_xlabel('Temperature (K)') +ax.set_ylabel('$C_p$ (kJ/kg/K)') +ax.set_title(f'Noisy $C_p(T)$ — noise = {noise_scale}') +ax.legend(fontsize=8) + +# Middle: training loss +ax = axes[1] +ax.semilogy(train_losses, label='Train loss') +ax.set_xlabel('Epoch') +ax.set_ylabel('MSE') +ax.set_title('Training Loss') +ax.legend() + +# Right: train vs. validation loss +ax = axes[2] +ax.semilogy(train_losses, label='Train loss') +ax.semilogy(val_losses, label='Validation loss') +ax.axvline(best_epoch, color='gray', linestyle='--', alpha=0.5, + label=f'Best val (epoch {best_epoch})') +ax.set_xlabel('Epoch') +ax.set_ylabel('MSE') +ax.set_title('Train vs. Validation Loss') +ax.legend(fontsize=8) + +plt.tight_layout() +plt.savefig('nn_fit_noisy.png', dpi=150) +plt.show() diff --git a/05-neural-networks/nn_noisy_workshop.ipynb b/05-neural-networks/nn_noisy_workshop.ipynb new file mode 100644 index 0000000..7ad3f1a --- /dev/null +++ b/05-neural-networks/nn_noisy_workshop.ipynb @@ -0,0 +1,179 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "6e917878", + "source": "# Overfitting and Noisy Data\n\n**CHEG 667-013 — LLMs for Engineers**\n\nIn the previous notebook, we fit clean NIST data for $C_p(T)$ and everything worked beautifully. But real experimental data has noise. What happens to our neural network then?\n\nThis notebook explores:\n1. What noisy data looks like compared to the true signal\n2. Why a neural network can memorize noise instead of learning physics\n3. How a **train/validation split** reveals overfitting\n4. The connection to **early stopping** in nanoGPT's `train.py`", + "metadata": {} + }, + { + "cell_type": "markdown", + "id": "d115b276", + "source": "## 1. Load the clean data and add noise\n\nWe start from the same NIST data as before, then corrupt it with Gaussian noise to simulate experimental error.", + "metadata": {} + }, + { + "cell_type": "code", + "id": "102ce412", + "source": "import numpy as np\nimport matplotlib.pyplot as plt\nimport torch\nimport torch.nn as nn\n\n# Load clean NIST data\ndata = np.loadtxt(\"data/n2_cp.csv\", delimiter=\",\", skiprows=1)\nT_raw = data[:, 0]\nCp_raw = data[:, 1]\n\n# Add noise — try changing this value: 0.01, 0.02, 0.05, 0.1\nnoise_scale = 0.02 # kJ/kg/K\n\nrng = np.random.default_rng(seed=42)\nCp_noisy = Cp_raw + rng.normal(scale=noise_scale, size=Cp_raw.size)\n\nplt.figure(figsize=(8, 5))\nplt.plot(T_raw, Cp_raw, 'g--', linewidth=1.5, label='True (NIST)')\nplt.plot(T_raw, Cp_noisy, 'ko', markersize=6, label=f'Noisy (σ = {noise_scale})')\nplt.xlabel('Temperature (K)')\nplt.ylabel('$C_p$ (kJ/kg/K)')\nplt.title('Clean vs. noisy data')\nplt.legend()\nplt.show()\n\nprint(f\"Cp range: {Cp_raw.min():.4f} – {Cp_raw.max():.4f} kJ/kg/K\")\nprint(f\"Noise scale: {noise_scale} kJ/kg/K ({noise_scale / (Cp_raw.max() - Cp_raw.min()) * 100:.1f}% of signal range)\")", + "metadata": {}, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "35ff0d60", + "source": "### Pause and discuss\n\nLook at the plot. The noise is small compared to the overall trend — you can still clearly see the shape of $C_p(T)$. But it's enough to cause problems, as we'll see.\n\n**Question:** If you were fitting a polynomial to this data, would you expect it to work well? What about a very high-degree polynomial?", + "metadata": {} + }, + { + "cell_type": "markdown", + "id": "41f358d1", + "source": "## 2. Train/validation split\n\nHere's the key idea: if we train on *all* the data, we have no way to tell whether the network learned the real trend or just memorized the noise. We need to **hold out** some data that the network never sees during training, then check whether its predictions are good on that held-out data.\n\nWe'll use every 4th point for validation (9 points) and the rest for training (26 points).", + "metadata": {} + }, + { + "cell_type": "code", + "id": "88dbe11a", + "source": "# Split: every 4th point is validation\nval_mask = np.zeros(len(T_raw), dtype=bool)\nval_mask[::4] = True\ntrain_mask = ~val_mask\n\nT_train, Cp_train = T_raw[train_mask], Cp_noisy[train_mask]\nT_val, Cp_val = T_raw[val_mask], Cp_noisy[val_mask]\n\nplt.figure(figsize=(8, 5))\nplt.plot(T_train, Cp_train, 'ko', markersize=6, label=f'Training ({len(T_train)} pts)')\nplt.plot(T_val, Cp_val, 'bs', markersize=8, label=f'Validation ({len(T_val)} pts)')\nplt.plot(T_raw, Cp_raw, 'g--', linewidth=1, alpha=0.5, label='True (NIST)')\nplt.xlabel('Temperature (K)')\nplt.ylabel('$C_p$ (kJ/kg/K)')\nplt.title('Train/validation split')\nplt.legend()\nplt.show()", + "metadata": {}, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "0bbc02c5", + "source": "## 3. Normalize and prepare tensors\n\nAs before, we normalize to [0, 1] — but using only the **training set** statistics. The validation set must be normalized with the same min/max values so the network sees a consistent scale.", + "metadata": {} + }, + { + "cell_type": "code", + "id": "01974a6f", + "source": "# Normalize using training set statistics only\nT_min, T_max = T_train.min(), T_train.max()\nCp_min, Cp_max = Cp_train.min(), Cp_train.max()\n\ndef normalize_T(T):\n return (T - T_min) / (T_max - T_min)\n\ndef normalize_Cp(Cp):\n return (Cp - Cp_min) / (Cp_max - Cp_min)\n\ndef denormalize_Cp(Cp_norm):\n return Cp_norm * (Cp_max - Cp_min) + Cp_min\n\nX_train = torch.tensor(normalize_T(T_train), dtype=torch.float32).reshape(-1, 1)\nY_train = torch.tensor(normalize_Cp(Cp_train), dtype=torch.float32).reshape(-1, 1)\nX_val = torch.tensor(normalize_T(T_val), dtype=torch.float32).reshape(-1, 1)\nY_val = torch.tensor(normalize_Cp(Cp_val), dtype=torch.float32).reshape(-1, 1)\n\nprint(f\"Training: {X_train.shape[0]} points\")\nprint(f\"Validation: {X_val.shape[0]} points\")", + "metadata": {}, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "3cffc860", + "source": "## 4. Train the network — watching both loss curves\n\nThis is the critical part. We track *two* loss values at every epoch:\n- **Training loss** — how well the network fits the data it's learning from\n- **Validation loss** — how well it predicts data it has *never seen*\n\nWe also save the best validation loss and the epoch where it occurred. This is the same strategy used in nanoGPT's `train.py` — it saves a checkpoint at the lowest validation loss.\n\n**Before running this cell, make a prediction:** Will both curves keep going down together? Or will they diverge?", + "metadata": {} + }, + { + "cell_type": "code", + "id": "7cf0f639", + "source": "# Define network — same architecture as before\nH = 10\n\nmodel = nn.Sequential(\n nn.Linear(1, H),\n nn.Tanh(),\n nn.Linear(H, 1),\n)\n\nn_params = sum(p.numel() for p in model.parameters())\nprint(f\"Network: 1 -> {H} (tanh) -> 1 ({n_params} parameters)\")\nprint(f\"Training on {X_train.shape[0]} points\\n\")\n\n# Training setup\noptimizer = torch.optim.Adam(model.parameters(), lr=0.01)\nloss_fn = nn.MSELoss()\n\nepochs = 10000\nlog_interval = 1000\ntrain_losses = []\nval_losses = []\nbest_val_loss = float('inf')\nbest_epoch = 0\nbest_state = None\n\nfor epoch in range(epochs):\n # Training step\n model.train()\n Y_pred = model(X_train)\n train_loss = loss_fn(Y_pred, Y_train)\n\n optimizer.zero_grad()\n train_loss.backward()\n optimizer.step()\n\n # Validation step (no gradients needed)\n model.eval()\n with torch.no_grad():\n val_pred = model(X_val)\n val_loss = loss_fn(val_pred, Y_val)\n\n train_losses.append(train_loss.item())\n val_losses.append(val_loss.item())\n\n # Save the best model — just like nanoGPT's train.py\n if val_loss.item() < best_val_loss:\n best_val_loss = val_loss.item()\n best_epoch = epoch\n best_state = {k: v.clone() for k, v in model.state_dict().items()}\n\n if epoch % log_interval == 0 or epoch == epochs - 1:\n print(f\"Epoch {epoch:5d} Train: {train_loss.item():.6f} Val: {val_loss.item():.6f}\")\n\nprint(f\"\\nBest validation loss: {best_val_loss:.6f} at epoch {best_epoch}\")", + "metadata": {}, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "57c169d3", + "source": "## 5. The overfitting signal\n\nNow let's plot the two loss curves side by side. This is the most important plot in the notebook.", + "metadata": {} + }, + { + "cell_type": "code", + "id": "ad150ddc", + "source": "fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(13, 5))\n\n# Left: training loss only\nax1.semilogy(train_losses)\nax1.set_xlabel('Epoch')\nax1.set_ylabel('MSE')\nax1.set_title('Training loss alone — looks great!')\n\n# Right: both curves together\nax2.semilogy(train_losses, label='Train loss')\nax2.semilogy(val_losses, label='Validation loss', color='orange')\nax2.axvline(best_epoch, color='gray', linestyle='--', alpha=0.5,\n label=f'Best validation (epoch {best_epoch})')\nax2.set_xlabel('Epoch')\nax2.set_ylabel('MSE')\nax2.set_title('Train vs. validation — the full picture')\nax2.legend()\n\nplt.tight_layout()\nplt.show()", + "metadata": {}, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "3bfe1a00", + "source": "### Pause and discuss\n\nLook at the two panels:\n\n- **Left panel:** If we only tracked training loss, we'd think everything was fine. The loss keeps going down!\n- **Right panel:** The validation loss tells a different story. It decreases at first (the network is learning the real trend), then **starts increasing** (the network is learning the noise).\n\nThe dashed line marks the **best validation epoch** — the point where the network knows the most about the true relationship and the least about the noise. Training beyond that point makes the model *worse* at predicting new data.\n\n**This is exactly what happens in LLM training.** In nanoGPT, `train.py` evaluates the model on a validation set periodically and saves a checkpoint whenever validation loss reaches a new low. If you train too long, the model memorizes the training text rather than learning general language patterns.", + "metadata": {} + }, + { + "cell_type": "markdown", + "id": "c51917f2", + "source": "## 6. See the overfitting in the fit itself\n\nLet's compare the **final model** (trained to the end) with the **best model** (saved at the lowest validation loss). We also plot the true NIST curve for reference.", + "metadata": {} + }, + { + "cell_type": "code", + "id": "3f830870", + "source": "# Predictions from the final model (overtrained)\nT_fine = torch.linspace(0, 1, 200).reshape(-1, 1)\nmodel.eval()\nwith torch.no_grad():\n Cp_final_norm = model(T_fine)\nT_fine_K = T_fine.numpy() * (T_max - T_min) + T_min\nCp_final = denormalize_Cp(Cp_final_norm.numpy())\n\n# Predictions from the best model (early stopping)\nmodel.load_state_dict(best_state)\nmodel.eval()\nwith torch.no_grad():\n Cp_best_norm = model(T_fine)\nCp_best = denormalize_Cp(Cp_best_norm.numpy())\n\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(13, 5))\n\n# Left: final model\nax1.plot(T_train, Cp_train, 'ko', markersize=5, label='Train (noisy)')\nax1.plot(T_val, Cp_val, 'bs', markersize=6, label='Validation (noisy)')\nax1.plot(T_raw, Cp_raw, 'g--', linewidth=1.5, alpha=0.7, label='True (NIST)')\nax1.plot(T_fine_K, Cp_final, 'r-', linewidth=2, label=f'Final model (epoch {epochs-1})')\nax1.set_xlabel('Temperature (K)')\nax1.set_ylabel('$C_p$ (kJ/kg/K)')\nax1.set_title('Final model — trained too long')\nax1.legend(fontsize=8)\n\n# Right: best model\nax2.plot(T_train, Cp_train, 'ko', markersize=5, label='Train (noisy)')\nax2.plot(T_val, Cp_val, 'bs', markersize=6, label='Validation (noisy)')\nax2.plot(T_raw, Cp_raw, 'g--', linewidth=1.5, alpha=0.7, label='True (NIST)')\nax2.plot(T_fine_K, Cp_best, 'r-', linewidth=2, label=f'Best model (epoch {best_epoch})')\nax2.set_xlabel('Temperature (K)')\nax2.set_ylabel('$C_p$ (kJ/kg/K)')\nax2.set_title('Best model — early stopping')\nax2.legend(fontsize=8)\n\nplt.tight_layout()\nplt.show()", + "metadata": {}, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "2b5c35d0", + "source": "### Pause and discuss\n\nCompare the two panels. The final model (left) tries to pass through every noisy training point, producing wiggles that don't reflect the true physics. The best model (right) produces a smoother curve closer to the true NIST data.\n\n**The network doesn't know what's signal and what's noise.** It just minimizes the loss. If you let it train long enough, it will fit everything — including the noise. The validation set is our only way of detecting this.", + "metadata": {} + }, + { + "cell_type": "markdown", + "id": "2bf32bca", + "source": "## 7. How noise level affects overfitting\n\nLet's wrap the whole pipeline into a function and run it for several noise levels to see the effect systematically.", + "metadata": {} + }, + { + "cell_type": "code", + "id": "c45e3027", + "source": "def train_noisy(noise_scale, H=10, epochs=10000, seed=42):\n \"\"\"Train on noisy data and return results for plotting.\"\"\"\n rng = np.random.default_rng(seed=seed)\n Cp_noisy = Cp_raw + rng.normal(scale=noise_scale, size=Cp_raw.size)\n\n # Split\n Cp_tr, Cp_va = Cp_noisy[train_mask], Cp_noisy[val_mask]\n T_mn, T_mx = T_raw[train_mask].min(), T_raw[train_mask].max()\n Cp_mn, Cp_mx = Cp_tr.min(), Cp_tr.max()\n\n X_tr = torch.tensor((T_raw[train_mask] - T_mn) / (T_mx - T_mn), dtype=torch.float32).reshape(-1, 1)\n Y_tr = torch.tensor((Cp_tr - Cp_mn) / (Cp_mx - Cp_mn), dtype=torch.float32).reshape(-1, 1)\n X_va = torch.tensor((T_raw[val_mask] - T_mn) / (T_mx - T_mn), dtype=torch.float32).reshape(-1, 1)\n Y_va = torch.tensor((Cp_va - Cp_mn) / (Cp_mx - Cp_mn), dtype=torch.float32).reshape(-1, 1)\n\n mdl = nn.Sequential(nn.Linear(1, H), nn.Tanh(), nn.Linear(H, 1))\n opt = torch.optim.Adam(mdl.parameters(), lr=0.01)\n loss_fn = nn.MSELoss()\n\n t_losses, v_losses = [], []\n best_vl, best_ep, best_st = float('inf'), 0, None\n\n for ep in range(epochs):\n mdl.train()\n pred = mdl(X_tr)\n tl = loss_fn(pred, Y_tr)\n opt.zero_grad(); tl.backward(); opt.step()\n\n mdl.eval()\n with torch.no_grad():\n vl = loss_fn(mdl(X_va), Y_va)\n\n t_losses.append(tl.item())\n v_losses.append(vl.item())\n if vl.item() < best_vl:\n best_vl, best_ep = vl.item(), ep\n best_st = {k: v.clone() for k, v in mdl.state_dict().items()}\n\n # Get best-model predictions\n mdl.load_state_dict(best_st)\n mdl.eval()\n T_f = torch.linspace(0, 1, 200).reshape(-1, 1)\n with torch.no_grad():\n Cp_pred = mdl(T_f).numpy() * (Cp_mx - Cp_mn) + Cp_mn\n T_f_K = T_f.numpy() * (T_mx - T_mn) + T_mn\n\n return dict(noise=noise_scale, t_losses=t_losses, v_losses=v_losses,\n best_epoch=best_ep, T_fine=T_f_K, Cp_pred=Cp_pred,\n Cp_train=Cp_tr, Cp_val=Cp_va)\n\n\n# Run for several noise levels\nnoise_levels = [0.005, 0.02, 0.05, 0.1]\nresults = [train_noisy(ns) for ns in noise_levels]", + "metadata": {}, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "id": "49ff5b58", + "source": "fig, axes = plt.subplots(2, len(noise_levels), figsize=(16, 9))\n\nfor i, r in enumerate(results):\n # Top row: fits\n ax = axes[0, i]\n ax.plot(T_raw[train_mask], r['Cp_train'], 'ko', markersize=4)\n ax.plot(T_raw[val_mask], r['Cp_val'], 'bs', markersize=5)\n ax.plot(T_raw, Cp_raw, 'g--', linewidth=1, alpha=0.5)\n ax.plot(r['T_fine'], r['Cp_pred'], 'r-', linewidth=2)\n ax.set_title(f\"σ = {r['noise']}\")\n ax.set_xlabel('T (K)')\n if i == 0:\n ax.set_ylabel('$C_p$ (kJ/kg/K)')\n\n # Bottom row: loss curves\n ax = axes[1, i]\n ax.semilogy(r['t_losses'], label='Train')\n ax.semilogy(r['v_losses'], label='Val', color='orange')\n ax.axvline(r['best_epoch'], color='gray', linestyle='--', alpha=0.5)\n ax.set_title(f\"Best epoch: {r['best_epoch']}\")\n ax.set_xlabel('Epoch')\n if i == 0:\n ax.set_ylabel('MSE')\n if i == len(noise_levels) - 1:\n ax.legend(fontsize=8)\n\nplt.suptitle('Effect of noise level on overfitting (H = 10)', fontsize=14, y=1.02)\nplt.tight_layout()\nplt.show()", + "metadata": {}, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "e9c16100", + "source": "### Pause and discuss\n\nNotice the trend across the four columns:\n- **Low noise (σ = 0.005):** The curves barely diverge. Early stopping happens late. The fit is essentially correct.\n- **Moderate noise (σ = 0.02–0.05):** The divergence is clear. Early stopping matters.\n- **High noise (σ = 0.1):** The validation loss diverges quickly and dramatically. The noise is comparable to the signal itself.\n\n**Key insight:** The same model architecture can be fine or catastrophically overfit depending on the quality of the data. This is why data quality matters so much in ML — and why LLM training requires carefully curated datasets, not just more data.", + "metadata": {} + }, + { + "cell_type": "markdown", + "id": "5b796024", + "source": "## 8. Does model size make it worse?\n\nWith clean data, we noted that 31 parameters for 35 data points was borderline. With noisy data and a train/validation split, we only have 26 training points. What happens if we increase `H`?", + "metadata": {} + }, + { + "cell_type": "code", + "id": "2cd8da66", + "source": "# Compare different model sizes with the same noise level\nhidden_sizes = [5, 10, 25, 50]\nnoise = 0.05 # moderate noise to make the effect visible\n\nresults_H = [train_noisy(noise, H=h) for h in hidden_sizes]\n\nfig, axes = plt.subplots(2, len(hidden_sizes), figsize=(16, 9))\n\nfor i, (h, r) in enumerate(zip(hidden_sizes, results_H)):\n n_params = 2 * h + h + 1\n\n ax = axes[0, i]\n ax.plot(T_raw[train_mask], r['Cp_train'], 'ko', markersize=4)\n ax.plot(T_raw[val_mask], r['Cp_val'], 'bs', markersize=5)\n ax.plot(T_raw, Cp_raw, 'g--', linewidth=1, alpha=0.5)\n ax.plot(r['T_fine'], r['Cp_pred'], 'r-', linewidth=2)\n ax.set_title(f\"H = {h} ({n_params} params)\")\n ax.set_xlabel('T (K)')\n if i == 0:\n ax.set_ylabel('$C_p$ (kJ/kg/K)')\n\n ax = axes[1, i]\n ax.semilogy(r['t_losses'], label='Train')\n ax.semilogy(r['v_losses'], label='Val', color='orange')\n ax.axvline(r['best_epoch'], color='gray', linestyle='--', alpha=0.5)\n ax.set_title(f\"Best epoch: {r['best_epoch']}\")\n ax.set_xlabel('Epoch')\n if i == 0:\n ax.set_ylabel('MSE')\n if i == len(hidden_sizes) - 1:\n ax.legend(fontsize=8)\n\nplt.suptitle(f'Effect of model size on overfitting (σ = {noise})', fontsize=14, y=1.02)\nplt.tight_layout()\nplt.show()\n\nfor h, r in zip(hidden_sizes, results_H):\n print(f\"H = {h:3d} params = {2*h+h+1:4d} best epoch = {r['best_epoch']}\")", + "metadata": {}, + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "1fdea24c", + "source": "## 9. Summary: what we learned\n\n| Concept | In this notebook | In LLM training |\n|---------|-----------------|-----------------|\n| **Overfitting** | Network memorizes noisy $C_p$ data points | Model memorizes training text instead of learning language |\n| **Validation loss** | Increases while training loss decreases | Same — the signal that training should stop |\n| **Early stopping** | Save model at best validation epoch | `train.py` saves checkpoint at lowest validation loss |\n| **Model size** | More neurons = faster overfitting | More parameters = needs more (and better) data |\n| **Data quality** | More noise = earlier overfitting | Poor training data = poor model, no matter the size |\n\nThe validation loss is the most important diagnostic in training. It's the only thing that tells you whether the model is learning something general or just memorizing. When you see LLM papers report \"training loss\" and \"validation loss\", this is exactly what they mean.", + "metadata": {} + }, + { + "cell_type": "markdown", + "id": "552d4795", + "source": "## 10. Exercises\n\nTry these in new cells below:\n\n1. **Different random seeds.** Change `seed=42` to other values in the `train_noisy` function. Does the best epoch change? Does the overall pattern (validation loss rising) persist?\n\n2. **Regularization by reducing model size.** With `noise_scale = 0.05`, try `H = 3`. This gives only 10 parameters — too few to memorize 26 points. Does it overfit? Is the fit still reasonable?\n\n3. **More data helps.** Instead of holding out every 4th point, try every 8th (fewer validation, more training). Does overfitting get better or worse? Why?\n\n4. **Polynomial comparison.** Fit a high-degree polynomial (degree 10 or 15) to the noisy data using `np.polyfit`. How does it compare to the neural network? Does it also overfit?", + "metadata": {} + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python", + "version": "3.12.0" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file