Batch normalisation – trainable and non trainable – day 27

A standard Keras batch normalization layer stores four numbers per feature. The optimizer learns the scale γ and shift β. The layer itself updates the moving mean and moving variance during training and reads them during inference.

Day 27 follows the batch normalization examples from Day 26. You’ll trace a single feature through training and inference, count the original model’s weights, and see what changes when you disable the affine transform or freeze the layer.

Demystifying Trainable and Non-Trainable Parameters in Batch Normalization

Batch normalization (BN) is a powerful technique used in deep learning to stabilize and accelerate training. The core idea behind BN is to normalize the output of a previous layer by subtracting the batch mean and dividing by the batch standard deviation. This is expressed by the following general formula:

x^=x−μBσB2+ε
y=γ⁢x^+β

Where:

  • x is the input to the batch normalization layer.
  • μB and σB2 are the mean and variance of the current mini-batch, respectively.
  • ε is a small constant added to avoid division by zero.
  • x^ is the normalized output.
  • γ and β are learnable parameters that scale and shift the normalized output.

Why This Formula is Helpful

The normalization step ensures that the input to each layer has a consistent distribution, which addresses the problem of “internal covariate shift”—where the distribution of inputs to a layer changes during training. By maintaining a stable distribution, the training process becomes more efficient, requiring less careful initialization of parameters and allowing for higher learning rates.

The addition of γ and β parameters allows the model to restore the capacity of the network to represent the original data distribution. This means that the model can learn any representation it could without normalization, but with the added benefits of stabilized and accelerated training. The use of batch normalization has been shown empirically to result in faster convergence and improved model performance, particularly in deeper networks.

Work through one feature by hand

Take three activation values, 2, 4 and 6, from the same feature in a dense layer. Let m be the number of values, xi the i-th value, μB the batch mean, σB2 the batch variance, and ε the positive stability constant. For dense inputs shaped (batch, features), Keras with axis=-1 does this calculation separately for each feature.

  1. Center. Add the values and divide by m = 3. The mean is (2 + 4 + 6) / 3 = 4. Subtracting it gives −2, 0 and 2.
  2. Measure spread. Square the centered values and divide their sum by m. The batch variance is (4 + 0 + 4) / 3 = 8/3.
  3. Normalize. With ε = 0.001, divide the three centered values by √(8/3 + 0.001). The normalized values are approximately −1.2245, 0 and 1.2245.
  4. Scale and shift. For γ = 2 and β = 1, multiply each normalized value by 2 and add 1. The outputs are approximately −1.4490, 1 and 3.4490.

The centered values sum to zero. Dividing them all by the same positive denominator keeps the mean at zero and changes the variance to σB2 / (σB2 + ε). Multiplying by γ then scales the variance by γ2, and adding β moves the mean to β. A negative γ reverses feature order.

Historical context. Internal covariate shift was the original paper’s motivation. Later experiments found that the optimization gains could persist despite deliberately introduced distribution changes and reported smoother optimization in the settings studied. The per-batch normalization above fixes only the first two moments of the normalized feature up to the ε adjustment. The learned affine parameters set a feature-wise scale and offset, while the original batch-specific mean and variance are shared statistics.

Understanding Trainable and Non-Trainable Parameters in Batch Normalization

In any batch normalization layer, there are typically four parameters associated with the normalization process:

  • γ (Scale) – Trainable
  • β (Shift) – Trainable
  • μ (Moving Mean) – Non-Trainable
  • σ (Moving Variance) – Non-Trainable

Trainable Parameters: γ and β

γ (Scale): This parameter scales the normalized output, allowing the model to control the variance after normalization. Without this parameter, the network might lose the ability to represent inputs with varying magnitudes.

β (Shift): This parameter shifts the normalized output, essentially adjusting the mean of the output distribution. It prevents the network from losing information about the original distribution after normalization.

Both γ and β are critical because they give the model the flexibility to learn the optimal scale and shift for the normalized activations during training. These parameters are updated via backpropagation, just like weights in a Dense layer.

Non-Trainable Parameters: μ and σ

μ (Moving Mean): This is the running average of the means computed over each mini-batch during training. It provides a stable mean during inference when the batch statistics might differ from the training phase.

σ (Moving Variance): Similar to the moving mean, this is the running average of the variance computed over each mini-batch. It stabilizes the variance during inference.

These parameters are crucial for ensuring that the batch normalization behaves consistently during inference. Unlike γ and β, μ and σ are not updated by backpropagation; instead, they are updated by tracking the statistics during training.

One layer, two sources of statistics

