smartyfy.mrindigi.com

Python Master Course V2 — 150. Deep Learning Capstone: A Diagnosed CPU Model

Purpose and learning outcomes

The capstone is a small neural experiment that another learner can inspect, rerun, and challenge. You will classify bundled digits on the CPU, compare with a strong regularized linear baseline, diagnose training, choose a checkpoint using validation, and verify trusted checkpoint recovery before a final test evaluation. A transparent result is more valuable than an unexplained high score.

  • Design a bounded neural experiment with a strong baseline
  • Verify data shapes, gradients and checkpoint recovery
  • Report validation choices, test results and compute limits

Prerequisites: 141–149: neural-network engineering.

Environment and run order

Use the isolated Python 3.11 or 3.12 environment from lesson 142. All tensors and models below run on the CPU. No pretrained weights or external datasets are downloaded. For first-time setup install the numerical packages, then use the official PyTorch installer selector for your operating system. The CPU wheel command below is for Linux or Windows; macOS uses python -m pip install torch. Run Python blocks sequentially in a single file.

Shell

python -m pip install numpy pandas scikit-learn matplotlib
# Linux/Windows CPU installation:
python -m pip install torch --index-url https://download.pytorch.org/whl/cpu
python -m pip freeze > requirements-observed.txt

Understand the model and the evidence

Start with a bounded question

The input is an 8-by-8 grayscale digit with known pixel range; the target is one of ten digit labels. We compare a small dense neural network with a standardized logistic classifier. The task does not establish performance on arbitrary photographs, handwriting populations, rotations, or corrupted images. Record a fixed seed, split, maximum epoch count, patience, and CPU thread budget before fitting.

A strong baseline protects the conclusion

The linear baseline uses the same training rows and predicts on the same validation rows. Its scaler is fitted only on training. The neural network uses the known constant pixel scaling and a hidden nonlinear layer. Comparing only against random guessing would miss whether the neural system adds value beyond a simple well-established predictor. If the baseline wins on validation, acknowledge that result and keep it as the selected prediction system.

Training quality and statistical quality differ

Shape assertions, finite-gradient checks, and checkpoint round trips test implementation behavior. Validation loss and baseline comparisons assess predictive behavior on development data. A network can pass every engineering test and still underperform a simpler model. Conversely, an attractive score with a broken data boundary is not valid evidence. Keep both classes of checks in the final report.

Checkpoint selection is part of the experiment

Validation loss selects the best neural epoch using a declared patience rule. We restore that copied state before comparing validation accuracy with the baseline. Test accuracy is computed only for the selected system; the neural checkpoint is still verified as an engineering artifact. If the final errors inspire another model version, treat them as development information and plan new independent evaluation rather than recycling the same claim.

Incremental worked example

1. Prepare data, baseline, and a compact neural model

The script creates all required artifacts locally. Pixel normalization uses the known scale rather than full-data statistics. The baseline has its own training-fitted scaler. A single CPU thread and at most 40 neural epochs keep the exercise modest.

Python

from pathlib import Path
import copy
import json
import platform
import time
import numpy as np
import torch
from torch import nn
from torch.utils.data import TensorDataset, DataLoader
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

torch.set_num_threads(1)
torch.manual_seed(50)
X_np, y_np = load_digits(return_X_y=True)
X_np = (X_np / 16.0).astype(np.float32)
ids = np.arange(len(y_np))
development, test = train_test_split(ids, test_size=0.2, stratify=y_np, random_state=50)
train, valid = train_test_split(development, test_size=0.25,
    stratify=y_np[development], random_state=51)
X, y = torch.tensor(X_np), torch.tensor(y_np, dtype=torch.long)
baseline = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1500, C=1.0))
baseline.fit(X_np[train], y_np[train])
def build_model():
    return nn.Sequential(nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, 10))
model = build_model()
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
loader = DataLoader(TensorDataset(X[train], y[train]), batch_size=64, shuffle=True,
    generator=torch.Generator().manual_seed(50), num_workers=0)
