GenAI Speedrun
Home Mock Exam
⚡ PART 2 · DEEP LEARNING & LANGUAGE

Neural Networks

From a single perceptron to deep networks — weights, bias and activation, gradient descent, backpropagation, multi-layer perceptrons and recurrent networks.

Syllabus topics 24–29 ⏱ ~19 min read 24 practice questions

The Artificial Neuron

Neural networks are the engine of Deep Learning — ML with networks of many layers. They are loosely inspired by the brain.

Biological neuronWhat it doesArtificial equivalent
DendritesReceive signals from other neuronsInputs (x)
SynapsesControl how strong each signal isWeights (w)
Cell body / SomaAdds up all the signalsSummation (z)
AxonSends out the final decisionOutput (y)
Artificial Neuron — a mathematical unit that takes inputs, multiplies each by a weight, adds a bias, and passes the result through an activation function to produce an output.

The Single-Cell Perceptron

The perceptron (Rosenblatt, 1958) was the first algorithmic model of a neuron. It is a tiny decision-maker that does just three steps.

Step A & B:   z = (w1·x1) + (w2·x2) + … + b
Step C:   if z ≥ 0 → output 1   else → output 0 Multiply inputs by weights, add the bias, then apply an activation to decide.
ComponentRole
Inputs (x)The data features
Weights (w)How important each input is — learned during training
Bias (b)A threshold/offset; lets the activation shift so it need not pass through the origin
Weighted sum (z)z = Σ(w·x) + b — the linear part
Activation functionDecides if the neuron "fires"; adds non-linearity
🍕 Worked example — "Should I order pizza?" Inputs: hunger x₁ = 8, money x₂ = 20. Weights: w₁ = 2 (hunger matters a lot), w₂ = 1, bias b = −15 (general laziness).
z = (2 × 8) + (1 × 20) + (−15) = 16 + 20 − 15 = 21. Since z ≥ 0 → output 1 → order pizza!
💡 Tip — why a bias term? Without a bias, the decision boundary is forced through the origin. The bias lets the activation shift left or right, so the model can fit data that does not pass through (0,0). Examiners love this question — "Why is a bias necessary?".

From hard threshold to probability — the sigmoid activation

A plain step ("if z ≥ 0 → 1") is harsh. Often we want a probability, so we pass z through the sigmoid (introduced earlier):

σ(z) = 1 / (1 + e−z)

This "dimmer switch" squashes any z into (0, 1): big positive z → ≈1, big negative z → ≈0, z = 0 → 0.5.

Python · a perceptron by hand
import numpy as np

def perceptron(inputs, weights, bias):
    z = np.dot(inputs, weights) + bias      # weighted sum
    return 1 if z >= 0 else 0               # step activation

x = [8, 20]          # hunger, money
w = [2, 1]           # weights
b = -15              # bias

print("Decision:", perceptron(x, w, b))     # 1 = order pizza
OutputDecision: 1

The Single-Layer Perceptron & its limits

A single-layer perceptron is one layer of neurons mapping inputs directly to outputs. It is fundamentally a linear classifier — it draws a single straight line (or hyperplane) to separate two classes.

⚠️ The XOR problem — the famous limitation A single perceptron can model the AND and OR logic gates because their outputs are linearly separable (one straight line splits them). But it cannot model XOR (output 1 only when inputs differ) — no single straight line can separate XOR's classes. This observation by Minsky & Papert (1969) triggered the first "AI Winter".
Linear separability — data is linearly separable if a single straight line/plane can perfectly split the classes. A single-layer perceptron only works on linearly separable data.

The fix? Stack neurons into hidden layers — a Multi-Layer Perceptron — which can learn non-linear boundaries and solve XOR.

How a perceptron learns — Gradient Descent

⛰️ The foggy mountain Imagine standing blindfolded on "Mount Error" — height = your total mistake (loss), and you want the valley (zero error). Strategy: feel the slope under your feet (the gradient), take a small step downhill, and repeat. That is Gradient Descent.
Loss function — measures "how wrong is the model?". For regression, the squared error e = (y − ŷ)². Training = minimising the loss.

The update rule

New Weight = Old Weight − (Learning Rate × Gradient) We move opposite to the slope to go downhill. The gradient is ∂Loss/∂weight.
Learning rate — the size of each step. Too large → overshoot the valley, loss bounces or diverges. Too small → painfully slow convergence. If learning rate = 0 → the model never learns at all (no update).
🧩 Worked example — one gradient-descent step Predict sales. Inputs x₁=44.5, x₂=39.3; weights w₁=0.1, w₂=0.2, b=0; actual y=10.4.
Forward pass: prediction = 0.1·44.5 + 0.2·39.3 + 0 = 4.45 + 7.86 = 12.31.
Error: 10.4 − 12.31 = −1.91 (predicted too high).
Update (learning rate 0.0001): gradient term −2(y−ŷ) = 3.82. For w₁: slope = 3.82×44.5 = 170.1, so w₁_new = 0.1 − 0.0001×170.1 = 0.083.
Re-check: new prediction ≈ 10.96 — the error shrank from −1.91 to −0.56. The network is now strictly better.

