Bird
Raised Fist0
TensorFlowml~5 mins

Weight initialization strategies in TensorFlow

Choose your learning style10 modes available
Introduction

Weight initialization helps the model learn better and faster by starting with good values for its weights.

When building a neural network to avoid slow or stuck learning.
When training deep models to prevent problems like vanishing or exploding gradients.
When experimenting with different model architectures to improve accuracy.
When using activation functions like ReLU or sigmoid that need special care in initialization.
Syntax
TensorFlow
initializer = tf.keras.initializers.HeNormal()
layer = tf.keras.layers.Dense(units=64, activation='relu', kernel_initializer=initializer)

You choose an initializer and pass it to the layer's kernel_initializer argument.

Common initializers include GlorotUniform, HeNormal, and RandomNormal.

Examples
GlorotUniform is good for layers with sigmoid or tanh activations.
TensorFlow
initializer = tf.keras.initializers.GlorotUniform()
layer = tf.keras.layers.Dense(32, activation='relu', kernel_initializer=initializer)
HeNormal works well with ReLU activations to keep gradients stable.
TensorFlow
initializer = tf.keras.initializers.HeNormal()
layer = tf.keras.layers.Dense(64, activation='relu', kernel_initializer=initializer)
RandomNormal initializes weights with small random values from a normal distribution.
TensorFlow
initializer = tf.keras.initializers.RandomNormal(mean=0., stddev=0.05)
layer = tf.keras.layers.Dense(10, activation='softmax', kernel_initializer=initializer)
Sample Model

This code builds a small neural network using the HeNormal initializer for weights. It trains on random data for 3 epochs and then makes predictions on new random inputs.

TensorFlow
import tensorflow as tf
from tensorflow.keras import layers, models

# Create a simple model with HeNormal initializer
initializer = tf.keras.initializers.HeNormal()

model = models.Sequential([
    layers.Dense(64, activation='relu', kernel_initializer=initializer, input_shape=(20,)),
    layers.Dense(10, activation='softmax', kernel_initializer=initializer)
])

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# Generate dummy data
import numpy as np
x_train = np.random.rand(100, 20).astype('float32')
y_train = np.random.randint(0, 10, size=(100,))

# Train the model
history = model.fit(x_train, y_train, epochs=3, batch_size=10, verbose=2)

# Make predictions on new data
x_test = np.random.rand(5, 20).astype('float32')
predictions = model.predict(x_test)

print('Predictions shape:', predictions.shape)
print('First prediction:', predictions[0])
OutputSuccess
Important Notes

Choosing the right initializer can help your model train faster and avoid common problems.

He initialization is best for ReLU activations, while Glorot (Xavier) is good for sigmoid or tanh.

Always set the initializer when creating layers to control how weights start.

Summary

Weight initialization sets starting values for model weights to help learning.

Use HeNormal for ReLU and GlorotUniform for sigmoid/tanh activations.

Proper initialization prevents slow or stuck training and improves accuracy.

Practice

(1/5)
1. Which weight initialization strategy is best suited for layers using ReLU activation in TensorFlow?
easy
A. Zeros initializer
B. GlorotUniform initializer
C. RandomNormal initializer with mean 0
D. HeNormal initializer

Solution

  1. Step 1: Understand activation and initialization relation

    ReLU activation benefits from initial weights that maintain variance through layers to avoid dying neurons.
  2. Step 2: Match initializer to activation

    HeNormal initializer is designed for ReLU, scaling weights to keep variance stable.
  3. Final Answer:

    HeNormal initializer -> Option D
  4. Quick Check:

    ReLU uses HeNormal [OK]
Hint: Use HeNormal for ReLU activations to keep variance stable [OK]
Common Mistakes:
  • Choosing GlorotUniform for ReLU layers
  • Using zeros initializer causing no learning
  • RandomNormal without scaling causes slow training
2. Which of the following is the correct syntax to initialize weights with GlorotUniform in TensorFlow?
easy
A. tf.keras.initializers.glorot_uniform()
B. tf.initializers.GlorotUniform()
C. tf.keras.initializers.GlorotUniform()
D. tf.keras.initializers.Glorot_uniform()