loss_fn = nn.CrossEntropyLoss()
assert model(X[:2]).shape == (2, 10)
best_loss, best_state, best_epoch, stale = float("inf"), None, -1, 0
history = []
start = time.perf_counter()

2. Train with diagnostics and validation stopping

Every mean batch loss is weighted by its batch size for the epoch report. Gradient clipping raises on non-finite values. A deep copy preserves the best parameter state. Patience of five and a small minimum improvement are fixed before training.

Python

for epoch in range(40):
    model.train()
    total = 0.0
    max_grad_norm = 0.0
    for xb, yb in loader:
        optimizer.zero_grad(set_to_none=True)
        logits = model(xb)
        assert logits.shape == (len(xb), 10)
        loss = loss_fn(logits, yb)
        if not torch.isfinite(loss):
            raise RuntimeError("Non-finite loss")
        loss.backward()
        norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 5.0, error_if_nonfinite=True)
        max_grad_norm = max(max_grad_norm, float(norm))
        optimizer.step()
        total += loss.item() * len(xb)
    model.eval()
    with torch.no_grad():
        value = loss_fn(model(X[valid]), y[valid]).item()
    history.append({"epoch": epoch, "train_loss": total / len(train),
                    "valid_loss": value, "max_preclip_grad_norm": max_grad_norm})
    if value < best_loss - 1e-4:
        best_loss, best_state, best_epoch, stale = value, copy.deepcopy(model.state_dict()), epoch, 0
    else:
        stale += 1
    if stale >= 5:
        break
training_seconds = time.perf_counter() - start
model.load_state_dict(best_state)
model.eval()

3. Verify recovery and evaluate the selected system

The neural artifact stores state tensors and simple metadata, then reloads only the trusted file this script created. A fixed validation batch verifies identical recovered logits within tolerance. The final report records whether the neural model or baseline was selected; it never hides a baseline win.

Python

out = Path("lesson150-artifacts")
out.mkdir(exist_ok=True)
checkpoint = out / "trusted-neural-state.pt"
torch.save({"state_dict": best_state, "best_epoch": best_epoch,
            "pixel_divisor": 16.0, "seed": 50}, checkpoint)
restored = build_model()
state = torch.load(checkpoint, map_location="cpu", weights_only=True)
restored.load_state_dict(state["state_dict"])
restored.eval()
with torch.no_grad():
    assert torch.allclose(model(X[valid[:8]]), restored(X[valid[:8]]), atol=1e-6)
    neural_validation = (restored(X[valid]).argmax(1) == y[valid]).float().mean().item()
baseline_validation = baseline.score(X_np[valid], y_np[valid])
selected = "neural" if neural_validation > baseline_validation else "linear_baseline"
if selected == "neural":
    with torch.no_grad():
        final_pred = restored(X[test]).argmax(1).numpy()
else:
    final_pred = baseline.predict(X_np[test])
report = {"selected": selected, "validation_neural": neural_validation,
    "validation_baseline": baseline_validation, "test_accuracy": float(np.mean(final_pred == y_np[test])),
    "best_epoch": best_epoch, "epochs_run": len(history), "training_seconds": training_seconds,
    "python": platform.python_version(), "torch": str(torch.__version__),
    "train_rows": len(train), "validation_rows": len(valid), "test_rows": len(test),
    "history": history}
(out / "report.json").write_text(json.dumps(report, indent=2), encoding="utf-8")
print(json.dumps({k: v for k, v in report.items() if k != "history"}, indent=2))

Expected output / interpretation

The script creates a trusted neural checkpoint and a JSON report in lesson150-artifacts.
Checkpoint recovery is checked before final evaluation.
Accuracy, selected model, epoch count, and wall time are honest runtime results; no winner or speed is promised.