Variants of Gradient Descent

Backpropagation

Backpropagation — the algorithm that computes how much each weight contributed to the final error, by working backward from the output layer to the input layer using the chain rule of calculus.

The two passes of training

🔑 Backpropagation = "distributing the blame" We know the final error, but which weights caused it? Backpropagation answers that. Using the chain rule, it calculates each weight's share of responsibility (its gradient), layer by layer, from output back to input. Gradient descent then uses those gradients to nudge every weight toward less error.

Training terminology

TermMeaning
EpochOne complete pass through the entire training dataset
Batch sizeNumber of samples processed before the weights update once
IterationOne weight update = Total samples ÷ Batch size (per epoch)
Python · the training loop concept (Keras)
from keras import models, layers
from keras.optimizers import SGD

# A simple single-layer network
model = models.Sequential()
model.add(layers.Dense(1, input_dim=2, activation='sigmoid'))

# loss measures error; SGD does gradient descent + backprop
model.compile(optimizer=SGD(learning_rate=0.01),
              loss='mse', metrics=['mae'])

# epochs = full passes over the data
model.fit(X_train, y_train, epochs=10, batch_size=32)
💡 Tip — the four-step DL workflow Every neural-network program follows: (1) Prepare data → (2) Define architecture (layers) → (3) Compile (choose loss + optimizer) → (4) Train (the fit loop runs forward pass → backprop → weight update for each epoch).

Multi-Layer Perceptron (MLP)

Earlier we saw that a single perceptron is a linear classifier — it cannot solve XOR. The fix is to stack neurons into layers.

Multi-Layer Perceptron (MLP) — a neural network with an input layer, one or more hidden layers, and an output layer. The hidden layers let it learn non-linear decision boundaries.

The three kinds of layers

🍕 The Pizza Factory analogy A single ingredient is not a pizza — you need steps. Input layer = raw ingredients (flour, water, tomato). Hidden layer = the chefs: Chef A mixes flour+water → dough; Chef B mixes tomato+spices → sauce. They create useful intermediate features. Output layer = the server combines dough+sauce+cheese → the final pizza. The chefs are "hidden" — you only see the menu and the meal.
🔑 Universal Approximation Theorem A network with just one hidden layer and enough neurons can approximate any continuous function. This is why MLPs are so powerful — and why stacking layers solves XOR and other non-linear problems.

Forward propagation

Data flows input → output. At each neuron: (1) compute the weighted sum Z = WX + B, then (2) apply a non-linear activation A = f(Z).

Activation Functions

🔑 Why activation functions exist An activation function adds non-linearity. Without it, stacking layers would just be a chain of linear operations — the whole network would collapse into one big linear function and could never learn curves. Activation functions are what make deep networks powerful.
FunctionRangeUse / Notes
Sigmoid
σ(z)=1/(1+e⁻ᶻ)
(0, 1)Binary classification output (probability). Con: vanishing gradient.
Tanh
hyperbolic tangent
(−1, 1)Zero-centred (better than sigmoid). Con: still suffers vanishing gradients.
ReLU
max(0, z)
[0, ∞)Industry standard for hidden layers. Fast, fixes vanishing gradient for positive z. Con: "Dead ReLU" (neurons stuck at 0).
Softmax(0, 1), sums to 1Output layer for multi-class classification — turns raw scores (logits) into probabilities that sum to 1.
🧩 Softmax example Raw scores (logits) [2.0, 1.0, 0.1] → Softmax → [0.7, 0.2, 0.1]. The outputs are now probabilities that sum to 1.0, so the network can say "70% class A, 20% class B, 10% class C".
⚠️ The Vanishing Gradient problem Sigmoid and tanh "squash" inputs into a small range. During backpropagation through many layers, gradients get multiplied repeatedly and shrink toward zero — so early layers barely learn. Solution: use ReLU in hidden layers, which keeps a gradient of 1 for positive inputs.
💡 Tip — the standard recipe Hidden layers → ReLU. Output layer for binary classification → Sigmoid. Output layer for multi-class → Softmax. Output layer for regression → no activation (linear). Memorise this — it appears in coding questions constantly.

