Please enable JavaScript to use CodeHS

AI Engineer

Making networks train

Depth is useless without good initialization and regularisation. This deep dive covers why activations die, how batch norm helps, and why dropout prevents overfitting.

AI ~15 min Programmer
Vocabulary

Key terms for this tutorial

Here are the words that matter most in this tutorial. Come back here if a term feels fuzzy.

batch
A small group of examples processed together. Batches let us estimate gradients quickly and use hardware efficiently.
gradient
A vector of partial derivatives showing how much each parameter affects the loss.
overfitting
When a model memorizes training data and fails on new data.
ReLU
A common activation function that outputs the input directly if it is positive, and zero otherwise.
weight
A learnable number inside a model that is adjusted during training.
dropout
Randomly turning off neurons during training to prevent the network from memorizing the training set.

Activations

Activations and dead neurons

Sigmoid and tanh squash inputs into a narrow range. In deep networks, repeated squashing drives gradients toward zero: the vanishing-gradient problem. ReLU avoids this for positive inputs, but negative inputs die forever. Leaky ReLU and GELU try to keep gradients alive on both sides.

activations.py
import torch
import torch.nn.functional as F
x = torch.linspace(-3, 3, 7)
print('x:', x)
print('relu:', F.relu(x))
print('gelu:', F.gelu(x).round(decimals=2))
Output
x: tensor([-3., -2., -1.,  0.,  1.,  2.,  3.])
relu: tensor([0., 0., 0., 0., 1., 2., 3.])
gelu: tensor([-0.0400, -0.0800, -0.1600,  0.0000,  0.8400,  1.9200,  2.9900])

Line-by-line: activations.py

Read this slowly. Each line does one small, concrete thing.

  1. import torch — Import the torch library so we can use its built-in tools.
  2. import torch.nn.functional as F — Import the torch library so we can use its built-in tools.
  3. print('x:', x) — Print a result so we can see what the model learned.
  4. print('relu:', F.relu(x)) — Print a result so we can see what the model learned.
  5. print('gelu:', F.gelu(x).round(decimals=2)) — Print a result so we can see what the model learned.

Pop-in: Read the code one block at a time

Industry code imports many libraries. Focus on the sequence: prepare data, define the model, run the training loop, and evaluate. The rest is setup.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Neural Networks — Deep Dive'. Explain the section 'Activations and dead neurons' in plain English. Include simple analogies, vocabulary definitions, and a short example. Also walk through the code example in this section step by step.


Initialization

Weight initialization

If weights are too large, activations explode. If they are too small, signals shrink. Xavier/Glorot initialization scales weights by the fan-in and fan-out of each layer so the variance of activations stays roughly constant across depth.

init.py
import torch
import torch.nn as nn

layer = nn.Linear(100, 100)
nn.init.xavier_uniform_(layer.weight)
print('weight std:', layer.weight.std().item():.4f)
print('expected ~:', (2 / (100 + 100)) ** 0.5:.4f)
Output
weight std: 0.0986
expected ~: 0.1000

Line-by-line: init.py

Read this slowly. Each line does one small, concrete thing.

  1. import torch — Import the torch library so we can use its built-in tools.
  2. import torch.nn as nn — Import the torch library so we can use its built-in tools.
  3. layer = nn.Linear(100, 100) — Add a linear layer that multiplies inputs by a weight matrix and adds a bias.
  4. print('weight std:', layer.weight.std().item():.4f) — Print a result so we can see what the model learned.
  5. print('expected ~:', (2 / (100 + 100)) ** 0.5:.4f) — Print a result so we can see what the model learned.

Pop-in: Read the code one block at a time

Industry code imports many libraries. Focus on the sequence: prepare data, define the model, run the training loop, and evaluate. The rest is setup.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Neural Networks — Deep Dive'. Explain the section 'Weight initialization' in plain English. Include simple analogies, vocabulary definitions, and a short example. Also walk through the code example in this section step by step.


