smartyfy.mrindigi.com

Python Master Course V2 — 144. Optimization, Initialization and Regularization

Purpose and learning outcomes

Changing an optimizer, learning rate, dropout setting, and network width all at once makes an experiment difficult to interpret. This lesson changes one optimization or regularization choice at a time while keeping a small synthetic dataset, split, architecture, and update budget fixed. The result is a learning-curve comparison, not a universal ranking of optimizers.

  • Compare SGD and Adam under a controlled budget
  • Apply weight decay, dropout and appropriate initialization
  • Diagnose the interaction of learning rate, scale and batch size

Prerequisites: 143: training loops; 136: fair comparison.

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

Optimization depends on the scale of the problem

SGD follows the current gradient scaled by a learning rate. Adam also maintains moving summaries of first and second gradient moments, producing coordinate-wise adaptive updates. The same numerical learning rate does not imply equivalent update behavior, and a fixed epoch budget may favor one method. Standardizing training features improves comparability, but cannot remove every optimization difference.

Initialization sets the starting geometry

If all hidden units begin identically, they can remain symmetric and learn redundant features. Random initialization breaks that symmetry. Kaiming initialization is designed for rectifier activations such as ReLU under particular variance assumptions. We explicitly initialize Linear weights and zero biases, then reset the seed for each candidate so corresponding layers start consistently. This controls one source of variation, not every possible floating-point effect.

Regularization changes what is learned

Weight decay discourages large parameter values; its exact relationship with an L2 loss penalty depends on the optimizer formulation. AdamW implements decoupled weight decay, whereas this demonstration uses Adam’s documented weight_decay parameter and describes it as that specific setting. Dropout randomly zeroes activations during training and rescales the survivors. In evaluation mode it becomes the identity operation. Both can reduce overfitting, but excessive regularization can cause underfitting.

Controlled comparisons still need humility

We compare SGD and Adam at a shared prespecified learning rate to isolate a nominal configuration change, then add weight decay or dropout to Adam separately. This does not establish which optimizer is best after equal tuning effort. A dedicated DataLoader generator keeps minibatch shuffling independent from dropout’s random draws. Repeat development experiments across several planned seeds and report their distribution rather than selecting the most favorable run.

Incremental worked example

1. Create fixed data and an experiment function

The protected test set is retained but not evaluated while comparing settings. Every run fits the same small architecture on the same standardized training rows. The initializer is applied to every Linear module through Module.apply.

Python

import numpy as np
import torch
from torch import nn
from torch.utils.data import TensorDataset, DataLoader
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

torch.set_num_threads(1)
X, y = make_classification(n_samples=480, n_features=10, n_informative=5,
                           n_redundant=1, flip_y=0.04, random_state=44)
Xd, Xt, yd, yt = train_test_split(X, y, test_size=0.2, stratify=y, random_state=44)
Xr, Xv, yr, yv = train_test_split(Xd, yd, test_size=0.25, stratify=yd, random_state=45)
scaler = StandardScaler().fit(Xr)
xr = torch.tensor(scaler.transform(Xr), dtype=torch.float32)
xv = torch.tensor(scaler.transform(Xv), dtype=torch.float32)
yr_t, yv_t = torch.tensor(yr, dtype=torch.long), torch.tensor(yv, dtype=torch.long)
def initialize(module):
    if isinstance(module, nn.Linear):
        nn.init.kaiming_normal_(module.weight, nonlinearity="relu")
        nn.init.zeros_(module.bias)
def experiment(optimizer_name="adam", decay=0.0, dropout=0.0, seed=44):
    torch.manual_seed(seed)
    net = nn.Sequential(nn.Linear(10, 24), nn.ReLU(), nn.Dropout(dropout),
                        nn.Linear(24, 2))
    net.apply(initialize)
    opt_class = torch.optim.SGD if optimizer_name == "sgd" else torch.optim.Adam
    opt = opt_class(net.parameters(), lr=0.02, weight_decay=decay)
    loader = DataLoader(TensorDataset(xr, yr_t), batch_size=32, shuffle=True,
        generator=torch.Generator().manual_seed(seed), num_workers=0)
    loss_fn = nn.CrossEntropyLoss()
    history = []
    for epoch in range(30):
        net.train()
        total = 0.0
        for inputs, targets in loader:
            opt.zero_grad(set_to_none=True)
            loss = loss_fn(net(inputs), targets)
            loss.backward()
            opt.step()
            total += loss.item() * len(inputs)
        net.eval()
        with torch.no_grad():
            valid_loss = loss_fn(net(xv), yv_t).item()
        history.append((total / len(xr), valid_loss))
    return net, np.asarray(history)

2. Run four prespecified development comparisons