Loss Functions & Optimizers

Loss functions — the scorecard

Optimizers — how the weights are updated

Python · building an MLP with Keras
from keras import models, layers
from keras.layers import Input

# MLP for classifying 28x28 images (flattened to 784) into 10 classes
model = models.Sequential([
    Input(shape=(784,)),
    layers.Dense(64, activation='relu'),     # hidden layer 1
    layers.Dense(32, activation='relu'),     # hidden layer 2
    layers.Dense(10, activation='softmax')   # output: 10 classes
])

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

model.fit(x_train, y_train, epochs=10,
          validation_data=(x_test, y_test))
OutputEpoch 1/10 accuracy: 0.9215 - val_accuracy: 0.9578 Epoch 5/10 accuracy: 0.9819 - val_accuracy: 0.9708 Epoch 10/10 accuracy: 0.9917 - val_accuracy: 0.9760
💡 Tip — MLP vs simpler models on MNIST On the MNIST handwritten-digit dataset, a Decision Tree reaches ~88% test accuracy, Logistic Regression ~92%, but an MLP reaches ~97%+. Hidden layers and non-linear activations let the MLP capture far richer patterns.

Recurrent Neural Networks (RNN)

⚠️ Why MLPs fail on sequences A standard MLP treats every input independently and has no notion of order. But language and time-series are sequential — "Dog bites man" ≠ "Man bites dog". We need a network with memory.
Recurrent Neural Network (RNN) — a network designed for sequential data. It processes inputs one step at a time and maintains a hidden state that carries information from previous steps — a form of memory.

How an RNN remembers

At each time step t, the RNN combines the current input with the previous hidden state:

ht = tanh( Wh·ht−1 + Wx·xt + b ) ht−1 is the memory of everything seen so far; xt is the new word/value.

This loop means the hidden state at the end is a (nested) function of all earlier inputs — so the network "remembers" context when predicting the next word.

What RNNs are used for

Python · an RNN for sentiment classification
from keras.models import Sequential
from keras.layers import Embedding, SimpleRNN, Dense

model = Sequential()
model.add(Embedding(input_dim=100, output_dim=8))  # word -> vector
model.add(SimpleRNN(16))                           # the sequence reader
model.add(Dense(1, activation='sigmoid'))          # 0 = negative, 1 = positive

model.compile(loss='binary_crossentropy',
              optimizer='adam', metrics=['accuracy'])
model.fit(padded_data, labels, epochs=50)

preds = model.predict(test_pad)   # e.g. "movie was good"
print("Prediction:", preds)
OutputPrediction: [[0.92]] # 0.92 -> Positive sentiment
⚠️ RNN limitation — long-term memory Basic ("vanilla") RNNs suffer from the vanishing gradient problem over long sequences — they forget information from far back. Improved variants LSTM (Long Short-Term Memory) and GRU add gates to remember long-range context. Transformers later replaced RNNs for most NLP tasks.

Beyond MLPs — CNNs & Transformers

Standard dense (MLP) layers ignore structure. Specialised architectures handle structured data better:

ArchitectureDesigned forKey idea
CNN (Convolutional NN)Images / spatial dataFilters that capture spatial patterns (edges, shapes)
RNN / LSTMSequences / time-seriesHidden state carries memory across time steps
TransformerText / sequences (modern)Self-attention — processes the whole sequence at once (see Transformers & LLMs)
💡 Tip — diagnosing training with loss curves Watch validation loss: if training loss keeps falling but validation loss starts rising, the network is overfitting → use early stopping, more data, dropout, or a simpler model.
? Practice Questions

Perceptron arithmetic and the learning process are common exam material.

MCQQ1Components

In a perceptron, what do the weights represent?

  • A The final output
  • B The importance of each input
  • C The number of layers
  • D The learning rate
Answer: B

Each weight scales how strongly its input influences the decision — exactly like synapse strength in a biological neuron. Weights are what the network learns.

MCQQ2XOR

A single-layer perceptron cannot solve the XOR problem because:

  • A XOR has too much data
  • B XOR is not linearly separable — no single straight line splits its classes
  • C XOR needs a bias term
  • D XOR has three inputs
Answer: B

A single-layer perceptron is a linear classifier (one straight line). XOR's classes cannot be separated by any single line, so hidden layers are required.

MCQQ3Bias

Why is a bias term necessary in a neuron?

  • A It speeds up training
  • B It lets the activation shift, so the model can fit data not passing through the origin
  • C It removes the need for weights
  • D It is the model's output
Answer: B

Without a bias the decision boundary is locked through the origin. The bias is an offset that shifts the activation left/right, giving the model the flexibility to fit real data.

