xbe.at Work with me

Deep learning / Neural network fundamentals

Weights and Biases in Neural Networks in Python

9 min read8 sectionsCC0

Contents
  1. The Anatomy of a Neuron
  2. Initializing Weights and Biases
  3. Optimization and Gradient Descent
  4. Regularization and Weight Decay
  5. Batch Normalization and Its Effect on Weights
  6. Visualizing and Interpreting Weights
  7. Common pitfalls
  8. Key takeaways

Neural networks are fundamentally mathematical functions defined by a vast collection of parameters. These parameters consist of weights, which determine the strength and direction of connections between neurons, and biases, which shift the activation threshold of each neuron. While the architecture of a network defines its capacity to represent complex functions, the specific values of its weights and biases determine what it actually learns. Mastering the manipulation, initialization, and optimization of these parameters is the core of deep learning engineering. It is not merely about stacking layers but about ensuring that the numerical landscape of the loss function is navigable, stable, and efficient.

The importance of understanding weights and biases extends beyond theoretical curiosity. Poor initialization can lead to vanishing or exploding gradients, causing training to stall or diverge entirely. Inadequate regularization can result in models that memorize noise rather than learning generalizable patterns. Conversely, sophisticated techniques like batch normalization, weight decay, and quantization allow practitioners to train deeper, faster, and more robust models. Whether you are deploying a lightweight model on an edge device or fine-tuning a large language model, the behavior of your system is dictated by how these numerical values are managed throughout the lifecycle of the model.

This tutorial explores the practical mechanics of weights and biases in Python. We will move from the foundational linear algebra of a single neuron to advanced strategies for initialization, optimization, regularization, and deployment. By building a cohesive example using PyTorch, we will demonstrate how these concepts interact in real-world scenarios, highlighting common failure modes and the specific tools used to mitigate them.

The Anatomy of a Neuron

At its most basic level, a neuron computes a weighted sum of its inputs, adds a bias term, and passes the result through a non-linear activation function. Mathematically, for an input vector \mathbf{x}, weight vector \mathbf{w}, and bias b, the output y is:

y = \sigma(\mathbf{w} \cdot \mathbf{x} + b)

Here, \sigma represents the activation function, such as ReLU or Sigmoid. The weight \mathbf{w} scales the input, determining how much influence a particular feature has on the neuron's output. The bias b allows the activation function to be shifted left or right, enabling the neuron to fire even when all inputs are zero. Without biases, the decision boundary of a linear layer would always pass through the origin, severely limiting the model's expressive power.

In practice, we process inputs in batches. If we have a batch of inputs X with shape (N, D), weights W with shape (D, H), and biases b with shape (H,), the forward pass for a hidden layer is computed as:

Z = XW + b

The addition of b is broadcast across the batch dimension. This vectorized operation is the backbone of all deep learning frameworks. Understanding this matrix multiplication is crucial because it reveals why weight initialization is so critical: if the values in W are too large, Z explodes; if too small, Z vanishes.

Initializing Weights and Biases

Random initialization is not arbitrary. The goal is to keep the variance of activations and gradients consistent across layers. If the variance grows exponentially with depth, gradients explode; if it shrinks, they vanish. Two standard techniques address this: Xavier (Glorot) initialization and He initialization.

Xavier initialization is designed for symmetric activation functions like Tanh or Sigmoid. It draws weights from a uniform distribution with bounds \pm \sqrt{\frac{6}{n_{in} + n_{out}}}. This ensures that the variance of the activations is approximately the same in the forward and backward passes.

He initialization is tailored for ReLU activations. Since ReLU zeroes out half of the inputs, it effectively halves the variance. To compensate, He initialization scales the weights by \sqrt{\frac{2}{n_{in}}}. Using Xavier initialization with ReLU often leads to dying neurons, where weights become zero and gradients cease to flow.

import torch
import torch.nn as nn
import numpy as np