How Keras batch normalization processes one feature. A trainable layer reads the current batch in training mode and stored statistics in inference mode.
  1. 1. Choose statistics.
    Training uses this batch’s mean and variance. Inference uses their stored moving estimates.
  2. 2. Normalize.
    Subtract the selected mean and divide by the square root of the selected variance plus ε.
  3. 3. Apply γ and β.
    Multiply by the scale and add the shift when enabled.

During training, a separate state update blends the observed mean and variance into their moving estimates.

Batch Normalization: Training Mode vs. Inference / Frozen Mode Flow diagram showing how a BatchNormalization layer uses mini-batch mean and variance plus moving updates during training, versus stored moving mean and moving variance during inference or when trainable is False. TRAINING MODE (trainable=True, training=True) Mini-Batch Input x e.g. [2, 4, 6] Batch Statistics μ_B = 4.0, σ_B² = 8/3 Normalize x̂ (x − μ_B) / √(σ_B² + ε) Scale & Shift (Trainable) y = γ·x̂ + β (backprop) Non-Trainable State Update: s_new = p·s_old + (1 − p)·s_batch (stored μ, σ²) INFERENCE MODE (training=False) OR FROZEN LAYER (trainable=False) Input Example x Single or batch Stored Moving Stats μ_moving = 1.0, σ² = 17/12 Fixed Normalize x̂ No moving-stat update Apply Learned γ, β Deterministic prediction Key distinction: scale=False, center=False removes γ and β completely, but still updates moving stats when trainable=True.
Visual Sketch 1 — How Batch Normalization switches between Training and Inference. During training, each mini-batch drives normalization and updates the non-trainable moving estimates; during inference (or when trainable=False in Keras), the layer freezes and reuses the stored estimates for deterministic outputs.

For each statistic s, the Keras update is snew = p × sold + (1 − p) × sbatch, where p is Keras momentum. With momentum 0.75, previous mean 0 and batch mean 4, the new mean is 1. A previous variance of 1 becomes 0.75 × 1 + 0.25 × (8/3) = 17/12. So for input 4 and the same γ and β, the training output is 1, while inference after that update produces about 6.0392.

Terminology. The moving variance tracks squared deviations. We denote it σmoving2 to distinguish it from a standard deviation. The word non-trainable in a Keras summary describes optimizer-managed gradients. Keras can still change that state during a training forward pass.

When to Use Trainable and Non-Trainable Parameters

The decision of whether to keep γ and β trainable or fixed is often task-dependent. Here’s a guide on when and how to configure these parameters:

Correction to the fixed-scale example below. In Keras, scale=False, center=False omits both affine variables, which is equivalent to γ = 1 and β = 0. A trainable layer with those flags still uses batch statistics and updates its moving statistics under training=True. To preserve the learned γ and β and the moving statistics of a pretrained Keras batch normalization layer, set that layer’s trainable property to False. Keras then runs it in inference mode. If you change trainable flags for a compiled model, recompile before further fitting.

What each Keras configuration does after the layer is built
ConfigurationAffine variablesStatistics and state updates
Defaultsγ and β, both trainableA training call uses batch statistics and updates moving statistics
scale=False, center=FalseNeither variable existsA training call uses batch statistics and updates moving statistics
center=Falseγ is trainable, β is omittedA training call uses batch statistics and updates moving statistics
trainable=False with default affine flagsKeep γ and β as non-trainable weightsUse stored statistics and skip moving updates
Defaults with training=False on the callγ and β remain trainable weightsThis explicit inference call uses stored statistics and skips moving updates

1. Standard Use Case (Trainable γ and β)

In most scenarios, you want γ and β to be trainable because they allow the network to learn the appropriate scaling and shifting, which can significantly improve performance, especially in deeper networks.

tf.keras.layers.BatchNormalization(trainable=True)

This configuration is the default in most frameworks, as it provides the network with the flexibility needed to adapt during training.

2. Fixed Scale and Shift (Non-Trainable γ and β)

There are cases where you might want to fix γ and β, such as when your model needs to behave predictably without adapting during training, or in certain transfer learning scenarios where pre-trained layers are being fine-tuned.

tf.keras.layers.BatchNormalization(scale=False, center=False)

This approach is less common but can be useful in specific architectures where you want to prevent the model from overfitting or when the normalized inputs are already well-distributed.

3. Custom Configurations

You might also encounter situations where only one of these parameters (either γ or β) is trainable. This might be the case in models where scaling is crucial but shifting is not, or vice versa.

tf.keras.layers.BatchNormalization(scale=True, center=False)

These custom settings can be explored based on the behavior of your model on validation data.

Practical Example: Understanding the Model Summary

Consider the following model structure, which includes batch normalization:

model = tf.keras.Sequential([
    tf.keras.layers.Flatten(input_shape=[28, 28]),
    tf.keras.layers.Dense(300, kernel_initializer="he_normal", use_bias=False),
    tf.keras.layers.BatchNormalization(),
    tf.keras.layers.Activation("relu"),
    tf.keras.layers.Dense(100, kernel_initializer="he_normal", use_bias=False),
    tf.keras.layers.BatchNormalization(),
    tf.keras.layers.Activation("relu"),
    tf.keras.layers.Dense(10, activation="softmax")
    ])

When you inspect the model summary, you’ll notice a distinction between trainable and non-trainable parameters:

Corrected Keras summary. The three numbers printed in the original lesson below were miscounted. The exact architecture shown has 267,810 total parameters, of which 267,010 are trainable and 800 are non-trainable. These counts describe the model’s weights before training. Some compiled-model summaries also report optimizer state separately.

Flatten converts each 28 × 28 input into a 784-element vector. A bias-free dense layer with d input features and u output units contains d × u kernel entries. A dense layer with a bias adds u more. Each default batch normalization layer adds one scale, shift, moving mean and moving variance per output feature.

Parameter counts for the original Day 27 model
LayerCalculationTrainableNon-trainable
Dense (300)784 × 300235,2000
Batch normalization (300)2 × 300 for each column600600
Dense (100)300 × 10030,0000
Batch normalization (100)2 × 100 for each column200200
Dense (10, softmax)100 × 10 + 101,0100
Flatten and ReLUsShape change and activations00
Total267,010800
Day 27 Keras Model Parameter Breakdown: 267,810 Total Parameters Chart showing each layer’s trainable and non-trainable parameter counts and comparing Default BN, Affine Disabled, and Frozen BN configurations. Exact Parameter Breakdown of the Day 27 Keras Model (267,810 Total) Trainable = 267,010 (teal) · Non-Trainable = 800 (amber) · Notice why BN contributes 4 weights per feature (2 trainable + 2 non-trainable) Dense(300, use_bias=False) 235,200 trainable BatchNormalization (300) 600 trainable (γ, β) + 600 non-trainable (μ, σ²) Dense(100, use_bias=False) 30,000 trainable BatchNormalization (100) 200 trainable (γ, β) + 200 non-trainable (μ, σ²) Dense(10, softmax + bias) 1,010 trainable (100×10 + 10) Default: 267,010 T / 800 NT scale=False, center=False: 266,210 T / 800 NT Frozen BN: 266,210 T / 1,600 NT
Visual Sketch 2 — Exact Layer-by-Layer Parameter Counts vs. Keras BN Flags. Comparing Default, scale=False, center=False (drops 800 affine weights so total becomes 267,010), and Frozen BN (trainable=False, keeps total 267,810 but moves 800 affine weights into non-trainable).

Disabling both affine terms in both normalization layers removes 800 weights from the model. Freezing both normalization layers with default affine flags instead moves 800 weights from the trainable column to the non-trainable column. In either case, the dense layers still account for 266,210 trainable weights.

Original summary output retained for reference.

Total params: 271,346
    Trainable params: 268,978
    Non-trainable params: 2,368

Reproduce the counts and check training behavior

Run this Python example with TensorFlow. It checks the model’s weights, then compares a trainable, a frozen and an affine-disabled layer on the same synthetic batch.

Show the runnable TensorFlow example
"""Reproduce Day 27's parameter counts and Keras batch-normalization modes."""
import math

import tensorflow as tf

keras = tf.keras

def count(weights):
    return sum(math.prod(weight.shape) for weight in weights)

def check_model_counts():
    model = keras.Sequential([
        keras.Input(shape=(28, 28)),
        keras.layers.Flatten(),
        keras.layers.Dense(300, kernel_initializer="he_normal", use_bias=False),
        keras.layers.BatchNormalization(),
        keras.layers.ReLU(),
        keras.layers.Dense(100, kernel_initializer="he_normal", use_bias=False),
        keras.layers.BatchNormalization(),
        keras.layers.ReLU(),
        keras.layers.Dense(10, activation="softmax"),
    ])
    observed = (
        model.count_params(),
        count(model.trainable_weights),
        count(model.non_trainable_weights),
    )
    assert observed == (267_810, 267_010, 800), observed
    print("Total, trainable, non-trainable:", observed)