MCQQ4Gradient descent

What happens during training if the learning rate is set to 0?

  • A The model trains extremely fast
  • B The model never learns — weights never update
  • C The loss becomes negative
  • D The model overfits instantly
Answer: B

New weight = old weight − (learning rate × gradient). If the learning rate is 0, the step size is 0, so weights never change and no learning occurs.

MCQQ5Backpropagation

Backpropagation uses which mathematical rule to compute gradients?

  • A The Pythagorean theorem
  • B The chain rule of calculus
  • C Bayes' theorem
  • D The quadratic formula
Answer: B

Backpropagation applies the chain rule layer by layer, from the output backward to the input, to find how each weight affects the final loss.

MCQQ6Terminology

One complete pass through the entire training dataset is called:

  • A A batch
  • B An iteration
  • C An epoch
  • D A gradient
Answer: C

An epoch = one full pass over all training data. A batch is a subset processed before one update; an iteration is one update.

MCQQ7Learning rate

A learning rate that is far too large will most likely cause the loss to:

  • A Decrease smoothly and quickly
  • B Oscillate wildly or diverge (overshoot the minimum)
  • C Stay exactly constant
  • D Become a probability
Answer: B

Too-large steps overshoot the valley of the loss landscape, so the loss bounces around or even grows. Too-small steps make training painfully slow.

NumericalQ8Forward pass

A perceptron has inputs x₁=3, x₂=5; weights w₁=0.4, w₂=0.2; bias b=−2. Compute z and the step output (1 if z ≥ 0).

z = 0.2, output = 1

z = (0.4×3) + (0.2×5) + (−2) = 1.2 + 1.0 − 2.0 = 0.2. Since 0.2 ≥ 0, the step activation outputs 1.

NumericalQ9Iterations

A dataset has 5000 samples and the batch size is 100. How many iterations make up one epoch?

Answer: 50

Iterations per epoch = total samples ÷ batch size = 5000 ÷ 100 = 50. The weights are updated 50 times in one epoch.

CodingQ10Perceptron

Write a Python function that implements a perceptron with a step activation, given a list of inputs, weights, and a bias.

Solution
Python
def perceptron(inputs, weights, bias):
    # Step A & B: weighted sum
    z = bias
    for x, w in zip(inputs, weights):
        z += x * w
    # Step C: step activation
    return 1 if z >= 0 else 0

print(perceptron([3, 5], [0.4, 0.2], -2))   # z = 0.2 -> 1
print(perceptron([1, 1], [0.4, 0.2], -2))   # z = -1.4 -> 0
Output1 0
CodingQ11Sigmoid neuron

Modify a neuron to output a probability using the sigmoid activation instead of a hard step. Test with inputs [2, 3], weights [0.5, 0.5], bias 0.

Solution
Python
import numpy as np

def neuron(inputs, weights, bias):
    z = np.dot(inputs, weights) + bias
    return 1 / (1 + np.exp(-z))      # sigmoid activation

prob = neuron([2, 3], [0.5, 0.5], 0)
print("Probability:", round(prob, 4))
print("Class:", 1 if prob >= 0.5 else 0)
OutputProbability: 0.9241 Class: 1

z = 0.5·2 + 0.5·3 + 0 = 2.5; σ(2.5) ≈ 0.924, so the predicted class is 1.

Short AnswerQ12Concept

In one or two sentences, explain the difference between the forward pass and backpropagation.

Model answer

The forward pass sends data from inputs through the network to produce a prediction and compute the loss. Backpropagation then goes backward, using the chain rule to calculate how much each weight contributed to that loss (its gradient), so gradient descent can update the weights to reduce error.

MCQQ13MLP

What allows a Multi-Layer Perceptron to learn non-linear patterns that a single perceptron cannot?

  • A A larger learning rate
  • B Hidden layers combined with non-linear activation functions
  • C More training epochs only
  • D Removing the bias terms
Answer: B

Hidden layers plus non-linear activations let the network bend decision boundaries. Without non-linear activations, stacked layers collapse into one linear function.

MCQQ14Activation

Which activation function is the industry standard for hidden layers?

  • A Sigmoid
  • B Softmax
  • C ReLU
  • D Linear
Answer: C

ReLU = max(0, z) is fast and avoids the vanishing-gradient problem for positive inputs, making it the default for hidden layers.

MCQQ15Activation

For the output layer of a 10-class classification problem, you should use:

  • A ReLU
  • B Sigmoid
  • C Softmax
  • D Tanh
Answer: C

Softmax converts raw scores into probabilities that sum to 1 across all classes — ideal for multi-class output. Sigmoid is for binary output.

MCQQ16Non-linearity

