Angad Sandhu
Search
Browse
On this page

6.1 Neural Network Fundamentals

6.1 Neural Network Fundamentals


Key Concepts

6.1.1 Feedforward Networks

A feedforward neural network (FNN) is the simplest type of artificial neural network where information flows in one direction—from input to output—without cycles.

Architecture

Input Layer → Hidden Layer(s) → Output Layer

x₁ ──┐
     ├──→ [h₁] ──┐
x₂ ──┤           ├──→ [o₁] → ŷ
     ├──→ [h₂] ──┤
x₃ ──┘           └──→ [o₂]

Components

  1. Neurons (Nodes): Basic computational units

    • Receive inputs, apply weights, sum them, add bias, apply activation
    • output = activation(Σ(wᵢxᵢ) + b)
  2. Layers:

    • Input layer: Receives raw features (no computation)
    • Hidden layers: Learn intermediate representations
    • Output layer: Produces final predictions
  3. Weights & Biases: Learnable parameters

    • Weights (W): Scale the importance of inputs
    • Biases (b): Allow shifting the activation function

Forward Pass

# Single layer computation
z = W @ x + b      # Linear transformation
a = activation(z)  # Non-linear activation

# Full network (L layers)
a[0] = x  # Input
for l in range(1, L+1):
    z[l] = W[l] @ a[l-1] + b[l]
    a[l] = activation(z[l])
output = a[L]

Universal Approximation Theorem

A feedforward network with a single hidden layer containing a finite number of neurons can approximate any continuous function on compact subsets of Rⁿ, given appropriate activation functions. This doesn't guarantee:

  • Efficient learning
  • Good generalization
  • Practical number of neurons needed

6.1.2 Backpropagation

Backpropagation is the algorithm for computing gradients of the loss with respect to all parameters, enabling gradient-based optimization.

The Chain Rule

For a composite function f(g(x)), the derivative is:

df/dx = df/dg × dg/dx

Backprop Algorithm

  1. Forward pass: Compute and cache all intermediate values (z, a for each layer)
  2. Compute output loss: L = loss(ŷ, y)
  3. Backward pass: Propagate gradients from output to input
# Output layer gradient
dL/da[L] = derivative of loss w.r.t. output

# For each layer l from L down to 1:
dL/dz[l] = dL/da[l] * activation'(z[l])  # Element-wise
dL/dW[l] = dL/dz[l] @ a[l-1].T           # Weight gradient
dL/db[l] = sum(dL/dz[l], axis=1)         # Bias gradient
dL/da[l-1] = W[l].T @ dL/dz[l]           # Propagate to previous layer

Computational Graph View

x → [W₁] → z₁ → [ReLU] → a₁ → [W₂] → z₂ → [softmax] → ŷ → [loss] → L
                                                                    ↓
Backward: ←─────────────────────────────────────────────────────────┘

Key Insights

  • Gradients flow backward through the same computational graph
  • Each operation must define both forward and backward passes
  • Caching intermediate values is essential (memory vs. recomputation tradeoff)

6.1.3 Activation Functions

Activation functions introduce non-linearity, enabling networks to learn complex patterns.

Why Non-linearity?

Without activation functions, stacking linear layers collapses to a single linear transformation:

W₂(W₁x + b₁) + b₂ = (W₂W₁)x + (W₂b₁ + b₂) = W'x + b'

Common Activation Functions

FunctionFormulaRangeDerivative
Sigmoidσ(x) = 1/(1+e⁻ˣ)(0, 1)σ(x)(1-σ(x))
Tanh(eˣ-e⁻ˣ)/(eˣ+e⁻ˣ)(-1, 1)1 - tanh²(x)
ReLUmax(0, x)[0, ∞)0 if x<0, 1 if x>0
Leaky ReLUmax(αx, x)(-∞, ∞)α if x<0, 1 if x>0
ELUx if x>0, α(eˣ-1) if x≤0(-α, ∞)1 if x>0, α·eˣ if x≤0
GELUx·Φ(x)(-∞, ∞)Complex
Swishx·σ(x)(-∞, ∞)Complex
Softmaxeˣⁱ/Σeˣʲ(0, 1), sums to 1pᵢ(1-pᵢ) for i=j

ReLU: The Default Choice

ReLU(x) = max(0, x)

     │    /
     │   /
─────┼──/────
     │

Advantages:

  • Computationally efficient (just a threshold)
  • No vanishing gradient for positive inputs
  • Induces sparsity (many neurons output 0)
  • Faster convergence than sigmoid/tanh

Disadvantages:

  • "Dying ReLU": neurons can get stuck at 0 if they always receive negative inputs
  • Not zero-centered

Sigmoid vs Softmax

  • Sigmoid: Binary classification, multi-label (independent probabilities)
  • Softmax: Multi-class classification (mutually exclusive, sums to 1)

6.1.4 Vanishing and Exploding Gradients

These are fundamental problems in training deep networks.

Vanishing Gradients

Problem: Gradients become exponentially small as they propagate backward through many layers.

Cause: Chain rule multiplication with values < 1

∂L/∂W₁ = ∂L/∂aₙ × ∂aₙ/∂aₙ₋₁ × ... × ∂a₂/∂a₁ × ∂a₁/∂W₁

If each ∂aᵢ/∂aᵢ₋₁ ≈ 0.1, then after 10 layers: 0.1¹⁰ = 10⁻¹⁰

Symptoms:

  • Early layers learn very slowly or not at all
  • Loss plateaus early in training
  • Sigmoid/tanh saturate at extremes (derivative → 0)

Solutions:

  • ReLU activation (gradient = 1 for positive inputs)
  • Proper weight initialization (Xavier, He)
  • Batch normalization
  • Skip connections (ResNet)
  • LSTM/GRU for sequences

Exploding Gradients

Problem: Gradients become exponentially large, causing unstable updates.

Cause: Chain rule multiplication with values > 1

If each factor ≈ 2, then after 10 layers: 2¹⁰ = 1024

Symptoms:

  • Loss becomes NaN or Inf
  • Weights grow unboundedly
  • Training diverges

Solutions:

  • Gradient clipping: grad = min(grad, threshold)
  • Proper weight initialization
  • Lower learning rate
  • Batch normalization

6.1.5 Batch Normalization

Batch normalization normalizes layer inputs to stabilize and accelerate training.

Algorithm

For a mini-batch B = {x₁, ..., xₘ}:

# 1. Compute batch statistics
μ_B = (1/m) * Σxᵢ           # Batch mean
σ²_B = (1/m) * Σ(xᵢ - μ_B)²  # Batch variance

# 2. Normalize
x̂ᵢ = (xᵢ - μ_B) / √(σ²_B + ε)  # ε for numerical stability

# 3. Scale and shift (learnable parameters)
yᵢ = γ * x̂ᵢ + β  # γ (scale), β (shift) are learned

Why It Works

  1. Reduces internal covariate shift: Layer inputs have consistent distribution
  2. Allows higher learning rates: Gradients are more stable
  3. Acts as regularization: Batch statistics add noise
  4. Reduces sensitivity to initialization: Normalizes regardless of input scale

Training vs Inference

  • Training: Use batch statistics (μ_B, σ²_B)
  • Inference: Use running averages computed during training
    μ_running = momentum * μ_running + (1 - momentum) * μ_B

Placement

  • Originally: after linear, before activation
  • Modern practice: often before linear (pre-activation) or after activation

Layer Normalization (Alternative)

  • Normalizes across features instead of batch
  • Used in Transformers (batch size = 1 friendly)
  • No dependency on batch statistics

6.1.6 Dropout

Dropout is a regularization technique that randomly "drops" neurons during training.

Algorithm

# Training
mask = (random(shape) > p)  # p = dropout probability
output = (input * mask) / (1 - p)  # Scale to maintain expected value

# Inference
output = input  # No dropout, no scaling needed (inverted dropout)

Visualization

Training (p=0.5):          Inference:
[●]─┬─[●]─┬─[●]           [●]─┬─[●]─┬─[●]
    │     │                   │     │
[○]─┼─[●]─┼─[○]  →        [●]─┼─[●]─┼─[●]
    │     │                   │     │
[●]─┴─[○]─┴─[●]           [●]─┴─[●]─┴─[●]

○ = dropped, ● = active

Why It Works

  1. Prevents co-adaptation: Neurons can't rely on specific other neurons
  2. Ensemble effect: Training many "thinned" networks, averaging at test time
  3. Adds noise: Acts as data augmentation on activations
  4. Encourages redundancy: Features must be useful independently

Typical Values

  • Hidden layers: p = 0.5
  • Input layer: p = 0.2 (less aggressive)
  • CNNs: Often lower (p = 0.25) or use spatial dropout

6.1.7 Weight Initialization

Proper initialization is crucial for stable training.

The Problem

  • Too small: Activations shrink to zero, vanishing gradients
  • Too large: Activations explode, exploding gradients

Xavier/Glorot Initialization

For layers with sigmoid or tanh activation:

W ~ Uniform(-√(6/(n_in + n_out)), √(6/(n_in + n_out)))
# or
W ~ Normal(0, √(2/(n_in + n_out)))

He Initialization

For ReLU activation (accounts for ReLU zeroing half the values):

W ~ Normal(0, √(2/n_in))

Why These Work

  • Maintain variance of activations across layers
  • Prevent vanishing/exploding at initialization
  • Based on analysis of forward and backward pass variance

Questions & Answers

⭐ Q1: What are the basics of ANNs? What is the benefit of ReLU activation?

Answer:

Artificial Neural Networks (ANNs) are computational models inspired by biological neurons, consisting of:

  1. Layers: Input → Hidden → Output
  2. Neurons: Compute weighted sum of inputs, add bias, apply activation
  3. Forward propagation: Data flows through network to produce predictions
  4. Backpropagation: Gradients flow backward to update weights
  5. Training: Minimize loss via gradient descent

Mathematical formulation:

z = Wx + b        (linear transformation)
a = f(z)          (activation function)
L = loss(ŷ, y)    (compute error)
W = W - α∇L       (update weights)

Benefits of ReLU:

  1. Computational efficiency: Simple threshold operation max(0, x)
  2. No vanishing gradient (for positive inputs): Gradient is exactly 1
  3. Sparse activation: Many neurons output 0, leading to efficient representations
  4. Faster convergence: Typically 6x faster than sigmoid/tanh
  5. Biological plausibility: More similar to actual neuron firing patterns

ReLU drawbacks to mention:

  • "Dying ReLU" problem: Neurons stuck at 0
  • Not zero-centered
  • Solutions: Leaky ReLU, ELU, or careful initialization

Q2: What happens in a neural network if you remove all hidden layers?

Answer:

Without hidden layers, you have a single-layer network that can only learn linear transformations.

For classification (with softmax):

ŷ = softmax(Wx + b)

This is equivalent to logistic regression (binary) or softmax regression (multiclass).

For regression:

ŷ = Wx + b

This is equivalent to linear regression.

Implications:

  1. Can only learn linearly separable patterns

    • XOR problem: Cannot be solved
    • Complex decision boundaries: Impossible
  2. Limited representational power

    • No feature learning
    • Must rely on hand-crafted features
  3. Universal approximation lost

    • Hidden layers enable approximating any continuous function
    • Without them, limited to hyperplane decision boundaries

Visual example:

With hidden layers:          Without hidden layers:
Can learn this:              Can only learn this:
  ●●●    ○○○                      ●●● | ○○○
 ●●●●●  ○○○○○                    ●●●● | ○○○○
  ●●●    ○○○                      ●●● | ○○○
(arbitrary boundary)          (linear boundary only)

⭐ Q3: What are regularization procedures in deep neural networks?

Answer:

Regularization prevents overfitting by constraining model complexity. Key techniques:

1. Weight Regularization

  • L2 (Weight Decay): Penalize large weights

    L_total = L_data + λΣw²

    Effect: Weights shrink toward zero, smoother functions

  • L1: Encourage sparsity

    L_total = L_data + λΣ|w|

    Effect: Some weights become exactly zero

2. Dropout

  • Randomly zero out neurons during training (typically p=0.5)
  • Prevents co-adaptation, acts as ensemble
  • Apply to hidden layers, not output

3. Batch Normalization

  • Normalizes layer inputs
  • Adds noise through batch statistics
  • Allows higher learning rates

4. Data Augmentation

  • Artificially expand training data
  • Images: rotation, flipping, cropping, color jitter
  • Text: synonym replacement, back-translation
  • Reduces overfitting to specific training examples

5. Early Stopping

  • Monitor validation loss during training
  • Stop when validation loss starts increasing
  • Simple but effective

6. Label Smoothing

  • Replace hard labels [0, 1] with soft labels [0.1, 0.9]
  • Prevents overconfident predictions
  • Improves generalization

7. Architectural Regularization

  • Reduce model capacity (fewer layers/neurons)
  • Skip connections (ResNet)
  • Weight sharing (CNNs, RNNs)

Interview tip: Mention that modern practice often combines multiple techniques—e.g., dropout + weight decay + data augmentation + batch norm.


⭐ Q4: How do you prevent overfitting or underfitting in a deep learning model?

Answer:

Diagnosing the Problem:

SymptomTraining LossValidation LossDiagnosis
High bothHighHighUnderfitting
Low train, high valLowHighOverfitting
Both low, closeLowLowGood fit

Preventing Underfitting (High Bias):

  1. Increase model capacity

    • Add more layers (depth)
    • Add more neurons per layer (width)
    • Use more expressive architecture
  2. Train longer

    • More epochs
    • Check if loss is still decreasing
  3. Reduce regularization

    • Lower dropout rate
    • Reduce weight decay
    • Remove constraints
  4. Better features

    • Feature engineering
    • Use pretrained embeddings
    • Transfer learning
  5. Hyperparameter tuning

    • Learning rate (often too high or too low)
    • Batch size
    • Optimizer choice

Preventing Overfitting (High Variance):

  1. Get more data

    • Best solution when possible
    • Data augmentation as alternative
  2. Regularization

    • Dropout (0.2-0.5)
    • Weight decay (L2)
    • Batch normalization
  3. Reduce model capacity

    • Fewer layers/neurons
    • Simpler architecture
  4. Early stopping

    • Monitor validation loss
    • Stop when it starts increasing
  5. Ensemble methods

    • Train multiple models
    • Average predictions
  6. Cross-validation

    • Better estimate of generalization
    • K-fold for hyperparameter selection

Practical workflow:

1. Start with a model that overfits (proves it can learn)
2. Add regularization until validation improves
3. If underfitting, increase capacity
4. Iterate until train/val losses converge

Key insight for interviews: The goal is to find the sweet spot where the model is complex enough to capture patterns but regularized enough to generalize. Always monitor both training and validation metrics.

Browse the library