# Define a simple MLP
class SimpleMLP(nn.Module):
    def __init__(self, input_dim, hidden_dim, output_dim):
        super(SimpleMLP, self).__init__()
        self.fc1 = nn.Linear(input_dim, hidden_dim)
        self.fc2 = nn.Linear(hidden_dim, output_dim)
        
        # Initialize weights
        # He initialization for ReLU layers
        nn.init.kaiming_normal_(self.fc1.weight, mode='fan_in', nonlinearity='relu')
        nn.init.zeros_(self.fc1.bias)
        
        # Xavier initialization for output layer (if using Sigmoid/Tanh) 
        # or He if using ReLU. Here we assume ReLU for hidden, linear for output.
        nn.init.kaiming_normal_(self.fc2.weight, mode='fan_in', nonlinearity='linear')
        nn.init.zeros_(self.fc2.bias)

    def forward(self, x):
        x = torch.relu(self.fc1(x))
        x = self.fc2(x)
        return x

# Instantiate and inspect
model = SimpleMLP(10, 64, 1)
print(f"Weight mean: {model.fc1.weight.mean().item():.4f}")
print(f"Weight std: {model.fc1.weight.std().item():.4f}")
Weight mean: 0.0399
Weight std: 0.4642

This code initializes a multi-layer perceptron. Notice that biases are initialized to zero. This is standard practice because biases do not suffer from the same symmetry-breaking issues as weights. The weights are initialized using kaiming_normal_, which implements He initialization. The output shows the statistical properties of the initialized weights. For a layer with 10 inputs, the standard deviation should be close to \sqrt{2/10} \approx 0.447. If you observe a standard deviation significantly different from this, your initialization strategy may be mismatched with your activation function.

Optimization and Gradient Descent

Training a neural network involves minimizing a loss function L(\theta), where \theta represents all weights and biases. Gradient descent updates these parameters by moving in the direction of the steepest descent. The update rule for a weight w is:

w_{t+1} = w_t - \eta \nabla_w L

where \eta is the learning rate. While simple gradient descent works, it is often slow and sensitive to the curvature of the loss landscape. Modern optimizers like Adam and RMSProp adapt the learning rate for each parameter individually. Adam combines momentum (accelerating in consistent directions) and adaptive learning rates (slowing down in noisy directions).

A critical aspect of optimization is the interaction between the learning rate and the magnitude of the gradients. If the learning rate is too high, the optimization oscillates around the minimum. If too low, convergence is painfully slow. Furthermore, without proper regularization, the optimizer may find a minimum that fits the training data perfectly but fails on unseen data.

Regularization and Weight Decay

Overfitting occurs when a model learns noise in the training data. Regularization techniques constrain the weights to prevent them from growing too large. L2 regularization, also known as weight decay, adds a penalty term proportional to the square of the weights to the loss function:

L_{total} = L_{data} + \lambda \sum w^2

This penalty encourages the optimizer to keep weights small, leading to smoother decision boundaries and better generalization. In PyTorch, weight decay is typically applied directly in the optimizer, not in the loss function calculation, for numerical stability and efficiency.

import torch.optim as optim

# Define optimizer with weight decay
optimizer = optim.Adam(model.parameters(), lr=0.001, weight_decay=1e-4)

# Training loop snippet
# for epoch in range(num_epochs):
#     optimizer.zero_grad()
#     outputs = model(inputs)
#     loss = criterion(outputs, targets)
#     loss.backward()
#     optimizer.step()

In this snippet, weight_decay=1e-4 applies L2 regularization to all parameters. It is important to note that weight decay should generally not be applied to bias parameters or parameters in batch normalization layers, as these do not contribute to overfitting in the same way. Some advanced optimizers like AdamW separate the weight decay from the gradient update, providing better generalization performance than standard Adam with L2 regularization.

Batch Normalization and Its Effect on Weights

Batch normalization (BN) normalizes the inputs of each layer to have zero mean and unit variance. This reduces internal covariate shift, allowing for higher learning rates and faster convergence. However, BN introduces its own learnable parameters: scale (\gamma) and shift (\beta).