Regularisation

Batch normalisation and dropout

Batch normalisation re-centres and re-scales each layer's inputs. It reduces internal covariate shift, lets you use larger learning rates, and acts as a weak regulariser. Dropout randomly zeroes neurons during training, forcing the network to spread out its representations.

regularisation.py
import torch
import torch.nn as nn

mlp = nn.Sequential(
    nn.Linear(10, 64),
    nn.BatchNorm1d(64),
    nn.ReLU(),
    nn.Dropout(0.3),
    nn.Linear(64, 1)
)
mlp.eval()
out = mlp(torch.randn(4, 10))
print('output shape:', out.shape)
Output
output shape: torch.Size([4, 1])

Line-by-line: regularisation.py

Read this slowly. Each line does one small, concrete thing.

  1. import torch — Import the torch library so we can use its built-in tools.
  2. import torch.nn as nn — Import the torch library so we can use its built-in tools.
  3. nn.Linear(10, 64), — Add a linear layer that multiplies inputs by a weight matrix and adds a bias.
  4. nn.Linear(64, 1) — Add a linear layer that multiplies inputs by a weight matrix and adds a bias.
  5. mlp.eval() — Put the model in evaluation mode, turning off dropout for inference.
  6. out = mlp(torch.randn(4, 10)) — Create a tensor filled with random numbers to use as fake data or initial weights.
  7. print('output shape:', out.shape) — Print a result so we can see what the model learned.

Pop-in: Read the code one block at a time

Industry code imports many libraries. Focus on the sequence: prepare data, define the model, run the training loop, and evaluate. The rest is setup.

?

Why does dropout need different behaviour at evaluation?

During inference, dropout is turned off. Why?

At eval we want deterministic outputs; dropout during training randomly zeroes activations to prevent co-adaptation, but would corrupt predictions if left on.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Neural Networks — Deep Dive'. The practice question 'Why does dropout need different behaviour at evaluation?' asks: During inference, dropout is turned off. Why? The answer is: At eval we want deterministic outputs; dropout during training randomly zeroes activations to prevent co-adaptation, but would corrupt predictions if left on.. Explain the concept behind this in simple terms.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Neural Networks — Deep Dive'. Explain the section 'Batch normalisation and dropout' in plain English. Include simple analogies, vocabulary definitions, and a short example. Also walk through the code example in this section step by step.


Check yourself

Check yourself

?

Why do deep networks need careful initialization?

What happens if weights are too small?

Signals and gradients shrink as they propagate through many layers, making the network untrainable.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Neural Networks — Deep Dive'. The practice question 'Why do deep networks need careful initialization?' asks: What happens if weights are too small? The answer is: Signals and gradients shrink as they propagate through many layers, making the network untrainable.. Explain the concept behind this in simple terms.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Neural Networks — Deep Dive'. Explain the section 'Check yourself' in plain English. Include simple analogies, vocabulary definitions, and a short example.


Quick quiz

Three questions

1. What is the vanishing-gradient problem?

Stuck or curious? Explain this question to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Neural Networks — Deep Dive'. The quiz asks: What is the vanishing-gradient problem? The correct answer is: Gradients shrink through many squashing layers. Explain why that answer is right and why the other choices are wrong, using a simple example.

2. What does batch normalisation do?

Stuck or curious? Explain this question to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Neural Networks — Deep Dive'. The quiz asks: What does batch normalisation do? The correct answer is: Normalises layer inputs to stabilise training. Explain why that answer is right and why the other choices are wrong, using a simple example.

3. Why is dropout used?

Stuck or curious? Explain this question to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Neural Networks — Deep Dive'. The quiz asks: Why is dropout used? The correct answer is: To prevent neurons from relying too heavily on each other. Explain why that answer is right and why the other choices are wrong, using a simple example.

Keep learning

Networks learn numbers; next we go deeper into language modeling.

Part of the CodeHS tutorial library.