smartyfy.mrindigi.com

AI & Machine Learning Master Course — 106. Initialization and optimization algorithms

Smartyfy AI & Machine Learning Master Course

Course ID: smartyfy-ai-ml-master-200

Lesson 106: Initialization and optimization algorithms

Prerequisites: Lesson 105. Learning outcome: Compare initialization choices, SGD, momentum, and adaptive optimization.

Initialization sets the first learning conditions

A network begins with parameters before it has learned anything. Their scale affects activation magnitudes and the gradients that pass through layers. Values that are too large can saturate some nonlinearities or produce unstable signals; values that are too small can make signals and gradients weak.

Hidden units also need a way to learn different functions. If equivalent hidden neurons start with identical parameters and receive identical gradient updates, symmetry can keep them identical. Random initialization breaks that symmetry. Zero initialization can be appropriate for a simple single-output linear model, but setting every weight in a multilayer hidden network to zero is a different situation.

Initialization recipes use assumptions about fan-in, fan-out, activation shape, and approximate signal statistics. They are sensible starting points, not guarantees that arbitrary architectures will train. Inspect actual activations and gradients on the intended data.

Relate variance to connectivity

Fan-in is the number of inputs contributing to a unit; fan-out is the number of outputs receiving from a unit. Xavier-style initialization balances scale using both for certain activation settings. He-style initialization is commonly associated with rectifier networks and a weight variance around 2/fan-in under its simplifying assumptions.

With fan-in eight, that He-style target variance is 0.25 and standard deviation is 0.5. The example samples ten thousand independent weights at this scale and observes variance about 0.2520. Sampling variability explains the small difference; matching a theoretical variance exactly is not required.

These formulas concern weight distributions and approximate propagation behavior. They do not say every activation has exactly unit variance or every gradient remains constant. Correlated inputs, nonzero means, normalization layers, and architecture choices can change the result. Record the convention and tensor orientation when using a framework initializer.

SGD, momentum, and Adam use gradients differently

Plain gradient descent updates a parameter by subtracting learning rate times its current gradient. Stochastic gradient descent uses a batch estimate of that gradient. In this lesson's deterministic quadratic example, there is no sampling noise, so the calculation is simply gradient descent.

Momentum keeps a running direction. Our convention is velocity = beta times previous velocity plus current gradient, followed by parameter minus learning rate times velocity. Other formulations rescale the gradient term, so state the convention before comparing numeric steps.

Adam maintains exponential averages of gradients and squared gradients, applies bias corrections for their initial zero state, and divides the first-moment estimate by a square-root second-moment scale plus epsilon. This creates coordinate-specific effective step sizes. It still needs a learning rate and does not guarantee better generalization than SGD.

CPU lab: five steps on a known quadratic

The objective is L(w)=0.5w squared, so its exact gradient is w. Every method starts at w=2 and uses nominal learning rate 0.1 for five steps. Momentum uses beta 0.9; Adam uses beta values 0.9 and 0.999 with epsilon 1e−8. The NumPy implementation exposes all state updates.

After five steps, SGD has w=1.180980 and loss 0.697357; momentum has w=−0.058320 and loss 0.001701; Adam has w=1.502956 and loss 1.129438. Momentum happens to be closest to the optimum after this fixed short horizon. These values do not rank the methods universally. NumPy 2.3.5 executed on CPU; no PyTorch optimizer was run.

import numpy as np
rng = np.random.default_rng(106)
samples = rng.normal(0, np.sqrt(2 / 8), 10000)
print('He-style target variance', 2 / 8, 'observed', round(samples.var(), 4))
for method in ['sgd', 'momentum', 'adam']:
    w = 2.; velocity = 0.; m = 0.; v = 0.
    for t in range(1, 6):
        g = w
        if method == 'sgd':
            step = g
        elif method == 'momentum':
            velocity = .9 * velocity + g; step = velocity
        else:
            m = .9 * m + .1 * g; v = .999 * v + .001 * g * g
            step = (m / (1 - .9 ** t)) / (np.sqrt(v / (1 - .999 ** t)) + 1e-8)
        w -= .1 * step
    print(method, 'w', round(w, 6), 'loss', round(.5 * w * w, 6))
assert np.isclose(2 * .9 ** 5, 1.18098)
A quadratic plot shows five-step endpoints for SGD at 1.180980, momentum at minus 0.058320 and Adam at 1.502956, starting from weight two.
Different update rules produce different steps even with the same nominal learning rate. Open full-size diagram