Solution

  1. Step 1: Recall TensorFlow initializer module

    Initializers are accessed via tf.keras.initializers with exact class names.
  2. Step 2: Check correct class name and casing

    The correct class name is GlorotUniform with capital G and U, called as a class with parentheses.
  3. Final Answer:

    tf.keras.initializers.GlorotUniform() -> Option C
  4. Quick Check:

    Correct class name and module path [OK]
Hint: Use exact class name with correct casing and parentheses [OK]
Common Mistakes:
  • Using lowercase function names instead of class
  • Missing parentheses after class name
  • Using wrong module path tf.initializers
3. What will be the output shape and initializer type of the following TensorFlow layer?
layer = tf.keras.layers.Dense(10, kernel_initializer=tf.keras.initializers.HeNormal())
print(layer.kernel_initializer)
medium
A. GlorotUniform initializer object, output shape (None, 10)
B. HeNormal initializer object, output shape (None, 10)
C. HeNormal initializer object, output shape (10, 10)
D. RandomNormal initializer object, output shape (None, 10)

Solution

  1. Step 1: Identify initializer and layer output

    The layer uses HeNormal initializer explicitly for kernel weights and has 10 output units.
  2. Step 2: Understand output shape of Dense layer

    Dense layers output shape is (batch_size, units), so shape is (None, 10) before input is given.
  3. Final Answer:

    HeNormal initializer object, output shape (None, 10) -> Option B
  4. Quick Check:

    HeNormal used and output units = 10 [OK]
Hint: Dense output shape is (None, units); initializer matches given class [OK]
Common Mistakes:
  • Confusing output shape with kernel shape
  • Assuming default initializer instead of HeNormal
  • Mixing initializer types
4. You wrote this code to initialize weights but get an error:
layer = tf.keras.layers.Dense(5, kernel_initializer='he_normal')
model = tf.keras.Sequential([layer])
model.build(input_shape=(None, 3))
print(layer.kernel_initializer())
What is the cause of the error?
medium
A. Calling kernel_initializer as a function without arguments
B. Using string 'he_normal' instead of initializer object
C. Not specifying bias_initializer
D. Missing input_shape in layer constructor

Solution

  1. Step 1: Understand kernel_initializer attribute type

    kernel_initializer is an initializer object, not a callable function without arguments.
  2. Step 2: Identify error cause

    Calling kernel_initializer() without arguments causes error because it expects shape and dtype parameters.
  3. Final Answer:

    Calling kernel_initializer as a function without arguments -> Option A
  4. Quick Check:

    Initializer needs shape args, can't call empty () [OK]
Hint: Don't call kernel_initializer() without shape and dtype [OK]
Common Mistakes:
  • Confusing string initializer with object
  • Ignoring required arguments for initializer call
  • Assuming bias_initializer causes this error
5. You want to initialize weights for a model with mixed activations: ReLU in some layers and sigmoid in others. Which strategy best improves training speed and accuracy?
hard
A. Use HeNormal for ReLU layers and GlorotUniform for sigmoid layers
B. Use GlorotUniform for all layers regardless of activation
C. Use RandomNormal with mean 0 and stddev 1 for all layers
D. Use Zeros initializer for all layers to start from zero

Solution

  1. Step 1: Match initializers to activation functions

    HeNormal suits ReLU to maintain variance; GlorotUniform suits sigmoid/tanh to avoid saturation.
  2. Step 2: Understand impact on training

    Proper matching prevents slow or stuck training and improves accuracy by keeping gradients healthy.
  3. Final Answer:

    Use HeNormal for ReLU layers and GlorotUniform for sigmoid layers -> Option A
  4. Quick Check:

    Match initializer to activation for best training [OK]
Hint: Match HeNormal to ReLU, GlorotUniform to sigmoid/tanh [OK]
Common Mistakes:
  • Using same initializer for all activations
  • Using zeros initializer causing no learning
  • Using RandomNormal without scaling
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard