How to perform mean subtraction and normalization with Tensorflow
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
Mean subtraction and normalization are essential preprocessing steps for neural networks. They center the data around zero and scale features to comparable ranges, which helps gradient descent converge faster and prevents features with large values from dominating the learning process. TensorFlow provides several ways to implement these operations.
Why Normalize?
Without normalization, features on different scales cause problems:
After normalization, all features have similar scales, enabling smoother optimization.
Mean Subtraction
Center data by subtracting the mean of each feature:
Normalization Methods
Min-Max Normalization (Scale to [0, 1])
Z-Score Normalization (Standardization)
Per-Image Normalization
Common for image data:
Using tf.keras.layers.Normalization
The Keras Normalization layer adapts to data and applies z-score normalization:
Using tf.keras.layers.Rescaling
For simple scaling (e.g., pixel values):
ImageNet-Style Normalization
Pre-trained models (ResNet, VGG, etc.) expect ImageNet normalization:
Batch Normalization During Training
Batch normalization normalizes activations within the network during training:
Using tf.data Pipeline
Apply normalization in the data pipeline:
Common Pitfalls
- Test Data Consistency: It is critical to apply the same mean subtraction and normalization parameters (mean, min, max, std deviation) calculated from the training data to the test and validation datasets. Never compute statistics from test data.
- Feature-Wise Normalization: Each feature should be normalized independently for optimal performance. Do not compute a single mean/std across all features.
- Batch Normalization: During model training, TensorFlow offers Batch Normalization as an additional normalization technique that normalizes intermediate activations, which is different from input normalization.
- Division by zero: When the standard deviation is zero (constant feature), division fails. Add a small epsilon:
(data - mean) / (std + 1e-7). - Integer overflow: Image data stored as
uint8overflows when subtracting the mean. Cast tofloat32first:tf.cast(image, tf.float32). - Training vs inference:
BatchNormalizationbehaves differently during training and inference. Always settraining=True/Falseappropriately or usemodel.fit()/model.predict()which handle it automatically.
Summary
- Mean subtraction centers data around zero; normalization scales features to comparable ranges
- Use
tf.keras.layers.Normalizationwith.adapt()for automatic z-score normalization - Use
tf.keras.layers.Rescalingfor simple value scaling (e.g., pixel values) - For pre-trained models, use the model's
preprocess_inputfunction for correct normalization - Always compute normalization statistics from training data and apply them to test/validation data
Related reading
- How to perform tf.image.per_image_standardization on a batch of images in tensorflow
- How to Plot and save a tensor as an image in Tensorflow
- How to plot grid of images in tensorboard?
- how to plot the tensorflow neural network object
- How to permutate tranposition in tensorflow?
- How to pickle Keras model?
- How to pick color palette for a pie-chart?
- How to plot a high resolution graph
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.