If a deep network used no activation functions (purely linear), what would happen?

  • A It would train faster and be more accurate
  • B All the layers would collapse into a single linear function — unable to learn curves
  • C It would become a Decision Tree
  • D Nothing would change
Answer: B

A composition of linear functions is still linear. Non-linear activations are what let multiple layers represent complex, curved patterns.

MCQQ17RNN

What makes an RNN suitable for sequential data like text?

  • A It has more layers than an MLP
  • B It keeps a hidden state that carries information from previous time steps
  • C It never uses activation functions
  • D It processes all words in random order
Answer: B

The hidden state acts as memory — it passes context from earlier steps forward, so word order and history influence the prediction.

MCQQ18Optimizer

Which optimizer is the common default choice, combining momentum with adaptive learning rates?

  • A SGD
  • B Adam
  • C ReLU
  • D Softmax
Answer: B

Adam (Adaptive Moment Estimation) blends momentum with per-parameter adaptive learning rates and is the practical default. ReLU/Softmax are activations, not optimizers.

MCQQ19Vanishing gradient

The vanishing gradient problem in deep networks using sigmoid is best mitigated by:

  • A Removing all hidden layers
  • B Switching hidden-layer activations to ReLU
  • C Setting the learning rate to 0
  • D Using softmax in every layer
Answer: B

ReLU keeps a gradient of 1 for positive inputs, so gradients do not shrink toward zero through many layers — unlike sigmoid/tanh which squash values.

NumericalQ20ReLU

Apply the ReLU activation to each value: −3, 0, 2.5, −0.1, 7.

Answer: 0, 0, 2.5, 0, 7

ReLU(z) = max(0, z). Negative values and 0 become 0; positive values pass through unchanged: −3→0, 0→0, 2.5→2.5, −0.1→0, 7→7.

CodingQ21Build an MLP

Using Keras, build an MLP for binary classification with input dimension 20, two hidden layers (16 and 8 neurons, ReLU), and a suitable output layer. Compile it.

Solution
Python
from keras import models, layers
from keras.layers import Input

model = models.Sequential([
    Input(shape=(20,)),
    layers.Dense(16, activation='relu'),    # hidden 1
    layers.Dense(8,  activation='relu'),    # hidden 2
    layers.Dense(1,  activation='sigmoid')  # binary output
])

model.compile(optimizer='adam',
              loss='binary_crossentropy',
              metrics=['accuracy'])
model.summary()
OutputModel: "sequential" - Total params: 481 (trainable)

Binary output → 1 neuron + sigmoid + binary_crossentropy loss.

CodingQ22Build an RNN

Build a Keras model with an Embedding layer, a SimpleRNN layer, and a sigmoid output, for binary sentiment classification.

Solution
Python
from keras.models import Sequential
from keras.layers import Embedding, SimpleRNN, Dense

model = Sequential()
model.add(Embedding(input_dim=5000, output_dim=16))  # words -> vectors
model.add(SimpleRNN(32))                             # reads the sequence
model.add(Dense(1, activation='sigmoid'))            # 0/1 sentiment

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

Embedding turns word indices into dense vectors; SimpleRNN processes them in order; the sigmoid output gives a sentiment probability.

Short AnswerQ23Concept

Why is the choice of output-layer activation different for regression, binary classification and multi-class classification?

Model answer

The output activation must match the kind of answer needed. Regression needs any real number, so the output is linear (no activation). Binary classification needs a single probability in (0,1), so sigmoid. Multi-class needs probabilities across many classes that sum to 1, so softmax.

Short AnswerQ24RNN

Why might a basic RNN struggle to remember the start of a very long sentence, and what architectures fix this?

Model answer

Over long sequences, gradients are multiplied many times and shrink toward zero (vanishing gradient), so the RNN effectively "forgets" early information. LSTM and GRU add gating mechanisms to retain long-range context, and Transformers use self-attention to access any position directly.

🎯Key Takeaways Neuron: z = Σ(w·x) + b → activation. Perceptron = linear classifier; cannot solve XOR (not linearly separable). Bias shifts the boundary off the origin. Gradient descent: new w = old w − (learning rate × gradient). Backprop = chain rule, distributes "blame" backward. Epoch = full data pass; iteration = one update. MLP = input + hidden layer(s) + output; hidden layers + non-linear activations enable non-linearity (Universal Approximation Theorem). Activations: ReLU (hidden), Sigmoid (binary out), Softmax (multi-class out), linear (regression out). Loss: MSE (regression), Cross-Entropy (classification). Optimizer default = Adam. RNN keeps a hidden state for sequences; LSTM/GRU fix long-memory.