Compare procedures rather than optimizer names

Equal nominal learning rates do not imply equal parameter steps across optimizers. Adam normalizes its update using accumulated gradient magnitudes, while momentum accumulates direction. A fair practical comparison gives each method a justified development tuning budget and records schedules, regularization, batch sizes, and stopping rules.

A short quadratic is convex, one-dimensional, and noise-free. Neural-network objectives can be high-dimensional and nonconvex with noisy batch gradients. An optimizer that reaches a low loss quickly in this toy example may behave differently there. Separate convergence speed, final training fit, validation quality, and resource cost.

Weight decay also depends on implementation. Adding an L2 penalty to the loss is equivalent to a particular shrinkage term under plain SGD, but coupled regularization and decoupled weight decay are not generally the same under adaptive updates. Check the exact optimizer API rather than treating all weight_decay arguments as interchangeable.

Tune and resume responsibly

Start with a small, prespecified learning-rate comparison and watch for finite losses, useful gradient magnitudes, and meaningful progress. A divergent loss can indicate an excessive rate, but also a data or implementation defect. Reducing the rate until nothing changes is not a diagnosis.

Optimizer state matters when resuming. Restoring parameters without momentum buffers or Adam moments changes the procedure. Save the step count and scheduler state when reproducibility requires them. A fresh optimizer may be intentional for fine-tuning, but should be described as a new training phase.

Use validation to choose the complete training configuration and reserve final evaluation for the frozen choice. Initialization seeds can affect results; report variation when comparing methods rather than highlighting one favorable run. The goal is a stable procedure with evidence, not allegiance to a particular optimizer.

Four practice questions with worked answers

Practice 1

For fan-in sixteen, what He-style variance and standard deviation follow?

Answer: Variance is 2/16=0.125 and standard deviation is the square root of 0.125, approximately 0.3536. These are initialization targets under the recipe’s assumptions.

Practice 2

Compute one plain step from w=2 for L=0.5w squared with rate 0.1.

Answer: The gradient is 2, so the update gives 2−0.1×2=1.8. Repeating plain steps multiplies w by 0.9 each time.

Practice 3

Why can identical hidden-unit initialization be problematic?

Answer: Equivalent units can receive identical gradients and remain identical, wasting the intended representational diversity. Random initialization can break that symmetry.

Practice 4

Does the momentum result prove it is always better than Adam?

Answer: No. It is one five-step comparison on a deterministic scalar quadratic with fixed nominal rates. Different objectives, rates, horizons, and data can change the ranking.

Five multiple-choice questions

Question 1

What does fan-in count?

  • A. Outputs receiving a unit’s activation
  • B. Total weights and biases in the layer
  • C. Inputs contributing to a unit

Correct: C. Connectivity determines the scale used by fan-based initialization.

Question 2

What extra state does momentum maintain?

  • A. An average of squared gradients only
  • B. Only the current gradient, with history discarded
  • C. An accumulated update direction

Correct: C. Its velocity combines previous direction with current gradient.

Question 3

Why does Adam use bias correction?

  • A. Its moment averages start at zero
  • B. Every gradient is a biased label estimate
  • C. It guarantees an unbiased final predictor

Correct: A. The correction addresses initialization of moving averages, not all statistical bias.

Question 4

Are equal learning-rate numbers equivalent across optimizers?

  • A. Yes, every parameter moves by the same amount
  • B. No, update transformations differ
  • C. Only when the nominal learning rate and initial parameters match

Correct: B. Momentum and adaptive normalization alter actual step sizes.

Question 5

What should a resumable checkpoint preserve?

  • A. Only the latest rounded loss
  • B. Parameters and relevant optimizer/scheduler state
  • C. Only the random seed without model values

Correct: B. Stateful optimization cannot generally be reconstructed from weights alone.

Common pitfalls

Avoid zeroing equivalent hidden weights indiscriminately, confusing variance with standard deviation, or ranking optimizers from one untuned toy run. Check regularization semantics and restore optimizer state when continuing the same training procedure.

Summary

Initialization shapes signal propagation and symmetry, while optimizers transform gradients into parameter updates. Their value must be judged as part of a documented, tuned, and reproducible training procedure.

Primary sources and further reading