Guided lab and acceptance criteria

  1. Create a project folder with the runnable script, environment record, tests, generated report, and a short README. Include the seed and source of bundled data, and state that the checkpoint may only be loaded from a trusted origin.
  2. Plot training and validation loss against epoch and mark the selected epoch. Add a gradient-norm summary and a one-batch overfit diagnostic using a separate model if the main run behaves unexpectedly. Do not debug on test labels.
  3. Add inference tests for a valid one-row batch, wrong feature count, values outside the allowed pixel range, and NaN. Decide whether raw pixels or normalized pixels enter the public function and document that choice without silently supporting both.
  4. Write a final model card and self-review: 25% honest data/evaluation boundaries, 25% baseline and bounded experiment, 25% diagnostics/checkpoint recovery, 25% readable reproducibility and limitations. Report a baseline win plainly. Passing the capstone requires correct evidence, not exceeding an arbitrary accuracy threshold.

Common mistakes and repairs

  • Selecting the best epoch by test accuracy: epoch choice is model selection and belongs to validation.
  • Saving the final epoch while reporting the best validation epoch: restore and persist the actual selected state.
  • Calling one measured CPU time a universal speed benchmark: record hardware, environment, workload, and what the timer includes.

Questions that test understanding

Why use logistic regression as the baseline?

It is a capable, inexpensive classifier for small numeric datasets and often performs well on digit features. Beating it provides stronger evidence than beating a dummy model alone. If it wins, that is a useful engineering outcome rather than a failure of the exercise.

Why choose neural checkpoints by loss but compare systems by accuracy?

Validation loss is a smooth signal sensitive to confidence and is often useful for early stopping, while the declared final system comparison here uses classification accuracy. Both choices are explicit parts of the protocol. Other tasks may justify different aligned criteria, but they should be fixed before test inspection.

What does the checkpoint test cover?

It verifies that this locally saved state can be loaded into the same architecture and reproduce logits on a fixed batch within tolerance. It does not test resuming Adam’s optimizer history, because this artifact is for inference. A resumable training checkpoint needs the additional state taught in lesson 145.

Why not refit the selected system on all development data?

Refitting is possible, but neural epoch and stopping choices need a carefully specified recipe once validation rows join training. This capstone preserves the exact fitted system selected by validation, making the final evaluation straightforward. A refit extension should be planned and evaluated as its own procedure.

What should the report say if the neural model loses?

State the baseline’s validation advantage and select it under the declared rule. Keep the neural diagnostics and recovery evidence as engineering results. Do not switch metrics, hide the comparison, or keep tuning against the final test until the neural model appears better.

When is this project ready for real deployment?

The capstone alone does not establish that. A real deployment needs representative data, input-shift and failure analysis, operational monitoring, latency and resource checks, privacy review, and an appropriate human decision process. This project demonstrates a reproducible learning workflow with deliberately limited scope.

Exercises with worked solutions

Exercise 1: Add a normalized-input contract

Reveal the worked solution and reasoning

This interface accepts normalized pixel values in [0,1], matching the trained model. It rejects ambiguous shapes and non-finite data before inference. Keep raw-pixel conversion in a separate documented wrapper if needed.

Python

def neural_predict_normalized(rows):
    batch = torch.as_tensor(rows, dtype=torch.float32)
    if batch.ndim != 2 or batch.shape[1] != 64:
        raise ValueError("Expected a batch with 64 normalized pixel features")
    if not torch.isfinite(batch).all() or (batch < 0).any() or (batch > 1).any():
        raise ValueError("Pixels must be finite and within [0,1]")
    restored.eval()
    with torch.no_grad():
        return restored(batch).argmax(1).numpy()
assert neural_predict_normalized(X_np[valid[:1]]).shape == (1,)

Exercise 2: Write a defensible completion statement

Reveal the worked solution and reasoning

A suitable statement names the dataset, fixed partitions, baseline, selected system, actual test metric, best neural epoch, and checkpoint test. It also states that the work ran on a bounded CPU budget and does not validate arbitrary handwriting images. Avoid claims of professional certification or production reliability based solely on completing this exercise.

Recap and next step

You have completed a diagnosed neural experiment with a strong baseline, protected test evidence, explicit training contracts, validation-based checkpoint selection, and trusted recovery. These habits transfer to larger architectures and AI applications. Keep the evidence boundary and failure tests visible whenever model complexity or deployment responsibility increases.

Official references

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.