The dictionary records exactly which factor changes from the plain Adam reference. We print final losses for a compact summary and retain all learning-curve points for inspection. Test data are deliberately not consulted.

Python

settings = {"sgd": ("sgd", 0.0, 0.0),
            "adam": ("adam", 0.0, 0.0),
            "adam_decay": ("adam", 0.01, 0.0),
            "adam_dropout": ("adam", 0.0, 0.2)}
runs = {}
for name, settings_tuple in settings.items():
    net, history = experiment(*settings_tuple)
    runs[name] = (net, history)
    print(name, "final training/validation loss", history[-1].tolist())
assert all(history.shape == (30, 2) for _, history in runs.values())

Expected output / interpretation

Four pairs of final losses are printed, and each run retains a (30,2) learning curve.
No optimizer ordering is guaranteed.
Training losses with dropout are measured under a different stochastic computation than evaluation losses.

Guided lab and acceptance criteria

  1. Plot all training and validation curves with clearly labeled settings. Identify divergence, slow progress, and widening generalization gaps as hypotheses to investigate, not definitive diagnoses from one curve.
  2. Repeat the four comparisons for seeds 44, 45, and 46 without changing the data split. Report all final validation losses and their spread. Explain that this measures initialization and training randomness while holding sampling variation fixed.
  3. Choose one optimizer and compare three prespecified learning rates under the same update budget. Keep this separate from the original one-factor comparison so the conclusion states whether settings or tuned optimizer families are being compared.
  4. Deliver a configuration table, curves, seed summary, and a justified next development choice. Passing work leaves test untouched and distinguishes Adam weight_decay behavior from decoupled AdamW rather than treating all uses of the phrase weight decay as interchangeable.

Common mistakes and repairs

  • Comparing dropout training loss directly with no-dropout evaluation loss as if computations were identical: inspect both under a common eval-mode pass when needed.
  • Changing initialization seed accidentally between candidates: reset it and use a separate loader generator to control data order.
  • Concluding Adam is universally superior from one fixed learning rate and small dataset: the experiment compares these particular configurations and budgets.

Questions that test understanding

Why might SGD look worse after 30 epochs?

It may need a different learning rate, momentum setting, schedule, or larger update budget. The result is evidence about this chosen configuration, not the entire optimizer family. Compare equal tuning budgets and compute constraints when making a broader practical decision.

Does dropout permanently delete neurons?

No. During training it randomly masks activations and rescales the remaining values according to the configured probability. During evaluation it returns the activations unchanged. Forgetting eval mode can make predictions unnecessarily stochastic and invalidate a checkpoint comparison.

Is Adam weight decay identical to AdamW?

Not generally. AdamW decouples the decay step from adaptive gradient normalization. Adam’s weight_decay behavior follows its specified optimizer formulation and options. Name the actual optimizer and settings in the report rather than assuming the same numeric coefficient means the same regularization effect.

Why use a separate generator for loader shuffling?

Dropout consumes random numbers during training. If shuffling and dropout share the same generator stream, changing dropout can also change future batch order. A dedicated loader generator makes that aspect of the comparison easier to control and explain.

Why does initialization depend on activation?

Activations transform signal variance differently. An initialization designed for rectifiers aims to keep forward or backward magnitudes from collapsing or exploding under simplifying assumptions. It is a useful default, not a guarantee that every architecture will train well.

Can regularization make both training and validation worse?

Yes. If it is too strong, the model may lack effective capacity or optimize too slowly under the chosen budget. Regularization is useful when it improves the intended generalization tradeoff, not because a technique is fashionable or increases the number of settings.

Exercises with worked solutions

Exercise 1: Verify dropout mode behavior

Reveal the worked solution and reasoning

Use a standalone Dropout module so the test concerns exactly one mechanism. Evaluation should return the input unchanged. Training may randomly keep or remove entries, so do not require every single random call to differ in a tiny tensor.

Python

drop = nn.Dropout(0.5)
values = torch.ones(100)
drop.eval()
assert torch.equal(drop(values), values)
drop.train()
result = drop(values)
assert set(result.tolist()) <= {0.0, 2.0}
print("dropout mode contract checked")

Exercise 2: Interpret a widening validation gap

Reveal the worked solution and reasoning

First verify validation uses eval mode and training-fitted preprocessing. If those checks pass, a falling training loss with rising validation loss suggests the model is fitting patterns that do not transfer. Try an explicitly planned smaller model, stronger regularization, or early stopping using validation. Keep the final test outside that diagnosis.

Recap and next step

Optimization experiments are informative when initialization, batch order, data boundaries, and compute budgets are explicit. Regularization is a tradeoff that must be measured. The next lesson adds diagnostic checks, validation-based early stopping, and checkpoints that preserve enough state to resume a run without confusing the latest model with the best one.

Official references

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