def check_training_modes():
    x = tf.constant([[2.0], [4.0], [6.0]])
    batch_variance = 8.0 / 3.0
    settings = {"momentum": 0.75, "epsilon": 1e-3}
    enabled = keras.layers.BatchNormalization(**settings)
    enabled.build((None, 1))
    enabled.gamma.assign([2.0])
    enabled.beta.assign([1.0])

    training = enabled(x, training=True)
    expected_training = 1.0 + 2.0 * (x - 4.0) / math.sqrt(batch_variance + 1e-3)
    tf.debugging.assert_near(training, expected_training)
    tf.debugging.assert_near(enabled.moving_mean, [1.0])
    moving_variance = 0.75 + 0.25 * batch_variance
    tf.debugging.assert_near(enabled.moving_variance, [moving_variance])

    expected_inference = 1.0 + 2.0 * (x - 1.0) / math.sqrt(moving_variance + 1e-3)
    tf.debugging.assert_near(enabled(x, training=False), expected_inference)

    enabled.trainable = False
    frozen = enabled(x, training=True)
    tf.debugging.assert_near(frozen, expected_inference)
    tf.debugging.assert_near(enabled.moving_mean, [1.0])
    tf.debugging.assert_near(enabled.moving_variance, [moving_variance])
    assert count(enabled.trainable_weights) == 0
    assert count(enabled.non_trainable_weights) == 4

    affine_off = keras.layers.BatchNormalization(scale=False, center=False, **settings)
    normalized = affine_off(x, training=True)
    expected_normalized = (x - 4.0) / math.sqrt(batch_variance + 1e-3)
    tf.debugging.assert_near(normalized, expected_normalized)
    tf.debugging.assert_near(affine_off.moving_mean, [1.0])
    tf.debugging.assert_near(affine_off.moving_variance, [moving_variance])
    assert affine_off.gamma is None and affine_off.beta is None
    assert count(affine_off.trainable_weights) == 0
    assert count(affine_off.non_trainable_weights) == 2
    print("Training, inference, freezing, and disabled affine transformation verified")

if __name__ == "__main__":
    print(f"TensorFlow {tf.__version__} / Keras {keras.__version__}")
    check_model_counts()
    check_training_modes()

How to Interpret These Numbers:

– Impact on Model Capacity: Trainable parameters directly affect the model’s capacity to learn from data. More trainable parameters typically allow the model to capture more complex patterns, but they also increase the risk of overfitting.

– Role During Inference: Non-trainable parameters ensure consistent behavior during inference. They allow the model to maintain stable predictions even when batch statistics vary between training and inference.

Choosing the Right Configuration

The choice between trainable and non-trainable configurations should be informed by:

– Model Complexity: For simpler models, fixed γ and β might suffice, whereas deeper networks benefit from trainable parameters.

– Training Data: Large, diverse datasets generally require trainable γ and β to adapt well, while small datasets might benefit from fixed parameters to prevent overfitting.

– Transfer Learning: In transfer learning, freezing γ and β in the early layers (especially those from a pre-trained model) might help maintain the learned features, while allowing later layers to adapt to new data.

Conclusion

Understanding the distinction between trainable and non-trainable parameters in batch normalization is essential for fine-tuning neural networks. By strategically configuring these parameters, you can enhance model performance, stabilize training, and ensure consistency during inference. Always consider the specific requirements of your task and experiment with different settings to find the optimal configuration.

This nuanced approach to batch normalization will empower you to make informed decisions when designing and training deep learning models, leading to more robust and effective results.

 

Practice and solutions

Common mistakes

  • Using training mode for evaluation. Predictions can depend on which other inputs share the batch and can change the moving statistics. Call evaluation and inference with the appropriate inference mode. For a pretrained backbone called during fine-tuning, follow Keras’s batch normalization guidance.
  • Reading the wrong feature axis. With channels-last convolutional input (N, H, W, C), axis=-1 stores one set of weights per channel and pools statistics over the batch and spatial dimensions.
  • Choosing freezing from dataset size alone. Consider whether existing moving statistics match the target inputs and whether the training batches provide stable estimates. Compare the supported configurations on held-out data.
A 64-feature layer uses center=False. How many weights does it have?

It has 64 trainable scales and 128 non-trainable moving statistics, for 192 weights. Turning off scale too leaves 128 weights, all moving statistics.

What happens to the counts if you freeze both normalization layers in the original model?

The total stays 267,810. The 800 affine values become non-trainable, leaving 266,210 trainable weights and 1,600 non-trainable weights.

What moving mean follows a batch mean of 8 after the worked example?

With the previous moving mean of 1 and momentum of 0.75, the next update is 0.75 × 1 + 0.25 × 8 = 2.75.

References

Leave a reply

Your email address will not be published. Required fields are marked *

You Can Also Learn Deep Learning in 80 Days Inside the iOS App Continue this roadmap in a focused mobile study experience with offline access, flashcards, notes, and progress tracking.
Open on the App Store