When BN is used, the scale of the preceding layer's weights becomes less critical because BN rescales the activations. In fact, the weight magnitude is effectively absorbed by the BN layer. This means that weight decay applied to the layer before BN has a different effect than in a network without BN. In some cases, applying weight decay to the weights before BN can be redundant or even detrimental if not tuned correctly.

class MLPWithBN(nn.Module):
    def __init__(self, input_dim, hidden_dim, output_dim):
        super(MLPWithBN, self).__init__()
        self.fc1 = nn.Linear(input_dim, hidden_dim, bias=False) # Bias not needed before BN
        self.bn1 = nn.BatchNorm1d(hidden_dim)
        self.fc2 = nn.Linear(hidden_dim, output_dim)
        
        nn.init.kaiming_normal_(self.fc1.weight, mode='fan_in', nonlinearity='relu')
        nn.init.kaiming_normal_(self.fc2.weight, mode='fan_in', nonlinearity='linear')
        nn.init.zeros_(self.fc2.bias)

    def forward(self, x):
        x = self.fc1(x)
        x = self.bn1(x)
        x = torch.relu(x)
        x = self.fc2(x)
        return x

Note that bias=False is set for the linear layer preceding the batch normalization. Since BN subtracts the mean, any bias added before BN is redundant and computationally wasteful. The BN layer's \beta parameter effectively replaces the bias. This structural detail is often overlooked but is essential for efficient implementation.

Visualizing and Interpreting Weights

Understanding what a network has learned often requires inspecting the weights directly. For convolutional neural networks (CNNs), visualizing the first layer's filters can reveal whether the network has learned edge detectors, color blobs, or noise. For fully connected networks, weight matrices can be visualized as heatmaps to identify strong connections or sparsity patterns.

import matplotlib.pyplot as plt

# Extract weights from the first layer
weights = model.fc1.weight.detach().cpu().numpy()

plt.figure(figsize=(10, 5))
plt.imshow(weights, cmap='viridis', aspect='auto')
plt.colorbar(label='Weight Value')
plt.title('Weight Matrix of First Layer')
plt.xlabel('Input Feature Index')
plt.ylabel('Hidden Neuron Index')
plt.show()
Figure drawn by the code above

This visualization displays the weight matrix. Bright colors indicate strong positive weights, while dark colors indicate strong negative weights. A random initialization would show a uniform noise pattern. A trained network might show structured patterns, such as groups of neurons with similar weight profiles, indicating that the network has learned to group similar features. If the weights appear uniformly small or zero, it may indicate that the learning rate was too low or the model is underfitting.

Common pitfalls

  • Ignoring Initialization Mismatch: Using Xavier initialization with ReLU activations often leads to vanishing gradients. Always match the initialization scheme to the activation function.
  • Applying Weight Decay to Biases and BN Parameters: Weight decay on biases and batch normalization parameters can harm performance. Most modern optimizers allow you to exclude these parameters from decay.
  • Forgetting to Set Model Mode: During inference, batch normalization layers must use running statistics, not batch statistics. Forgetting to call model.eval() leads to incorrect predictions.
  • Overlooking Gradient Clipping: In recurrent networks or very deep transformers, gradients can explode. Failing to clip gradients (torch.nn.utils.clip_grad_norm_) can cause training instability.
  • Treating All Weights Equally: In transfer learning, freezing all layers except the last one is a common strategy. However, fine-tuning the last few layers often yields better results than training from scratch or freezing everything.

Key takeaways

  • Weights and biases are the learnable parameters that define the function of a neural network.
  • Proper initialization (He for ReLU, Xavier for Tanh) is critical for stable training.
  • Weight decay (L2 regularization) prevents overfitting by penalizing large weights.
  • Batch normalization changes the role of biases and weights in preceding layers.
  • Visualization of weights provides insight into learned features and training health.
  • Optimizers like AdamW handle weight decay more effectively than standard Adam.

Keep going

More in Neural network fundamentals

All of them