Skip to content
JNTUK · B.Tech study libraryFree access · No sign-up
JNTUK · R23 · CSE · Semester 4-1

Deep Learning exam preparation.

Practice questions for every unit in the style of the R23 end exam, a model answer for each, and a one-page revision summary. Built on the official syllabus units.

  • Practice questions in the exam's style
  • Drafted with AI and checked by a second AI pass. Doubtful points were verified against public sources. Report a mistake
Units
5
Questions
60
2-mark
30
10-mark
30
Checked on

Exam guide

Paper pattern

Semester-end theory paper, 70 marks, from the JNTUK B.Tech R23 Regulations, end-examination pattern for theory subjects.

  1. Question 1 · 20 marksTen compulsory short-answer questions of 2 marks each (two from every unit).
  2. Questions 2 to 6 · 50 marksFive either/or questions of 10 marks each, one per unit. You answer one of the two in each.
  • The semester-end examination carries 70 marks; internal assessment carries 30.
  • Mid-semester examinations are separate: a 20-minute objective paper (10 marks) and a 90-minute subjective paper with three either/or questions of 10 marks (condensed to 15 marks).
  • The regulations text does not state the length of the end examination. Use the duration printed on your hall ticket or question paper.

Read the R23 regulations (PDF) ↗

How to split your time

This plan assumes a 3-hour paper. If yours is different, keep the same proportions. Marks per minute stay roughly even across Question 1 and the 10-mark answers.

  1. 10 minRead the paper and choose one option in each either/or question
  2. 30 minQuestion 1: ten short answers (about 3 minutes each)
  3. 130 minQuestions 2 to 6: one 10-mark answer per unit (about 26 minutes each)
  4. 10 minFinal check of numbering, calculations and diagrams

Study tips for Deep Learning

  • Work small numbers by hand: one neuron's weighted sum and activation, a softmax over three scores, a cross-entropy loss, and one gradient-descent weight update with the learning rate written in.
  • For every convolution or pooling layer, write the output-size formula with the stride and padding, then count the parameters of each Dense and Conv2D layer, because shape and parameter questions are quick marks.
  • Learn the main figures by drawing them from memory: a multilayer network, the training loop, a CNN pipeline, an unrolled RNN, a GAN and an autoencoder, labelling what flows along each arrow.
  • Keep a one-page list of the problems and fixes: overfitting and underfitting, vanishing gradients, and the remedies such as regularization, dropout, batch normalization, early stopping and more data.
  • Read the binary and multiclass Keras examples line by line until you can explain each layer, the loss and the output activation, and why each choice fits that problem.
Unit 1

Fundamentals of Deep Learning

Syllabus: Artificial intelligence, machine learning and deep learning; History of machine learning: probabilistic modeling; Early neural networks; Kernel methods; Decision trees, random forests and gradient boosting machines; The four branches of machine learning; Evaluating machine learning models; Overfitting and underfitting

One-page revision summary

  • AI is the effort to automate intellectual tasks; symbolic AI relied on hand-written rules, while machine learning learns the rules from examples and their answers.
  • Deep learning learns successive layers of representations, usually with a neural network, and the number of layers is the depth of the model.
  • A deep network learns in a loop: layers transform inputs with weights, the loss function scores the prediction, and the optimizer adjusts the weights by backpropagation.
  • Probabilistic modeling applies statistics to data; Naive Bayes and logistic regression are its classic examples, and logistic regression is a classification method despite its name.
  • A single-layer perceptron draws only a linear boundary, so it cannot learn XOR; multilayer networks became practical to train once backpropagation spread in the mid-1980s.
  • LeNet, a convolutional network trained with backpropagation at Bell Labs, was an early practical success at reading handwritten digits.
  • An SVM chooses the boundary with the largest margin to the nearest points, the support vectors, and uses a kernel for data that is not linearly separable.
  • Kernel methods are shallow: they scale poorly to very large datasets and need hand-made features for perceptual data such as images.
  • A decision tree is easy to interpret; a random forest combines many independently trained trees, while gradient boosting adds trees in sequence, each correcting the errors left so far.
  • Gradient boosting machines are among the strongest methods for structured data, while deep learning leads on perceptual data such as images, sound and text.
  • The four branches of machine learning are supervised, unsupervised, self-supervised and reinforcement learning.
  • Self-supervised learning creates its targets from the input itself, as in autoencoders or next-word prediction.
  • In reinforcement learning an agent takes actions in an environment and learns to maximise its total reward.
  • The test set is used only once; tuning on validation scores leaks information about the validation set, which is why a separate test set is kept.
  • Shuffle data before splitting, never shuffle when predicting the future from the past, and never let copies of the same sample land in both the training and validation sets.
  • Always compare a model with a common-sense baseline, such as always predicting the most frequent class.
  • Optimization fits the training data and generalization is performance on new data; overfitting begins when the two pull apart.
  • To fight overfitting, get more data first, then reduce the model size, add L1 or L2 weight regularization, add dropout or stop training early.

Learn these by heart

  • Classical programming: rules + data -> answers; machine learning: data + answers -> rules.
  • Bayes' theorem: P(C | x) = P(x | C) P(C) / P(x); Naive Bayes assumes the features are independent given the class.
  • Kernel trick: K(x, y) = φ(x)·φ(y), computed without forming φ; for example K(x, y) = (x·y)² for a degree-2 polynomial kernel.
  • Gini impurity = 1 − Σ pᵢ²; a boosting step is F_new = F_old + η × (a tree fitted to the residuals).
  • K-fold validation trains K models, each on (K − 1)/K of the data, and averages the K validation scores; iterated K-fold with P shuffles trains P × K models.
  • Overfitting: training loss keeps falling while validation loss rises. Underfitting: the training loss itself is still high.
  • L2 penalty = λ Σ w²; L1 penalty = λ Σ |w|.

2-mark questions

1 Define deep learning. What does the word "deep" refer to? 2 marks
Model answer

Deep learning is a subfield of machine learning that learns useful representations of data through many successive layers, usually stacked as a neural network. Each layer turns its input into a representation that is more useful for the task. "Deep" refers to the number of layers in the model, not to any deeper understanding.

2 What is a Naive Bayes classifier? State its key assumption. 2 marks
Model answer

Naive Bayes is a probabilistic classifier that applies Bayes' theorem, P(C | x) = P(x | C) P(C) / P(x), and predicts the class C with the highest posterior probability. Its "naive" assumption is that the input features are independent of one another given the class, so P(x | C) becomes a product of single-feature probabilities.

3 Why was backpropagation important for early neural networks? 2 marks
Model answer

Simple neural networks were studied from the 1950s, but there was no efficient way to train networks with several layers. Backpropagation, popularised in the mid-1980s, uses the chain rule to compute the gradient of the loss with respect to every weight, layer by layer from the output back to the input, so gradient descent can train multilayer networks.

4 What is the kernel trick in kernel methods such as the support vector machine? 2 marks
Model answer

The kernel trick lets an SVM behave as if the data were mapped into a high-dimensional space, where the classes can be separated by a hyperplane, without ever computing that mapping. A kernel function K(x, y) = φ(x)·φ(y) gives the dot product of two points in that space directly from their original coordinates, which keeps the computation cheap.

5 Distinguish a random forest from a gradient boosting machine. 2 marks
Model answer

Both are ensembles of decision trees. A random forest trains many trees independently, each on a bootstrap sample with a random subset of features at each split, and combines them by majority vote or averaging. A gradient boosting machine adds trees one after another, each new tree fitted to the errors (residuals) left by the trees before it.

6 A model reaches 99% accuracy on its training data but only 75% on the validation data. Is it overfitting or underfitting? Why? 2 marks
Model answer

It is overfitting. The gap of 99 − 75 = 24 percentage points shows that the model has learned patterns specific to the training samples that do not hold for new data. An underfitting model would score poorly on both sets, because it has not yet learned the relevant patterns even in the training data.

10-mark questions

1 Explain the relationship between artificial intelligence, machine learning and deep learning with a diagram. How does machine learning differ from classical programming, and how does a deep network learn? 10 marks
Model answer

Artificial intelligence (AI), machine learning (ML) and deep learning (DL) are nested fields: deep learning is a part of machine learning, and machine learning is one approach to AI.

Artificial intelligence, machine learning and deep learningA tree with Artificial intelligence at the top, which includes Symbolic AI (explicit rules) and Machine learning. Machine learning in turn includes Deep learning and Shallow learning (one or two layers).ArtificialintelligenceSymbolic AI:explicit rulesMachine learningDeep learningShallow learning:1-2 layersincludesincludes
Artificial intelligence, machine learning and deep learning

1. Artificial intelligence. AI is the broad effort to automate intellectual tasks that people normally perform. Early AI was symbolic AI: programmers wrote large sets of explicit rules, as in the expert systems of the 1980s. This worked for well-defined logical problems such as chess, but failed on fuzzy problems such as image classification, speech recognition and translation, where nobody can write the rules down.

2. Machine learning. Instead of being given rules, an ML system is trained. It is shown many examples of inputs together with the expected answers, finds statistical structure in them, and produces rules that automate the task. The learned rules are then applied to new data.

Classical programming:
  rules + data   -> answers
Machine learning:
  data + answers -> rules

3. Deep learning. DL is a kind of ML that learns successive layers of increasingly meaningful representations of the input. Most DL models are neural networks with layers stacked one after another; the number of layers is the depth of the model. Methods that learn only one or two layers of representations are called shallow learning (for example SVMs and decision trees).

4. How a deep network learns:

  • Each layer transforms its input using its weights (parameters), which start as random values.
  • The loss function compares the network's prediction with the true target and gives a loss score.
  • The optimizer uses this score as a feedback signal and adjusts the weights a little, using backpropagation, to lower the loss.
  • Repeating this training loop over many examples moves the weights to values that give a low loss.

In a digit classifier, for example, each layer turns the image into a representation that says less about the raw pixels and more about which digit it shows.

In short, every DL method is an ML method and every ML method belongs to AI, but not the reverse: symbolic AI is AI without learning, and shallow learning is ML without many layers.

2 Explain the four branches of machine learning with suitable examples and a diagram. 10 marks
Model answer

Machine learning problems fall into four broad branches, according to the kind of feedback the learning algorithm gets from the data.

The four branches of machine learningMachine learning at the top branches into Supervised, Unsupervised, Self-supervised and Reinforcement learning. Each branch has an example below it: classification and regression; clustering and PCA; autoencoders and next-word prediction; game playing and robotics.Machine learningSupervisedlearningUnsupervisedlearningSelf-supervisedlearningReinforcementlearningClassification,regressionClustering, PCAAutoencoders,next wordGame playing,robotics
The four branches of machine learning

1. Supervised learning. The model learns to map inputs to known targets (labels), usually supplied by people. It is by far the most common branch: most deep learning applications, such as optical character recognition, speech recognition, image classification and language translation, belong here. Typical tasks:

  • binary and multiclass classification, for example spam or not spam, or which of ten digits an image shows
  • regression, predicting a continuous value such as the price of a house
  • sequence generation (writing a caption for a picture), syntax tree prediction, object detection (drawing boxes around objects) and image segmentation (a mask over the pixels of each object)

2. Unsupervised learning. There are no targets. The algorithm finds useful transformations of the input for visualisation, compression or denoising, or to understand the correlations in the data. Dimensionality reduction, for example principal component analysis (PCA), and clustering, for example grouping customers by buying behaviour, are the standard examples. It is often a first step to understand a dataset before solving a supervised problem on it.

3. Self-supervised learning. This is supervised learning without human-made labels: the targets are generated from the input itself, usually by a simple rule. An autoencoder, whose target is its own input, is a classic example. Predicting the next frame of a video from earlier frames, or the next word of a text from the words before it, are others; this is sometimes called temporally supervised learning. The line between self-supervised and unsupervised learning is blurry and depends on whether one looks at the learning mechanism or at the application.

4. Reinforcement learning. An agent observes an environment, takes actions and receives rewards, and learns to choose the actions that maximise its total reward. Examples are a network that looks at a game screen and outputs moves that raise the score, and systems that learned to play Go. Robotics and resource management are other uses.

In conclusion, supervised learning dominates practical deep learning, but the branches are often combined; for example, a model may first be trained self-supervised on unlabelled text and then fine-tuned with labels.

3 Trace the history of machine learning before deep learning: probabilistic modeling, early neural networks and kernel methods. Show the kernel trick on a small example. 10 marks
Model answer

Before deep learning, machine learning passed through several families of methods, each solving some problems and leaving others open.

Stages of machine learning before deep learningA top-to-bottom chain of stages: Probabilistic modeling (Naive Bayes, logreg), Early neural networks (backpropagation, LeNet), Kernel methods (SVM, maximum margin and the kernel trick), then decision trees, random forests and gradient boosting machines, and finally Deep learning.ProbabilisticmodelingNaive Bayes,logregEarly neuralnetworksBackpropagation,LeNetKernelmethods (SVM)Largest margin,kernel trickTrees, forests,boostingDeep learning
Stages of machine learning before deep learning

1. Probabilistic modeling. This is one of the earliest forms of machine learning: it applies the principles of statistics to data.

  • Naive Bayes applies Bayes' theorem, P(C | x) = P(x | C) P(C) / P(x), assuming the features are independent given the class. It is fast and still used for text classification.
  • Logistic regression (logreg) is a classification algorithm despite its name. It computes z = w·x + b and passes it through the sigmoid σ(z) = 1/(1 + e^(−z)) to get a probability. For w = (0.8, −0.4), b = 0.2 and x = (2, 1): z = 1.6 − 0.4 + 0.2 = 1.4 and σ(1.4) = 0.802 > 0.5, so the input goes to class 1.

2. Early neural networks. Simple networks such as the perceptron were studied from the 1950s, but a single-layer perceptron draws only a linear boundary, so it cannot learn XOR. Multilayer networks can, but there was no efficient way to train them until backpropagation, which computes the gradient of the loss for every weight by the chain rule, became widely known in the mid-1980s. The first well-known practical success came from Yann LeCun at Bell Labs around 1989: LeNet, a convolutional network trained with backpropagation, read handwritten ZIP code digits from US mail, and its successors later read bank cheques.

3. Kernel methods. In the 1990s kernel methods, above all the support vector machine (SVM) developed by Vladimir Vapnik and colleagues, displaced neural networks for many tasks. An SVM finds the decision boundary (a hyperplane) with the largest margin to the nearest training points of each class, the support vectors. Classes that are not linearly separable are mapped to a higher-dimensional space, and the kernel trick computes dot products there directly, K(x, y) = φ(x)·φ(y), without computing φ.

Example: the polynomial kernel K(x, y) = (x·y)² with x = (1, 2) and y = (3, 1).

x·y = 1×3 + 2×1 = 5
K(x, y) = 5² = 25
φ(v) = (v1², √2·v1·v2, v2²)
φ(x) = (1, 2√2, 4)
φ(y) = (9, 3√2, 1)
φ(x)·φ(y) = 9 + 12 + 4 = 25

The kernel gives the same 25 while working only with the two original coordinates; for higher degrees and more features the saving grows quickly. SVMs, however, scale poorly to very large datasets and, being shallow, need hand-made features for perceptual data such as images.

These methods were later joined by decision trees, random forests and gradient boosting machines, and from about 2012 deep learning overtook all of them on perceptual tasks.

4 Explain decision trees, random forests and gradient boosting machines. Show one boosting step on a small regression example. 10 marks
Model answer

Decision trees and the ensembles built from them are among the strongest shallow methods for structured (tabular) data.

1. Decision trees. A decision tree is a flowchart-like structure: each internal node asks a question about one feature (for example "income > 50,000?"), each branch is an answer, and each leaf gives a class or a value. The tree is learned from data by choosing, at every node, the split that makes the child nodes purest, for example the largest fall in Gini impurity, 1 − Σ pᵢ². A node with 6 positive and 4 negative samples has Gini 1 − (0.6² + 0.4²) = 0.48. Splitting it into (5+, 1−) and (1+, 3−) gives 0.278 and 0.375, a weighted 0.6 × 0.278 + 0.4 × 0.375 = 0.317, so the impurity falls by 0.163. Trees are easy to visualise and interpret, but one deep tree overfits easily.

2. Random forests. Leo Breiman's random forest trains many decision trees, each on a bootstrap sample of the training data (drawn with replacement) and with a random subset of features tried at each split. The trees differ, so their errors partly cancel: for classification the forest takes a majority vote, for regression the average. If five trees vote spam, not spam, spam, spam, not spam, the forest outputs spam, 3 votes to 2. Forests are robust and need little tuning.

Random forest and gradient boostingIn the random forest, the training data feeds three trees, each on its own bootstrap sample, and their outputs meet in a majority vote or average. In gradient boosting, F0 = mean of targets passes its residuals to tree 1, which passes the new residuals to tree 2.Random forest: in parallelBoosting: trees in sequenceTraining dataTree 1 (bootstrapsample)Tree 2 (bootstrapsample)Tree 3 (bootstrapsample)Majority voteor averageF0 = meanof targetsTree 1 fitsresidualsTree 2 fitsnew residualsresidualsnew residuals
Random forest and gradient boosting

3. Gradient boosting machines. A GBM also combines trees, but builds them in sequence. Each new tree fits the errors of the current ensemble: for the squared-error loss ½(y − F)², the negative gradient is exactly the residual y − F. The new tree's output is added with a learning rate η.

Example: targets y = 3, 5 and 10, learning rate η = 0.5. Tree 1 has one split, samples 1 and 2 in one leaf and sample 3 in the other, and each leaf predicts the mean residual of its samples.

F0 = mean of targets = 6
residuals y − F0:     −3, −1, 4
tree 1 leaf values:   −2, −2, 4
F1 = F0 + 0.5 × tree 1
F1:                    5,  5, 8
new residuals:        −2,  0, 2
MSE: 26/3 = 8.67 -> 8/3 = 2.67

A second tree fitted the same way gives predictions 4.5, 4.5 and 9 and an MSE of 1.17, so each step lowers the training error. The number of trees and η must be tuned on validation data, because too many trees overfit. Libraries such as XGBoost and LightGBM make GBMs a top choice for structured data.

In short, a forest averages independent trees built in parallel, while boosting adds dependent trees in sequence, each correcting the errors that remain.

5 How are machine learning models evaluated? Explain training, validation and test sets, hold-out validation, K-fold and iterated K-fold validation with a worked example, and the points to keep in mind. 10 marks
Model answer

The aim of machine learning is a model that generalises, that is, performs well on data it has never seen. So a model is never judged on its own training data; the data is split into three sets.

1. Training, validation and test sets.

  • Training set: used to fit the weights.
  • Validation set: used to compare models and tune hyperparameters, such as the number of layers or units.
  • Test set: used once, at the very end, to estimate performance on new data.

A separate test set is needed because each round of tuning on validation scores leaks a little information about the validation set into the model, so the validation score becomes optimistic.

2. Simple hold-out validation. Set aside a fraction of the data for validation, train on the rest and score on the held-out part. With little data, though, the validation set is small and the score depends heavily on which samples fall in it.

3. K-fold validation. Split the data into K equal parts. For each part i, train a fresh model on the other K − 1 parts and evaluate it on part i. The final score is the average of the K scores.

4. Iterated K-fold validation with shuffling. Repeat K-fold P times, shuffling the data before each split, and average all P × K scores. It is the most reliable of the three when data is scarce, but the most costly.

Worked example: 1,000 labelled samples. Keep 250 aside as the test set and run 3-fold validation on the other 750, in parts of 250 (positions after shuffling).

Model  Validate  Train on       Score
1      1-250     251-750        0.84
2      251-500   1-250,501-750  0.88
3      501-750   1-500          0.86
Mean = (0.84+0.88+0.86)/3 = 0.86
Hold-out test set with 3-fold validation1,000 labelled samples split into 750 for 3-fold validation and 250 test samples set aside. Models 1, 2 and 3 validate on samples 1-250, 251-500 and 501-750; the mean of the 3 scores chooses the settings for a final model trained on all 750, which is evaluated once on the test samples.1,000 labelledsamples750 for 3-foldvalidation250 test samples,set asideModel 1:validate 1-250Model 2:validate 251-500Model 3:validate 501-750Mean of 3 scoresFinal model:train on 750choosesettingsevaluate once
Hold-out test set with 3-fold validation

With P = 4 shuffled repeats, 4 × 3 = 12 models are trained. After choosing the hyperparameters, train the final model on all 750 samples and evaluate it once on the 250 test samples.

5. Points to keep in mind:

  • Data representativeness: shuffle before splitting. If a dataset is sorted by class and its last 20% is held out, that part may hold classes the model never saw in training.
  • The arrow of time: when predicting the future from the past, do not shuffle; the test data must come after the training data in time.
  • Redundancy: if some samples appear twice, make sure no copy lands in both the training and the validation set.
  • Compare with a common-sense baseline, such as always predicting the most frequent class, to see whether the model is useful.

A sound protocol makes the reported score an honest estimate of how the model will do on new data.

6 What are overfitting and underfitting? How are they recognised from the training and validation loss, and how can overfitting be reduced? Illustrate with a numerical example. 10 marks
Model answer

The central tension in machine learning is between optimization, adjusting a model to do as well as possible on the training data, and generalization, doing well on data it has never seen. Only optimization can be controlled directly, so generalization is watched on validation data.

1. Underfitting. Early in training the training and validation losses fall together: the model has not yet learned all the relevant patterns, so it underfits. A model that is too small also underfits, and then the training loss itself stays high. Remedies: train longer, or use a bigger model with more capacity (more layers or units).

2. Overfitting. After some epochs the validation loss stops falling and starts to rise while the training loss keeps falling. The model is now learning patterns specific to the training samples, including noise, that do not hold for new data: it overfits.

Example (loss after each epoch):

Epoch  Train loss  Val loss
1      0.62        0.64
2      0.45        0.48
3      0.36        0.41
4      0.29        0.39  <- lowest
5      0.23        0.40
6      0.18        0.44
7      0.14        0.49
8      0.11        0.55

In epochs 1 to 3 both losses fall: the model is still underfitting. The validation loss is lowest at epoch 4 (0.39). From epoch 5 the training loss keeps falling but the validation loss rises, and the gap grows from 0.10 at epoch 4 to 0.44 at epoch 8: the model is overfitting. Early stopping would keep the weights from epoch 4.

Telling underfitting from overfittingTrain and watch both losses. If the training loss is still high, the model is underfitting: train longer or use a bigger model. If not, and the validation loss is rising, it is overfitting: use more data, L2 or dropout; otherwise it is a good fit.Train; watchboth lossesTraining lossstill high?UnderfittingValidationloss rising?Train longer,bigger modelOverfittingGood fit:keep the modelMore data,L2, dropoutyesnoyesno
Telling underfitting from overfitting

3. Ways to reduce overfitting:

  • Get more training data: the best remedy, because a model trained on more data generalises better.
  • Reduce the network's size (capacity): fewer layers or units leave less room to memorise.
  • Weight regularization: add a cost for large weights to the loss. L2 adds λ Σ w² and L1 adds λ Σ |w|. For weights (0.5, −1.0, 2.0) and λ = 0.01, L2 adds 0.01 × (0.25 + 1 + 4) = 0.0525, so a data loss of 0.30 becomes 0.3525; L1 would add 0.01 × 3.5 = 0.035.
  • Dropout: during training, randomly set a fraction (for example 0.5) of a layer's outputs to zero, so the network cannot rely on chance patterns.
  • Early stopping, and data augmentation for images.

In Keras, L2 regularization and dropout are added like this:

import keras
from keras import layers, regularizers

model = keras.Sequential([
  layers.Dense(16, activation="relu",
    kernel_regularizer=
      regularizers.l2(0.01)),
  layers.Dropout(0.5),
  layers.Dense(1, activation="sigmoid"),
])

A good fit lies on the border between underfitting and overfitting: first build a model large enough to overfit, then regularize and tune it while watching the validation loss.

Unit 2

Introducing Deep Learning

Syllabus: Biological and machine vision; Human and machine language; Artificial neural networks; Training deep networks; Improving deep networks

One-page revision summary

  • Machine vision gives computers the ability to recognise what images show, and its layered design was inspired by the hierarchy of the biological visual cortex.
  • Traditional machine vision relied on hand-engineered features and a shallow classifier, whereas deep learning learns its features directly from raw pixels.
  • AlexNet, a deep convolutional network trained on GPUs, won the ImageNet challenge by a wide margin and made deep learning the standard approach to machine vision.
  • Natural language has four main elements: phonology (sounds), morphology (word structure), syntax (sentence structure) and semantics (meaning).
  • One-hot vectors are long, sparse and treat every pair of words as equally different, while word vectors are short, dense and place similar words close together.
  • Word2vec learns word vectors by skip-gram or CBOW, and vector arithmetic such as king − man + woman ≈ queen shows that directions in the space carry meaning.
  • Deep learning NLP now powers machine translation, sentiment analysis, speech recognition and chatbots.
  • An artificial neuron computes a weighted sum of its inputs plus a bias and passes it through an activation function.
  • ReLU is the usual hidden-layer activation; sigmoid suits a binary output, softmax a multiclass output and a linear output neuron suits regression.
  • Training repeats forward pass, cost, backpropagation and weight update over mini-batches for several epochs.
  • Cross-entropy cost avoids the learning slowdown that quadratic cost causes in a saturated sigmoid output neuron.
  • The learning rate must be tuned: too small trains slowly, while too large overshoots the minimum or diverges.
  • The number of hidden layers and neurons is a hyperparameter, chosen by comparing results on validation data.
  • Vanishing and exploding gradients arise because backpropagation multiplies one factor per layer; Glorot or He initialization, ReLU and batch normalization keep them stable.
  • Momentum adds a fraction of the previous update to the current one, which speeds progress in a steady direction and damps oscillation.
  • AdaGrad, RMSProp and Adam give each weight its own adaptive learning rate based on the history of its squared gradients.
  • Overfitting is reduced by L1 or L2 regularization, dropout, data augmentation and early stopping.
  • TensorBoard plots training and validation loss across epochs, which helps spot overfitting and compare training runs.

Learn these by heart

  • Neuron: z = Σ wi·xi + b, a = f(z); sigmoid σ(z) = 1/(1 + e^(−z)), ReLU = max(0, z), softmax pk = e^(zk) / Σ e^(zj).
  • Dense layer parameters = n_in × n_out + n_out (784 inputs to 64 neurons gives 50,240).
  • Gradient descent: w ← w − η ∂C/∂w; iterations per epoch = ⌈N / batch size⌉.
  • Cross-entropy C = −[y ln a + (1 − y) ln(1 − a)]; with a sigmoid output, ∂C/∂z = a − y.
  • Sigmoid slope σ′(z) ≤ 0.25; Glorot uniform limit √(6/(n_in + n_out)); He standard deviation √(2/n_in).
  • Batch normalization: x̂ = (x − μ)/√(σ² + ε), then y = γx̂ + β with γ and β learned.
  • L2: C = C0 + λΣw²; L1: C = C0 + λΣ|w|; dropout scales kept outputs by 1/(1 − p) during training.

2-mark questions

1 What did Hubel and Wiesel discover about simple and complex cells in the visual cortex? 2 marks
Model answer

Recording from single neurons in the primary visual cortex of cats, Hubel and Wiesel found simple cells, which fire for an edge at one orientation in a small part of the visual field, and complex cells, which respond to such an edge anywhere in a wider area. Vision builds up from edges to shapes, an idea behind convolutional networks.

2 Distinguish a one-hot (localist) word representation from a word vector (distributed representation). 2 marks
Model answer

A one-hot vector is as long as the vocabulary, with a single 1 at the word's index; it is sparse, and two different words always have cosine similarity 0, so no meaning is captured. A word vector is short and dense, learned from text (for example by word2vec), so words used in similar contexts get nearby vectors.

3 A Dense layer of 64 neurons receives 784 inputs. How many trainable parameters does it have? 2 marks
Model answer

Each neuron has one weight per input and one bias.

Parameters = inputs × neurons + neurons = 784 × 64 + 64 = 50,176 + 64 = 50,240 trainable parameters.

4 A training set has 60,000 examples and the batch size is 128. How many iterations (weight updates) make up one epoch? 2 marks
Model answer

An epoch is one full pass over the training data, and each mini-batch gives one iteration.

Iterations = ⌈60,000 / 128⌉ = ⌈468.75⌉ = 469: there are 468 full batches of 128 examples and one last batch of 96 examples.

5 How does the Adam optimizer improve on plain stochastic gradient descent? 2 marks
Model answer

Plain SGD uses one fixed learning rate for every weight. Adam keeps, per weight, moving averages of the gradient (momentum) and of the squared gradient (as in RMSProp), corrects their start-up bias and divides each step by the root of the second average, so every weight gets an adaptive step. Defaults: η = 0.001, β1 = 0.9, β2 = 0.999.

6 What is a saturated neuron, and why does it slow down learning? 2 marks
Model answer

A sigmoid or tanh neuron is saturated when its input z is large in size, so its output sits near a limit and its slope is almost zero: σ′(5) = σ(5)(1 − σ(5)) ≈ 0.0066, against 0.25 at z = 0. Gradients through it are tiny, so its weights barely change. Cross-entropy cost and ReLU hidden units ease this.

10-mark questions

1 Explain how the study of biological vision shaped machine vision. Describe the hierarchy of the visual cortex, the move from feature engineering to deep learning, and the part played by ImageNet and AlexNet. 10 marks
Model answer

Machine vision, the ability of a computer to recognise what an image shows, was shaped by what neuroscientists learned about how animals see. Deep learning took from this work both its layered design and its central idea: features should be learned, not designed by hand.

1. Biological vision. Light falling on the retina becomes nerve signals that pass through the thalamus to the primary visual cortex (V1) at the back of the brain. Hubel and Wiesel, recording from single neurons in cats, found simple cells that fire for an edge at one orientation in a small part of the visual field, and complex cells that respond to such an edge anywhere in a wider area. Higher visual areas combine these into corners, shapes and finally whole objects.

2. The same hierarchy in machines. A deep network takes raw pixels. Its first layer learns edge detectors, doing a similar job to simple cells; middle layers combine edges into curves and shapes, and deep layers respond to object parts and whole objects.

Biological and machine vision both build objects from edgesTwo columns: biological vision runs from the retina via the thalamus to simple cells (edges), complex cells and higher areas (objects); machine vision runs from pixels to layer 1 (edges), middle layers (shapes) and deep layers (objects). Simple cells and layer 1 are linked as doing a similar job.Biological visionMachine visionRetinaSimplecells: edgesComplex cellsHigher areas:objectsPixelsLayer 1: edgesMiddlelayers: shapesDeep layers:objectsvia thalamussimilar job
Biological and machine vision both build objects from edges

3. Early networks. Fukushima's neocognitron stacked alternating layers modelled on simple and complex cells. LeNet-5, a convolutional network trained by backpropagation, recognised handwritten digits reliably enough to be used for reading bank cheques.

4. The feature-engineering era. For a long time the usual approach was traditional machine learning: experts hand-designed features, such as edge histograms or the Haar-like features of the Viola–Jones face detector, and a shallow classifier such as a support vector machine learned from them. Good features took years of expert effort and rarely transferred to a new task.

5. ImageNet and AlexNet. ImageNet is a very large labelled image database (more than 14 million images), and its yearly challenge (ILSVRC) asked models to sort images into 1,000 categories. AlexNet, a deep convolutional network by Krizhevsky, Sutskever and Hinton, trained on GPUs with ReLU activations and dropout, won the challenge by a wide margin over feature-engineered entries. After that, deep learning became the standard approach to machine vision.

In short, biological vision gave machine vision its edge-to-object hierarchy, and large labelled datasets, GPUs and deep networks finally let machines learn those features for themselves.

2 Describe the elements of natural human language and explain how deep learning represents words for a machine. Compare one-hot encoding with word vectors using a small numerical example. 10 marks
Model answer

Natural language processing (NLP) lets machines read, understand and produce human language. Like vision, it moved from features designed by experts to representations learned by deep networks.

1. Elements of natural human language.

  • Phonology: the sounds of a language and how they combine.
  • Morphology: how words are built from smaller units of meaning (morphemes), as in un + break + able.
  • Syntax: how words are ordered into phrases and sentences.
  • Semantics: the meaning of words and sentences.

A deep network learns patterns at these levels from examples instead of being given hand-written rules.

2. Traditional and deep learning NLP. Traditional NLP turned raw text into hand-engineered features, such as word counts, stems and part-of-speech tags, for a shallow model. Deep learning NLP turns raw text into learned word vectors and lets a deep network find useful features itself. Both end in an output such as a sentiment label or a translation; the deep learning route now leads in translation, sentiment analysis, speech recognition and chatbots.

Traditional NLP and deep learning NLPRaw text feeds two routes to the same output: the traditional route uses hand-engineered features and a shallow model, and the deep learning route uses learned word vectors and a deep network.Traditional NLPDeep learning NLPRaw textHand-engineeredfeaturesShallow modelWord vectorsDeep networkOutput: e.g.sentimentexperts designlearned
Traditional NLP and deep learning NLP

3. One-hot (localist) representation. Each word is a vector as long as the vocabulary, with a single 1 at the word's index: cat = [1, 0, 0, ...], dog = [0, 1, 0, ...]. The vectors are huge and sparse, and the cosine similarity of any two different words is 0, so cat is no closer to dog than to car.

4. Word vectors (distributed representation). Each word is a short dense vector, usually tens to a few hundred dimensions, learned from large amounts of text so that words used in similar contexts lie close together. Word2vec learns them by skip-gram (predict the context words from a word) or CBOW (predict a word from its context). Toy 3-dimensional vectors:

word   vector
cat    [0.8, 0.6, 0.1]
dog    [0.7, 0.7, 0.2]
car    [0.1, 0.2, 0.9]

cos(cat, dog) = 1.00 / (1.0050 × 1.0100) = 0.985

cos(cat, car) = 0.29 / (1.0050 × 0.9274) = 0.311

So cat sits much nearer dog than car, which one-hot vectors cannot show. Directions in the space also carry meaning: in trained vectors, king − man + woman lands close to queen.

In short, word vectors turn words into points in a meaningful space, and that is what lets deep networks work with human language.

3 Explain the artificial neuron, the layers of an artificial neural network and the common activation functions. Then compute the forward pass of a 2-2-3 network for x = (1, 2): ReLU hidden neurons with weights (0.5, 0.25) and (−1, 0.25) and zero biases; softmax output neurons with weights (1.5, 0.4), (1.0, −0.3) and (−0.5, 0.2) and biases 0.5, 0 and 0.5. 10 marks
Model answer

An artificial neural network (ANN) is a stack of layers of simple units, artificial neurons, loosely modelled on the neurons of the brain. Each layer transforms its input and passes the result to the next layer.

1. The artificial neuron. It multiplies each input by a weight, adds a bias and applies an activation function f: z = Σ wi·xi + b and a = f(z). Training adjusts the weights and biases.

2. Layers.

  • Input layer: holds the features (for example 784 pixel values) and does no computation.
  • Dense (fully connected) hidden layers: every neuron receives every output of the layer before. A layer with n_in inputs and n_out neurons has n_in × n_out + n_out parameters.
  • Output layer: one sigmoid neuron for a yes/no task, one softmax neuron per class for several classes, or a linear neuron for regression.

3. Activation functions.

  • Sigmoid: σ(z) = 1/(1 + e^(−z)), output between 0 and 1.
  • tanh: output between −1 and 1, centred on zero.
  • ReLU: max(0, z); cheap and does not saturate for z > 0, so it is the usual hidden-layer choice.
  • Softmax: pk = e^(zk) / Σ e^(zj), turns the output scores into class probabilities that sum to 1.

Without a non-linear activation, any stack of layers would collapse into a single linear map.

Forward pass through a 2-2-3 networkThe input layer with 2 features, x = (1, 2), feeds a Dense 2 ReLU hidden layer giving h = (1, 0), which feeds a Dense 3 softmax output layer giving class probabilities 0.665, 0.245 and 0.090.Input layer:2 featuresDense 2,relu (hidden)Dense 3,softmax (output)Classprobabilitiesx = (1, 2)h = (1, 0)0.665,0.245, 0.090
Forward pass through a 2-2-3 network

4. Worked forward pass for x = (1, 2):

Hidden, ReLU             z      a
h1: 0.5(1) + 0.25(2)     1.0    1.0
h2: -1(1) + 0.25(2)     -0.5    0.0

Output       z = w·h + b
o1: 1.5(1) + 0.4(0) + 0.5    = 2.0
o2: 1.0(1) - 0.3(0) + 0      = 1.0
o3: -0.5(1) + 0.2(0) + 0.5   = 0.0

Softmax: e^2 = 7.389, e^1 = 2.718, e^0 = 1, sum = 11.107.

p1 = 7.389 / 11.107 = 0.665, p2 = 2.718 / 11.107 = 0.245, p3 = 1 / 11.107 = 0.090.

The network predicts class 1 with probability 0.665. Neuron h2 gives 0 because ReLU switches off a negative input. The network has (2 × 2 + 2) + (2 × 3 + 3) = 6 + 9 = 15 parameters.

In short, an ANN is layers of weighted sums and activations, and the forward pass simply applies them in order from input to output.

4 Explain how a deep network is trained: the cost function, gradient descent, the learning rate, mini-batches and backpropagation. A sigmoid neuron with w = 0.8 and b = −0.2 receives x = 1.5 with target y = 1; perform one gradient-descent update using cross-entropy cost and learning rate 0.5. 10 marks
Model answer

Training a deep network means finding the weights and biases that make its outputs match the labels. It repeats one loop many times: forward pass, cost, backpropagation and weight update.

1. Cost function. The cost C measures how wrong the outputs are. Quadratic cost, C = (y − a)²/2 per example (averaged, this is mean squared error up to the ½), suits regression. For classification, cross-entropy C = −[y ln a + (1 − y) ln(1 − a)] is preferred: with a sigmoid output, ∂C/∂z = a − y, so a badly wrong neuron still learns fast, while quadratic cost multiplies this by σ′(z), which is near 0 for a saturated neuron.

2. Gradient descent. Each parameter moves against its gradient: w ← w − η ∂C/∂w. The learning rate η sets the step size: too small and training crawls, too large and the steps overshoot the minimum or diverge.

3. Mini-batches and SGD. Computing the gradient on all the data for every step is slow, so stochastic gradient descent uses small random mini-batches (for example 32 or 128 examples). One mini-batch gives one update, then the next mini-batch is used, and one pass over all the data is an epoch. The noise of mini-batches also helps the weights escape poor local minima.

4. Backpropagation. The chain rule carries the error from the output layer back through every layer, giving ∂C/∂w for all weights in one backward pass.

The training loop of a deep networkA mini-batch of data goes through the forward pass, the cross-entropy cost is computed, backpropagation finds the gradients, and the weights and biases are updated with learning rate η before the next mini-batch.Mini-batchof dataForward passCost: cross-entropyBackpropagationUpdate w,b with ηoutputs aCgradientsnextmini-batch
The training loop of a deep network

5. Worked example: x = 1.5, w = 0.8, b = −0.2, y = 1, η = 0.5.

z = 0.8(1.5) - 0.2       = 1.0
a = σ(1.0)               = 0.7311
C = -ln(0.7311)          = 0.3133
∂C/∂z = a - y            = -0.2689
∂C/∂w = (a - y)x         = -0.4034
∂C/∂b = a - y            = -0.2689
w = 0.8 - 0.5(-0.4034)   = 1.0017
b = -0.2 - 0.5(-0.2689)  = -0.0655

After the update, z = 1.0017(1.5) − 0.0655 = 1.4370, a = 0.8080 and C = 0.2132, so the cost fell from 0.3133. With quadratic cost, ∂C/∂z would be −0.2689 × σ′(1) = −0.2689 × 0.1966 = −0.0529, about five times smaller, so learning would be slower.

6. Tuning. The number of hidden layers and neurons, the learning rate and the batch size are hyperparameters, chosen by comparing results on validation data.

In short, the cost says how wrong the network is, backpropagation says which way to move each weight, and gradient descent moves it.

5 Why do deep networks suffer from vanishing and exploding gradients? Explain, with numerical illustrations, how weight initialization and batch normalization reduce these problems. 10 marks
Model answer

Adding layers lets a network learn richer features, but it also makes the gradients that reach the early layers unstable. Improving a deep network starts with keeping these gradients in a healthy range.

1. Why gradients become unstable. By the chain rule, the gradient reaching an early layer is a product with one factor per later layer: a weight times the slope of that layer's activation. The sigmoid slope σ′(z) = σ(z)(1 − σ(z)) is at most 0.25. With weights near 1, passing back through hidden layers 3, 2 and 1 (layer 3 is nearest the output) leaves at most 0.25, 0.0625 and 0.015625 of the output gradient; after ten layers it is at most 0.25^10 ≈ 9.5 × 10^(−7). The early layers hardly learn: the vanishing gradient problem. If each factor is above 1, say 1.5, ten layers give 1.5^10 ≈ 57.7: the gradient explodes and the weights jump wildly.

How the gradient shrinks going back through sigmoid layersThe output gradient of 1 passes back through hidden layer 3, hidden layer 2 and hidden layer 1; each step multiplies it by σ′(z) of at most 0.25, leaving at most 0.25, 0.0625 and 0.015625.Outputgradient: 1Hidden layer3: ≤ 0.25Hidden layer2: ≤ 0.0625Hidden layer1: ≤ 0.015625× σ′(z) ≤ 0.25× σ′(z) ≤ 0.25× σ′(z) ≤ 0.25
How the gradient shrinks going back through sigmoid layers

2. Weight initialization. Weights that start too large saturate neurons or blow signals up; weights that start too small shrink signals layer by layer. Good schemes scale the random weights to the layer size so that the signal's variance stays about the same:

  • Glorot (Xavier) uniform: weights from U(−L, L) with L = √(6/(n_in + n_out)). For a 784 → 64 layer, L = √(6/848) = 0.0841. It is the default for a Keras Dense layer.
  • He initialization, for ReLU layers: standard deviation √(2/n_in); for 784 inputs, √(2/784) = 0.0505.

Biases start at 0. ReLU hidden layers, whose slope is 1 for z > 0, also help.

3. Batch normalization. A batch-normalization layer standardizes each feature over the current mini-batch and then rescales it with two learned parameters: x̂ = (x − μ)/√(σ² + ε) and y = γx̂ + β. Example: the values 2, 4, 6, 8 give μ = 5, σ² = 5 and σ = 2.236, so x̂ = −1.342, −0.447, 0.447, 1.342 (ε ignored). At the start γ = 1 and β = 0, and training adjusts them. The next layer then receives centred, evenly scaled inputs, so gradients flow evenly, higher learning rates work and training is faster and less sensitive to initialization. At test time, running averages of μ and σ² are used.

4. Gradient clipping, which caps the size of the gradient before each update, further limits exploding gradients.

In short, careful initialization, ReLU, batch normalization and clipping keep gradients stable so that deep networks can train.

6 What is overfitting in a deep network? Explain how L1 and L2 regularization, dropout and data augmentation improve generalization, and write a Keras model that uses L2 regularization and dropout. 10 marks
Model answer

A network overfits when it learns the training data, noise included, so closely that it does worse on new data: training accuracy keeps rising while validation accuracy stalls or falls. Methods that close this gap improve generalization.

1. L2 and L1 regularization. A penalty on large weights is added to the cost C0:

  • L2: C = C0 + λ Σ w². Its gradient adds 2λw, so every update shrinks each weight a little (weight decay) and the model becomes smoother.
  • L1: C = C0 + λ Σ |w|, which pushes many weights to exactly 0 and gives a sparse model.

Example, weights (0.5, −1.0, 2.0) with λ = 0.01: L2 penalty = 0.01 × (0.25 + 1 + 4) = 0.0525; L1 penalty = 0.01 × (0.5 + 1 + 2) = 0.035. λ is a hyperparameter: too large and the model underfits.

2. Dropout. During training, each neuron of a layer is switched off at random with probability p (often 0.2 to 0.5) afresh for every training example at every step. The network cannot rely on any single neuron, and in effect it trains many thinner networks that share weights. Keras scales the kept outputs by 1/(1 − p) during training (with p = 0.5, a kept output of 0.8 becomes 1.6), so at test time every neuron is used unchanged.

3. Data augmentation. New training examples are made from existing ones by changes that keep the label: for photos, small rotations, shifts, zooms and horizontal flips. The network sees more variety and learns features that do not depend on exact position.

4. Early stopping, which ends training when the validation loss stops improving, is a further simple guard.

A Keras model with L2 regularization and dropoutInput of shape 784 feeds Dense 64 relu with L2, then Dropout 0.5, Dense 64 relu, Dropout 0.5 and finally Dense 10 softmax.Input (784,)Dense 64,relu, L2Dropout 0.5Dense 64, reluDropout 0.5Dense 10,softmax
A Keras model with L2 regularization and dropout
import keras
from keras import layers, regularizers

reg = regularizers.l2(0.001)
model = keras.Sequential([
    keras.Input(shape=(784,)),
    layers.Dense(64, activation="relu",
                 kernel_regularizer=reg),
    layers.Dropout(0.5),
    layers.Dense(64, activation="relu"),
    layers.Dropout(0.5),
    layers.Dense(10,
                 activation="softmax"),
])

Parameters: 784 × 64 + 64 = 50,240; 64 × 64 + 64 = 4,160; 64 × 10 + 10 = 650; total 55,050. Dropout layers have no parameters.

In short, regularization keeps weights small, dropout stops neurons depending on each other, and augmentation enlarges the data, so the network generalizes better.

Unit 3

Neural Networks

Syllabus: Anatomy of a neural network; Introduction to Keras: Keras, TensorFlow, Theano and CNTK; Setting up a deep learning workstation; Classifying movie reviews: binary classification; Classifying newswires: multiclass classification

One-page revision summary

  • A neural network is built from layers combined into a model, trained on input data and targets, with a loss function as feedback and an optimizer that updates the weights.
  • Dense layers suit vector data, recurrent layers such as LSTM suit sequence data, and Conv2D layers suit image data.
  • Each layer accepts inputs of a certain shape, and Keras infers the input shape of every layer after the first.
  • The topology of a network fixes its hypothesis space, the set of functions it can learn.
  • Keras is a model-level Python library that hands low-level tensor operations to a backend engine.
  • Theano and CNTK were early Keras backends but are no longer developed; Keras today runs on TensorFlow, JAX or PyTorch.
  • The Keras workflow is: prepare the data, define the model, compile it with a loss, an optimizer and metrics, then call fit.
  • A deep learning workstation needs a CUDA-capable NVIDIA GPU with enough memory, the NVIDIA driver, CUDA and cuDNN, a Python environment, a backend and Keras.
  • Linux is the smoothest platform for GPU work, and Jupyter notebooks suit step-by-step experiments.
  • A cloud GPU avoids buying hardware and suits occasional work, while a local workstation is cheaper for regular, long training.
  • The IMDB dataset has 25,000 training and 25,000 test reviews, each set half positive and half negative; load_data(num_words=10000) keeps only the 10,000 most frequent words.
  • Reviews and newswires are multi-hot encoded into 10,000-value vectors before they reach the first Dense layer.
  • A binary classifier ends in Dense(1, sigmoid) and is trained with binary cross-entropy; its output is the probability of the positive class.
  • The Reuters newswire task is single-label multiclass classification into 46 topics, ending in Dense(46, softmax).
  • One-hot labels use categorical_crossentropy and integer labels use sparse_categorical_crossentropy; both give the same loss.
  • A hidden layer much narrower than the number of classes is an information bottleneck and lowers accuracy.
  • Validation loss that rises while training loss falls signals overfitting, so training should stop near the epoch of lowest validation loss.

Learn these by heart

  • Dense layer parameters = inputs × units + units (weights plus biases).
  • relu(x) = max(0, x); sigmoid(z) = 1 / (1 + e^(−z)), a value between 0 and 1.
  • Binary cross-entropy: L = −[y ln p + (1 − y) ln(1 − p)].
  • Softmax: p_i = e^(z_i) / Σ e^(z_j); with a one-hot target, categorical cross-entropy L = −ln(p of the true class).
  • Binary: Dense(1, sigmoid) with binary_crossentropy. Multiclass with C classes: Dense(C, softmax) with categorical_crossentropy (one-hot) or sparse_categorical_crossentropy (integers).
  • Keras workflow: data → model → compile(optimizer, loss, metrics) → fit.

2-mark questions

1 What are the four parts you must define to train a neural network? 2 marks
Model answer

Training needs four parts: layers, combined into a network or model, which hold the learnable weights; the input data and their matching targets; a loss function, which scores how far the predictions are from the targets; and an optimizer, which uses that score to decide how the weights are updated.

2 What is meant by layer compatibility in a neural network? Give an example. 2 marks
Model answer

Each layer accepts input tensors of a certain shape and returns output tensors of a certain shape, so a layer can only follow one whose output it can take. For example, a Dense(32) layer fed 784-value vectors outputs 32-value vectors, so the next layer must accept 32 values. Keras infers these input shapes automatically.

3 What is Keras, and what is meant by its backend engine? 2 marks
Model answer

Keras is a high-level, model-level Python library for defining and training deep learning models. It does not perform low-level tensor operations itself; a backend engine does. Early Keras supported TensorFlow, Theano and CNTK, but Theano and CNTK are no longer developed. Keras today runs on TensorFlow, JAX or PyTorch.

4 Why is a CUDA-capable NVIDIA GPU recommended for a deep learning workstation? 2 marks
Model answer

Training is dominated by large matrix multiplications and convolutions, which a GPU runs in parallel much faster than a CPU. TensorFlow, JAX and PyTorch use NVIDIA's CUDA platform and its cuDNN library for GPU work, so a CUDA-capable GPU with enough memory, local or in the cloud, cuts training time greatly.

5 Encode the review [1, 4, 4, 6] as a multi-hot vector over a vocabulary of 8 word indexes (0 to 7). 2 marks
Model answer

Start with eight zeros and set to 1 the position of every index in the review; a repeated index simply stays 1. Positions 1, 4 and 6 become 1, giving [0, 1, 0, 0, 1, 0, 1, 0]. The movie-review network uses the same encoding with 10,000 positions, one per frequent word.

6 A newswire classifier's softmax gives probability 0.25 to the true topic. Find the categorical cross-entropy loss for that newswire. 2 marks
Model answer

With a one-hot target, categorical cross-entropy keeps only the true-class term: loss = −ln(p_true) = −ln(0.25) = 1.3863. A probability of 1 would give a loss of 0. If the labels are stored as integers instead of one-hot vectors, the same loss is computed with sparse_categorical_crossentropy.

10-mark questions

1 Explain the anatomy of a neural network: layers, models, loss functions and optimizers. Show how they interact during training. 10 marks
Model answer

A neural network is trained by four parts working together: layers, combined into a network or model; the input data and the matching targets; a loss function, which gives the feedback signal; and an optimizer, which decides how the network learns from that signal.

1. Layers. A layer is a data-processing module that takes one or more tensors in and gives one or more tensors out. Most layers have weights, and the weights hold what the network has learned. The kind of layer is chosen to fit the data:

  • vectors of shape (samples, features) suit densely connected (Dense) layers;
  • sequences of shape (samples, timesteps, features) suit recurrent layers such as LSTM;
  • images of shape (samples, height, width, channels) suit 2D convolution (Conv2D) layers.

Layers must also be compatible: each accepts inputs of a certain shape and returns outputs of a certain shape, and Keras works out the input shape of every layer after the first.

2. Models. A model is a graph of layers. The usual one is a linear stack, in which each layer feeds the next; other topologies include networks with two branches, networks with several output heads, and inception blocks. The topology fixes the hypothesis space, the set of functions the network can learn, so choosing it is a key design decision.

3. Loss function. Also called the objective function, it measures how far the predictions are from the true targets, and training tries to minimise it. A network with several outputs can have one loss per output, but these are combined into one scalar, for example by summing them, because gradient descent needs a single number. Common choices are binary cross-entropy for two classes, categorical cross-entropy for many classes and mean squared error for regression.

4. Optimizer. It uses the gradient of the loss score to update the weights. It implements a variant of stochastic gradient descent, such as RMSprop or Adam.

How layers, loss function and optimizer interact in trainingInput X flows through Layer 1 and Layer 2 of the network to give predictions; the loss function compares the predictions with the true targets to give a loss score, and the optimizer uses the score to update the weights of both layers.Network (model)Input XLayer 1(weights)Layer 2(weights)PredictionsTrue targetsLoss functionLoss scoreOptimizerupdate weightsupdate weights
How layers, loss function and optimizer interact in training

Training is a loop: the input X passes through the layers and gives predictions; the loss function compares the predictions with the true targets and gives a loss score; the optimizer uses that score to update the weights; and the loop repeats over many batches until the loss is low.

In conclusion, the layers and the model decide what the network can compute, while the loss function and the optimizer decide how it learns.

2 What is Keras? Explain its main features, its relationship with TensorFlow, Theano and CNTK, and the typical workflow for building a model in Keras. 10 marks
Model answer

Keras is a high-level deep learning library for Python. It offers a convenient way to define and train almost any kind of deep learning model, and it is designed for fast experimentation.

Main features:

  • The same Keras code runs on a CPU or a GPU.
  • Short, readable model definitions make prototyping fast.
  • Ready-made layers cover dense, convolutional and recurrent networks and their combinations.
  • It handles models with several inputs or outputs and layers shared between parts of a model.

Keras and its backends. Keras is a model-level library: it supplies high-level building blocks, but it does not itself carry out low-level operations such as tensor products and convolutions. Those are handed to a specialised, optimised tensor library, the backend engine. Earlier Keras versions could use three backends: TensorFlow, developed at Google; Theano, developed at the Université de Montréal; and CNTK, the Microsoft Cognitive Toolkit. Theano and CNTK are no longer developed, so they are not current choices. Keras today runs on TensorFlow, JAX or PyTorch, and TensorFlow also includes Keras as its high-level API. The backend runs the work on a CPU through optimised maths libraries, or on an NVIDIA GPU through CUDA and cuDNN.

Keras, its backend engines and the hardware they useKeras sits on top and hands its work to a backend engine: TensorFlow, JAX or PyTorch, while the earlier backends Theano and CNTK are no longer developed. Each backend runs on a CPU through maths libraries or on a GPU through CUDA and cuDNN.Backend enginesKeras (modellevel)Earlier:Theano, CNTKTensorFlowJAXPyTorchCPU: mathslibrariesGPU: CUDAand cuDNNno longerdeveloped
Keras, its backend engines and the hardware they use

A typical Keras workflow has four steps:

1. Prepare the training data: input tensors and target tensors.

2. Define a model, a network of layers that maps inputs to targets.

3. Configure learning with compile(): the loss function, the optimizer and the metrics to monitor.

4. Train with fit(), which iterates over the training data in batches.

import keras
from keras import layers

model = keras.Sequential([
    keras.Input(shape=(784,)),
    layers.Dense(32, activation="relu"),
    layers.Dense(10, activation="softmax")
])
model.compile(
    optimizer="rmsprop",
    loss="categorical_crossentropy",
    metrics=["accuracy"])
model.fit(x_train, y_train,
          epochs=5, batch_size=128)

Here x_train holds 784-value input vectors and y_train holds one-hot targets for 10 classes. A model can be defined with the Sequential class, for a linear stack of layers as above, or with the functional API, for any directed acyclic graph of layers.

In conclusion, Keras separates the model definition from the engine that runs it, so the same model code can run on different backends and hardware.

3 Explain how a deep learning workstation is set up to run Keras. Compare training on a local GPU workstation with training in the cloud. 10 marks
Model answer

A deep learning workstation is the machine, at home, in a lab or rented in the cloud, on which models are written and trained. Small models train acceptably on a CPU, but convolutional and recurrent networks on real datasets can take many times longer there, so a GPU is strongly recommended.

Setting up the workstation, step by step:

1. Hardware: a CUDA-capable NVIDIA GPU with enough GPU memory for your models and batch sizes, a multi-core CPU, plenty of RAM and fast SSD storage for datasets.

2. Operating system: Linux, such as Ubuntu, is the smoothest choice for GPU work. On Windows, WSL2, the Windows Subsystem for Linux, provides a Linux environment, and TensorFlow needs it for GPU training on Windows.

3. GPU software: install the NVIDIA driver, then the CUDA toolkit and the cuDNN library in the versions your framework release expects. On Linux, current TensorFlow, JAX and PyTorch packages can also install matching CUDA libraries through pip.

4. Python environment: create an isolated environment with venv or conda, so that the library versions of different projects do not clash.

5. Backend and Keras: install a backend (TensorFlow, JAX or PyTorch) and Keras. Multi-backend Keras picks its backend from the KERAS_BACKEND environment variable.

6. Jupyter notebook: it runs code cell by cell and keeps outputs, plots and notes next to the code, which suits step-by-step experiments.

7. Check that the GPU is seen, for example with TensorFlow. An empty list means the GPU is not visible.

import tensorflow as tf
cfg = tf.config
print(cfg.list_physical_devices("GPU"))
Setting up a deep learning workstationA top-to-bottom chain of setup steps: a CUDA-capable NVIDIA GPU, Linux or WSL2, the NVIDIA driver, CUDA and cuDNN, a Python environment, the backend and Keras, a Jupyter notebook, and a check that the GPU is seen. A cloud GPU instance joins at the Python environment step because its driver and CUDA are often ready.NVIDIA GPU(CUDA-capable)Linux (or WSL2)NVIDIA driverCUDA and cuDNNPythonenvironmentBackendand KerasJupyter notebookCheck theGPU is seenCloud GPUinstancedriver andCUDA ready
Setting up a deep learning workstation

Local workstation or cloud?

  • A cloud GPU instance needs no hardware purchase, starts in minutes and can move to a bigger GPU when needed; many cloud images come with the driver and CUDA ready. But hourly charges add up for long or frequent training, and datasets must be uploaded.
  • A local workstation costs more at the start, but has no hourly charges, keeps data on site and is always available, so it suits anyone who trains models regularly.
  • Hosted notebook services that give limited free GPU time are a good starting point for students.

In conclusion, start with a cloud GPU or a hosted notebook while learning, and move to a local Linux machine with an NVIDIA GPU once deep learning becomes regular work.

4 Explain how a movie-review classifier is built for binary classification: preparing the data, choosing the layers, the loss and the optimizer, and validating the model. Include a Keras program. 10 marks
Model answer

Binary classification puts each input into one of two classes. In the movie-review task, the text of a review is used to predict whether it is positive (label 1) or negative (label 0).

1. The data. The IMDB dataset in Keras has 25,000 training reviews and 25,000 test reviews, each set half positive and half negative. Each review is already a list of word indexes, and load_data(num_words=10000) keeps only the 10,000 most frequent words, so every index is below 10,000.

2. Preparing the data. Lists of different lengths cannot be fed to a Dense layer, so each review becomes a multi-hot vector of 10,000 values: position i is 1 if word i occurs in the review and 0 otherwise. The labels become a float32 array of 0s and 1s.

3. The network. With vector inputs and a 0/1 label, a small stack of Dense layers works well:

  • Dense 16 with relu, then Dense 16 with relu. relu(x) = max(0, x) keeps positive values and zeroes negative ones; without such an activation, stacked Dense layers could learn only linear transformations.
  • Dense 1 with sigmoid. sigmoid(z) = 1/(1 + e^(−z)) squashes the score into the range 0 to 1, read as the probability that the review is positive.

4. Loss and optimizer. Because the output is a probability, binary cross-entropy is the right loss; RMSprop is a sound default optimizer, and accuracy is monitored.

5. Validation. Hold back 10,000 training reviews as a validation set, train on the other 15,000 and watch the validation loss after each epoch. When it starts to rise, the network is overfitting, so train for fewer epochs.

In the program, x_train holds the multi-hot vectors and y_train the float labels:

import keras
from keras import layers

model = keras.Sequential([
    keras.Input(shape=(10000,)),
    layers.Dense(16, activation="relu"),
    layers.Dense(16, activation="relu"),
    layers.Dense(1, activation="sigmoid")
])
model.compile(optimizer="rmsprop",
              loss="binary_crossentropy",
              metrics=["accuracy"])
x_val = x_train[:10000]
y_val = y_train[:10000]
model.fit(x_train[10000:],
          y_train[10000:],
          epochs=20, batch_size=512,
          validation_data=(x_val, y_val))
Layers of the movie-review binary classifierA review encoded as a 10,000-value multi-hot vector passes through Dense 16 with relu, Dense 16 with relu and Dense 1 with sigmoid, giving the probability that the review is positive; binary cross-entropy compares this probability with the label, 1 or 0.Multi-hot reviewDense 16, reluDense 16, reluDense 1, sigmoidProbabilitypositiveLabel: 1 or 0Binarycross-entropy10,000 values
Layers of the movie-review binary classifier

After training, model.predict(x_test) gives one probability per review, and values above 0.5 are read as positive; model.evaluate(x_test, y_test) reports the test loss and accuracy.

In conclusion, a binary classifier on vector data ends in a single sigmoid unit and is trained with binary cross-entropy.

5 The movie-review network takes 10,000-value multi-hot vectors and has the layers Dense(16, relu), Dense(16, relu) and Dense(1, sigmoid). (a) Find the trainable parameters in each layer and in total. (b) Four validation reviews have labels [1, 0, 0, 0] and the network outputs [0.9, 0.3, 0.6, 0.2]. Find the accuracy with a 0.5 threshold and the mean binary cross-entropy. (c) Explain how a validation set taken from the training data shows overfitting. 10 marks
Model answer

The working below follows the binary movie-review classifier.

(a) Parameters. A Dense layer with n inputs and m units has n × m weights plus m biases.

  • Layer 1: 10,000 × 16 + 16 = 160,016
  • Layer 2: 16 × 16 + 16 = 272
  • Layer 3: 16 × 1 + 1 = 17
Layer             Output      Params
Dense 16, relu    (None, 16)  160,016
Dense 16, relu    (None, 16)      272
Dense 1, sigmoid  (None, 1)        17
Total                         160,305

Almost all of the 160,305 parameters are in the first layer, because each of the 10,000 word positions connects to each of its 16 units.

(b) Accuracy and loss. With a threshold of 0.5, the outputs [0.9, 0.3, 0.6, 0.2] give the predicted classes [1, 0, 1, 0]. Against the labels [1, 0, 0, 0], reviews 1, 2 and 4 are right and review 3 is wrong, so accuracy = 3/4 = 75%.

Binary cross-entropy for one review is L = −[y ln p + (1 − y) ln(1 − p)]:

  • Review 1, y = 1, p = 0.9: L = −ln 0.9 = 0.1054
  • Review 2, y = 0, p = 0.3: L = −ln 0.7 = 0.3567
  • Review 3, y = 0, p = 0.6: L = −ln 0.4 = 0.9163
  • Review 4, y = 0, p = 0.2: L = −ln 0.8 = 0.2231

Sum = 1.6015, so the mean loss = 1.6015 / 4 = 0.4004. The wrongly classified review 3 gives the largest loss; the more confident a wrong output, the larger its loss.

(c) Validation and overfitting. The 50,000 IMDB reviews come as 25,000 training and 25,000 test reviews, and the test reviews are kept aside until the end. From the training reviews, 10,000 are held back as a validation set and the network is trained on the other 15,000.

Training, validation and test reviews in the movie-review taskThe 50,000 IMDB reviews split into 25,000 training and 25,000 test reviews; the training reviews split into 15,000 to train on and 10,000 for validation. The validation loss per epoch gives the epoch of lowest loss, after which the model is retrained and the test set is used once.IMDB reviews:50,000Training: 25,000Test: 25,000Train on 15,000Validation:10,000Validationloss per epochEpoch oflowest lossRetrain, thentest oncefit()kept untilthe end
Training, validation and test reviews in the movie-review task

After every epoch, fit() reports the training loss and the validation loss. The training loss keeps falling as the network fits its training reviews ever more closely. The validation loss falls at first, reaches its lowest value after a few epochs and then rises: the network is now learning patterns peculiar to the training reviews that do not carry over to new ones, which is overfitting. So note the epoch with the lowest validation loss, retrain on all 25,000 training reviews for that many epochs, and only then test once on the test set. A smaller network, weight regularisation or dropout also reduce overfitting.

In conclusion, the parameter count, the loss and the validation curve show how big the model is, how wrong it is and when to stop training it.

6 Explain how a newswire classifier assigns each newswire to one of 46 topics. Discuss the label encoding, the output layer, the loss and the information bottleneck, and find the parameters of each layer. For a simplified three-topic case with scores [2.0, 1.0, 0.1], find the softmax probabilities and the loss when the first topic is correct. 10 marks
Model answer

Multiclass classification puts each input into one of several classes. Each Reuters newswire belongs to exactly one of 46 topics, so this is single-label, multiclass classification.

1. Data. The Reuters dataset in Keras gives each newswire as a list of word indexes, and load_data(num_words=10000) keeps the 10,000 most frequent words. Each newswire is multi-hot encoded into a 10,000-value vector, as for movie reviews.

2. Label encoding. Each label is an integer from 0 to 45. Either one-hot encode it into a 46-value vector with a single 1 (keras.utils.to_categorical) and use categorical_crossentropy, or keep the integers and use sparse_categorical_crossentropy. Both compute the same loss.

3. Output layer. The last layer is Dense(46) with softmax, which turns 46 scores into 46 probabilities that add up to 1. The predicted topic is the one with the highest probability.

4. Information bottleneck. A layer can pass on only what its outputs can hold, so a 16-unit hidden layer may be too narrow for 46 topics, and 64 units are used. A hidden layer much narrower than the number of classes, say 4 units, throws information away for good, and validation accuracy drops.

5. Parameters (n × m weights + m biases):

  • 10,000 × 64 + 64 = 640,064
  • 64 × 64 + 64 = 4,160
  • 64 × 46 + 46 = 2,990
Layer              Output      Params
Dense 64, relu     (None, 64)  640,064
Dense 64, relu     (None, 64)    4,160
Dense 46, softmax  (None, 46)    2,990
Total                          647,214

6. Softmax example. Softmax gives p_i = e^(z_i) / Σ e^(z_j). For z = [2.0, 1.0, 0.1]:

  • e^2.0 = 7.3891, e^1.0 = 2.7183, e^0.1 = 1.1052; sum = 11.2125
  • p = [7.3891, 2.7183, 1.1052] / 11.2125 = [0.6590, 0.2424, 0.0986], which sums to 1
  • The target is one-hot [1, 0, 0], so categorical cross-entropy = −ln(0.6590) = 0.4170
Layers of the newswire multiclass classifierA newswire encoded as a 10,000-value multi-hot vector passes through Dense 64 with relu, Dense 64 with relu and Dense 46 with softmax, giving 46 probabilities; categorical cross-entropy compares them with the one-hot label of 46 values.Multi-hotnewswireDense 64, reluDense 64, reluDense 46,softmax46 probabilitiesOne-hot label,46 valuesCategoricalcross-entropy10,000 values
Layers of the newswire multiclass classifier

The Keras model, with the imports as for the movie reviews:

model = keras.Sequential([
    keras.Input(shape=(10000,)),
    layers.Dense(64, activation="relu"),
    layers.Dense(64, activation="relu"),
    layers.Dense(46, activation="softmax")
])
model.compile(
    optimizer="rmsprop",
    loss="categorical_crossentropy",
    metrics=["accuracy"])

In conclusion, a single-label multiclass network ends with one softmax unit per class, uses categorical cross-entropy (or its sparse form for integer labels), and keeps its hidden layers wide enough to avoid an information bottleneck.

Unit 4

Convolutional Neural Networks

Syllabus: Neural networks and representation learning; Convolutional layers; The multichannel convolution operation; Introduction to recurrent neural networks; RNN code; PyTorch tensors: deep learning with PyTorch; CNNs in PyTorch

One-page revision summary

  • Representation learning lets a network learn its own features from raw data, layer by layer, instead of using hand-designed features.
  • In an image network, early layers detect edges, middle layers detect textures and parts, and deeper layers detect whole objects.
  • A convolutional layer slides small learnable filters over its input, and each filter produces one feature map.
  • Local connectivity and weight sharing give convolutional layers far fewer parameters than dense layers and let them detect a pattern anywhere in the image.
  • Padding adds zeros around the border to keep the size, and stride sets how many cells the filter moves at each step.
  • A 2×2 max pooling layer with stride 2 halves the height and width of each feature map and has no parameters.
  • In multichannel convolution a filter is as deep as its input, its per-channel products are summed into one map, and the number of filters sets the number of output channels.
  • A 1×1 convolution mixes the channels at each pixel and changes the number of channels cheaply.
  • An RNN applies the same cell with the same weights at every time step and carries a hidden state that acts as memory of earlier inputs.
  • RNNs are trained by backpropagation through time; LSTM and GRU cells ease vanishing gradients on long sequences, and gradient clipping limits exploding ones.
  • RNN code is a loop over the time steps that updates h = tanh(Wx·x + Wh·h + b) and stores each hidden state.
  • In PyTorch, nn.RNN with batch_first=True takes input of shape (batch, sequence length, features) and returns the hidden states of every step and the final hidden state.
  • A PyTorch tensor has a shape, a dtype and a device, can be moved to a GPU, and tracks gradients when created with requires_grad=True.
  • Calling backward() on a scalar loss fills the .grad field of every tensor created with requires_grad=True, and gradients add up until they are zeroed.
  • A PyTorch model subclasses nn.Module, creates layers such as nn.Conv2d, nn.MaxPool2d and nn.Linear in __init__, and connects them in forward.
  • PyTorch image batches use the (batch, channels, height, width) layout, and nn.CrossEntropyLoss takes raw class scores and integer labels.

Learn these by heart

  • Convolution output size: O = floor((N + 2P − K)/S) + 1 for input size N, kernel K, padding P and stride S.
  • Conv2d parameters = C_out × (K × K × C_in + 1); Dense or Linear parameters = inputs × units + units.
  • RNN step: h_t = tanh(W_x·x_t + W_h·h_(t−1) + b), with the same weights at every step.
  • Single-layer PyTorch nn.RNN parameters = H × I + H × H + 2H for input size I and hidden size H, because it has two bias vectors.
  • PyTorch training step: optimizer.zero_grad(), loss = loss_fn(model(x), y), loss.backward(), optimizer.step().

2-mark questions

1 What is representation learning? Why is it central to deep learning? 2 marks
Model answer

Representation learning means that the model learns useful features (representations) of the raw input by itself during training, instead of using hand-designed features. In a deep network each layer re-represents the output of the layer below, so an image goes from pixels to edges, parts and whole objects, and the last layer classifies using these learned features.

2 Find the output size of a convolutional layer for a 28×28 input with a 3×3 kernel, stride 2 and padding 1. 2 marks
Model answer

Output size O = floor((N + 2P − K)/S) + 1. Here N = 28, K = 3, P = 1 and S = 2, so O = floor((28 + 2 − 3)/2) + 1 = floor(27/2) + 1 = 13 + 1 = 14. Each output feature map is 14×14.

3 How many parameters does a convolutional layer with 16 filters of size 3×3 have when its input is an RGB image? 2 marks
Model answer

An RGB input has 3 channels, and each filter spans all of them, so one filter has 3 × 3 × 3 = 27 weights plus 1 bias, that is 28 parameters. With 16 filters the layer has 16 × 28 = 448 parameters, whatever the height and width of the image.

4 What is a recurrent neural network? Write its hidden-state equation. 2 marks
Model answer

A recurrent neural network (RNN) processes a sequence one element at a time and carries a hidden state that summarises what it has seen so far. At step t: h_t = tanh(W_x·x_t + W_h·h_(t−1) + b). The same weights are reused at every time step, so one network handles sequences of any length.

5 How many trainable parameters does the PyTorch layer nn.RNN(input_size=10, hidden_size=20) have? 2 marks
Model answer

A single-layer nn.RNN holds an input-to-hidden weight matrix of 20 × 10 = 200 values, a hidden-to-hidden matrix of 20 × 20 = 400 values and two bias vectors (bias_ih and bias_hh) of 20 each. Total = 200 + 400 + 20 + 20 = 640. A Keras SimpleRNN of this size has one bias vector, so 620.

6 What is a PyTorch tensor? How does it differ from a NumPy array? 2 marks
Model answer

A PyTorch tensor is an n-dimensional array of numbers with a shape, a data type (dtype) and a device; for example, torch.zeros(2, 3) has shape (2, 3). Unlike a NumPy array, a tensor can be copied to a GPU with .to("cuda") and, when created with requires_grad=True, it records operations so that autograd can compute gradients.

10-mark questions

1 Explain representation learning. How does a deep neural network learn a hierarchy of features, and why are convolutional layers preferred over fully connected layers for images? 10 marks
Model answer

The performance of a learning system depends heavily on how its input is represented. Classical machine learning relied on hand-designed features, such as colour histograms or edge counts chosen by an expert, and trained a simple classifier on them. Representation learning instead lets the model discover the features itself from raw data, as part of training.

1. The idea: a network learns a mapping from the raw input (pixels, words, audio samples) to a new representation, a vector of features in which the task becomes easy. The features and the classifier are trained together by gradient descent on the same loss, so the features are tuned to the task.

2. Layers as successive representations: every layer takes the representation produced by the layer below and transforms it with weights followed by a nonlinear activation. Stacking layers builds a hierarchy. For an image, the first layer responds to edges and colour blobs, middle layers combine edges into textures and parts such as eyes or wheels, and deeper layers combine parts into whole objects. The final layer is a simple classifier working on this learned representation.

Hierarchy of features learned by a deep networkA top-to-bottom chain: raw pixels pass through the first layer to edges and colour blobs, through middle layers to textures and parts, through deeper layers to whole objects, and then to the classifier. The middle three stages are grouped as the learned representation.Learned representationRaw pixelsEdges andcolour blobsTexturesand partsWhole objectsClassifierfirst layermiddle layersdeeper layersfinal layer
Hierarchy of features learned by a deep network

3. Advantages: no manual feature engineering is needed; low-level features are reused by many higher-level ones; the same method works for images, text and speech; and with enough labelled data, learned features usually beat hand-designed ones. Unsupervised models such as autoencoders also learn representations, by learning to reconstruct their input.

4. Why fully connected layers suit images poorly: a 32×32 RGB image has 32 × 32 × 3 = 3,072 inputs. A dense layer of 128 units on it needs 3,072 × 128 + 128 = 393,344 parameters. It also ignores the fact that nearby pixels are related, and a pattern seen in one position must be learned again for every other position.

5. Why convolutional layers suit images: a convolutional layer connects each output only to a small local patch (local connectivity) and slides the same small filter over the whole image (weight sharing). A layer of 32 filters of size 3×3 on the same RGB image needs only 32 × (3 × 3 × 3 + 1) = 896 parameters, and a pattern learned in one place is detected everywhere.

In short, representation learning replaces hand-crafted features with features learned from data, and convolutional layers are the natural way to learn a hierarchy of local, reusable image features with few parameters.

2 Explain the working of a convolutional layer. Apply a 3×3 kernel to a 4×4 input with stride 1 and no padding, and explain the effect of padding and stride on the output size. 10 marks
Model answer

A convolutional layer is the main building block of a CNN. It holds a set of small learnable filters (kernels). Each filter slides over the input and, at every position, computes the sum of the element-wise products between the filter and the patch under it, plus a bias. The grid of results is a feature map, which shows where the filter's pattern occurs. Deep learning libraries actually compute cross-correlation (the kernel is not flipped), but the operation is still called convolution.

1. Local connectivity: each output value depends only on a small patch of the input, its receptive field.

2. Weight sharing: the same filter weights are used at every position, so the layer has few parameters and detects a pattern wherever it appears.

3. Worked example (stride 1, no padding, bias 0): input X and kernel K, a vertical-edge detector.

X = 2 1 0 3      K = 1 0 -1
    1 3 1 0          1 0 -1
    0 2 1 1          1 0 -1
    1 0 2 2

K adds the left column of each 3×3 patch and subtracts its right column:

  • Top-left: (2+1+0) − (0+1+1) = 3 − 2 = 1
  • Top-right: (1+3+2) − (3+0+1) = 6 − 4 = 2
  • Bottom-left: (1+0+1) − (1+1+2) = 2 − 4 = −2
  • Bottom-right: (3+2+0) − (0+1+2) = 5 − 3 = 2

The feature map is [[1, 2], [−2, 2]], and after ReLU it becomes [[1, 2], [0, 2]].

One convolutional filter on a 4×4 inputThe 4×4 input X and the 3×3 kernel K feed a sum of products (bias 0), taken over each 3×3 patch with stride 1 and the same weights everywhere. This gives the feature map [[1,2],[−2,2]], and ReLU turns it into [[1,2],[0,2]].Input X (4×4)Kernel K (3×3)Sum ofproducts, bias 0Feature map[[1,2],[−2,2]]ReLU: [[1,2],[0,2]]3×3 patch,stride 1same weights
One convolutional filter on a 4×4 input

4. Output size: for an N×N input, a K×K kernel, padding P and stride S, O = floor((N + 2P − K)/S) + 1. Here O = (4 + 0 − 3)/1 + 1 = 2, so the output is 2×2.

5. Padding: adding P rings of zeros around the input keeps information at the borders and controls the size. With P = 1 and S = 1, O = (4 + 2 − 3)/1 + 1 = 4, so the output stays 4×4 ("same" padding).

6. Stride: moving the filter S cells at a time shrinks the output. With P = 1 and S = 2, O = floor(3/2) + 1 = 2.

7. Depth of the output: a layer with F filters produces F feature maps, and each filter has K × K × (input channels) weights plus one bias.

In conclusion, a convolutional layer learns local pattern detectors with shared weights, and the kernel size, padding and stride together fix the size of each feature map.

3 Explain the multichannel convolution operation. Compute the output of one 2×2 filter applied to a two-channel 3×3 input, and give the general formulas for the output shape and the number of parameters. 10 marks
Model answer

Real inputs to a convolutional layer have several channels: an RGB image has 3, and a hidden convolutional layer outputs one channel per filter. Multichannel convolution lets every filter look at all input channels at once.

1. Shape of a filter: for an input with C_in channels, each filter has shape C_in × K × K, one K × K slice per input channel. In a standard convolution, a filter is as deep as its input.

2. Operation at one position: each input channel is multiplied element-wise with its own slice of the filter, all these products are added across every channel, and one bias is added. The result is a single number, so one filter gives one output feature map, however many input channels there are.

3. Many filters: a layer with C_out filters stacks their maps, so the output has C_out channels. Output shape = C_out × O × O, where O = floor((N + 2P − K)/S) + 1.

4. Parameters = C_out × (K × K × C_in + 1). The count does not depend on the image size.

5. Worked example: two input channels of size 3×3, one filter with two 2×2 slices, bias 1, stride 1 and no padding, so O = 3 − 2 + 1 = 2.

Channel 1  Slice 1   Channel 2  Slice 2
1 0 2      1 0       0 1 1      0 1
3 1 0      0 1       2 0 1      1 0
0 2 1                1 1 0

Slice 1 adds the main diagonal of each 2×2 patch, and slice 2 adds the other diagonal.

  • Channel 1 part: top-left 1+1 = 2, top-right 0+0 = 0, bottom-left 3+2 = 5, bottom-right 1+1 = 2
  • Channel 2 part: top-left 1+2 = 3, top-right 1+0 = 1, bottom-left 0+1 = 1, bottom-right 1+1 = 2
  • Output = channel 1 part + channel 2 part + bias:
2+3+1  0+1+1     6  2
5+1+1  2+2+1  =  7  5
Multichannel convolution with one two-slice filterChannel 1 is combined with slice 1 to give part 1 [[2,0],[5,2]], and channel 2 with slice 2 to give part 2 [[3,1],[1,2]]. The two parts are added together with bias 1 to give the single output map [[6,2],[7,5]].Channel 1 (3×3)Channel 2 (3×3)Part 1: [[2,0],[5,2]]Part 2: [[3,1],[1,2]]Sum + bias 1Output [[6,2],[7,5]]with slice 1with slice 2
Multichannel convolution with one two-slice filter

6. Layer size: with 8 such filters the output is 8 × 2 × 2 and the layer has 8 × (2 × 2 × 2 + 1) = 72 parameters. A layer of 64 filters of size 3×3 on a 32-channel input has 64 × (3 × 3 × 32 + 1) = 18,496 parameters.

7. A 1×1 convolution (K = 1) mixes the channels at each pixel and changes the number of channels cheaply.

Thus multichannel convolution sums the per-channel responses of a filter into one map, and the number of filters, not the number of input channels, sets the depth of the output.

4 Explain the structure of a recurrent neural network with its unrolled form. Write code for the forward pass of a simple RNN and trace it for the input sequence 1, 2, −1. 10 marks
Model answer

Feedforward networks and CNNs map one fixed-size input to one output and keep no memory between inputs. Text, speech and time series are sequences in which order matters, so they need a model with memory. A recurrent neural network (RNN) reads a sequence one element at a time and keeps a hidden state that summarises everything read so far.

1. Recurrence: at time step t the network combines the current input x_t with the previous hidden state h_(t−1): h_t = tanh(W_x·x_t + W_h·h_(t−1) + b). When an output is needed, y_t = W_y·h_t + b_y. The initial state h0 is usually zero.

2. Parameter sharing: the same W_x, W_h and b are used at every step, so the number of parameters does not grow with the length of the sequence.

3. Unrolling: drawing one copy of the cell per time step turns the loop into a deep feedforward chain, with the hidden state passed from left to right.

RNN unrolled over the sequence 1, 2, −1Inputs x1 = 1, x2 = 2 and x3 = −1 enter the hidden states through Wx, and each hidden state passes to the next through Wh, starting from h0 = 0: h1 = 0.4621, h2 = 0.8786, h3 = 0.2002. The last state h3 feeds the output layer (many-to-one).x1 = 1x2 = 2x3 = −1h0 = 0h1 = 0.4621h2 = 0.8786h3 = 0.2002Output layerWxWxWxWhWhWhmany-to-one
RNN unrolled over the sequence 1, 2, −1

4. Training: the unrolled network is trained by backpropagation through time (BPTT), which sends gradients back along the chain. Repeated multiplication by W_h makes gradients vanish or explode on long sequences: LSTM and GRU cells ease the vanishing, and gradient clipping limits the exploding.

5. Code for the forward pass (NumPy):

import numpy as np

def rnn_forward(xs, Wx, Wh, b, h0):
    h, hs = h0, []
    for x in xs:      # one time step
        h = np.tanh(Wx @ x + Wh @ h + b)
        hs.append(h)
    return hs         # all hidden states

Wx = np.array([[0.5]])
Wh = np.array([[0.8]])
b, h0 = np.zeros(1), np.zeros(1)
xs = np.array([[1.0], [2.0], [-1.0]])
hs = rnn_forward(xs, Wx, Wh, b, h0)

6. Trace with one input and one hidden unit (Wx = 0.5, Wh = 0.8, b = 0, h0 = 0) for the sequence 1, 2, −1:

  • t = 1: x1 = 1, 0.5·1 + 0.8·0 = 0.5, h1 = tanh(0.5) = 0.4621
  • t = 2: x2 = 2, 0.5·2 + 0.8·0.4621 = 1.3697, h2 = tanh(1.3697) = 0.8786
  • t = 3: x3 = −1, 0.5·(−1) + 0.8·0.8786 = 0.2029, h3 = tanh(0.2029) = 0.2002

h3 still depends on the first input through h1 and h2; this is the network's memory. To classify a whole sentence, h3 is passed to an output layer (many-to-one); to tag every word, an output is taken at every step (many-to-many).

In conclusion, an RNN is one cell applied repeatedly with shared weights, its hidden state carries information across time, and its forward pass is a simple loop over the sequence.

5 Explain PyTorch tensors and their main operations. Show with code how autograd computes gradients and how one gradient-descent step updates the weights. 10 marks
Model answer

PyTorch is a deep learning library built around the tensor, an n-dimensional array, together with automatic differentiation (autograd) and ready-made layers and optimisers. The graph of operations is built as the code runs, which makes models easy to debug.

1. Creating tensors: torch.tensor([[1., 2.], [3., 4.]]) builds one from data; torch.zeros(2, 3), torch.ones(2, 3), torch.randn(2, 3) and torch.arange(6) build one from a shape or a range.

2. Attributes: every tensor has a shape (x.shape), a data type (x.dtype, such as torch.float32 or torch.int64) and a device (x.device, CPU or GPU). x.to("cuda") returns a copy on a CUDA-capable NVIDIA GPU when one is present.

3. Operations: element-wise arithmetic (+, *, torch.exp), matrix multiplication (a @ b), reductions (x.sum(), x.mean()), NumPy-style indexing and slicing, and reshaping. A batch of 64 grayscale 28×28 images has shape (64, 1, 28, 28) in the (batch, channels, height, width) order, and x.reshape(64, -1) flattens it to (64, 784), since 28 × 28 = 784. torch.from_numpy() and x.numpy() convert to and from NumPy.

4. Autograd: a tensor created with requires_grad=True records the operations applied to it. Calling backward() on a scalar loss computes the gradient of the loss with respect to every such tensor and fills its .grad field. Gradients add up over calls, so they are zeroed before each step.

5. Worked example: a linear model ŷ = w·x + b with w = 2, b = 1, one sample x = 3, target y = 10 and squared-error loss L = (ŷ − y)².

  • Forward: ŷ = 2·3 + 1 = 7 and L = (7 − 10)² = 9
  • Gradients: ∂L/∂w = 2(ŷ − y)·x = 2(−3)(3) = −18 and ∂L/∂b = 2(ŷ − y) = −6
  • Update with learning rate 0.01: w = 2 − 0.01(−18) = 2.18 and b = 1 − 0.01(−6) = 1.06. The new prediction is 2.18·3 + 1.06 = 7.6, so the loss falls from 9 to 5.76.
import torch
x = torch.tensor(3.0)
y = torch.tensor(10.0)
w = torch.tensor(2.0, requires_grad=True)
b = torch.tensor(1.0, requires_grad=True)
loss = (w * x + b - y) ** 2
loss.backward()
print(w.grad.item(), b.grad.item())
# prints -18.0 -6.0
with torch.no_grad():
    w -= 0.01 * w.grad
    b -= 0.01 * b.grad

6. Deep learning with PyTorch: a real model subclasses nn.Module, a loss such as nn.CrossEntropyLoss measures the error, and an optimiser from torch.optim (SGD, Adam) applies the update. Each training step is: zero the gradients, forward pass, compute the loss, loss.backward(), optimiser step, then the next batch.

One PyTorch training step as a loopA loop of six steps: a batch of tensors x, y goes to the forward pass, then compute the loss, then loss.backward() fills the .grad fields, then the optimiser step updates the weights, then zero the gradients, and the loop returns to the next batch.Batch oftensors x, yForward passCompute the lossloss.backward()Optimiser stepZero thegradientsprediction ŷ.grad filledweightsupdatednext batch
One PyTorch training step as a loop

In conclusion, tensors hold the data and the parameters, autograd supplies the gradients, and torch.optim turns them into weight updates, which together make up the training loop.

6 Write a PyTorch program for a CNN that classifies 28×28 grayscale images into 10 classes. Give the output shape and number of parameters of each layer, and explain the training step. 10 marks
Model answer

A CNN for small grayscale images, such as handwritten digits, stacks convolution and pooling blocks as a feature extractor and ends with a fully connected classifier. In PyTorch the model subclasses nn.Module: layers are created in __init__ and connected in forward. Tensors use the (batch, channels, height, width) layout, so one image is 1×28×28.

1. Model code:

import torch
import torch.nn as nn

# Conv2d(in, out, kernel, stride, padding)
class SmallCNN(nn.Module):
    def __init__(self):
        super().__init__()
        self.features = nn.Sequential(
            nn.Conv2d(1, 16, 3, 1, 1),
            nn.ReLU(),
            nn.MaxPool2d(2),
            nn.Conv2d(16, 32, 3, 1, 1),
            nn.ReLU(),
            nn.MaxPool2d(2),
        )
        self.fc = nn.Linear(32*7*7, 10)

    def forward(self, x):
        x = self.features(x)
        return self.fc(x.flatten(1))

2. Shapes and parameters. A 3×3 kernel with stride 1 and padding 1 keeps the size, since (28 + 2 − 3)/1 + 1 = 28; MaxPool2d(2) uses a 2×2 window with stride 2 and halves height and width. Conv2d parameters = C_out × (3 × 3 × C_in + 1); Linear parameters = inputs × outputs + outputs.

Layer             Output     Params
Input             1x28x28         0
Conv2d 1->16      16x28x28      160
ReLU, MaxPool2d   16x14x14        0
Conv2d 16->32     32x14x14    4,640
ReLU, MaxPool2d   32x7x7          0
Flatten           1568            0
Linear 1568->10   10         15,690
Total                        20,490

Here 160 = 16 × (9 + 1), 4,640 = 32 × (9 × 16 + 1) and 15,690 = 1568 × 10 + 10.

Layers of the PyTorch CNN for 28×28 grayscale imagesA top-to-bottom chain: input 1×28×28, Conv2d 16 with 3×3 kernel and ReLU (16×28×28), MaxPool2d (16×14×14), Conv2d 32 with ReLU (32×14×14), MaxPool2d (32×7×7), Flatten (1568), Linear 1568 to 10 and 10 class scores. The convolution and pooling layers form the feature extractor and the last two layers form the classifier.Feature extractorClassifierInput 1×28×28Conv2d 16,3×3, ReLUMaxPool2d 2Conv2d 32,3×3, ReLUMaxPool2d 2FlattenLinear 1568 → 1010 class scores16×28×2816×14×1432×14×1432×7×7156810
Layers of the PyTorch CNN for 28×28 grayscale images

3. Training step:

model = SmallCNN()
loss_fn = nn.CrossEntropyLoss()
params = model.parameters()
opt = torch.optim.SGD(params, lr=0.01)
for images, labels in train_loader:
    opt.zero_grad()
    loss = loss_fn(model(images), labels)
    loss.backward()
    opt.step()

train_loader is a DataLoader that yields batches of images with shape (batch, 1, 28, 28) and integer labels 0 to 9. nn.CrossEntropyLoss applies log-softmax internally, so the model outputs 10 raw class scores and has no softmax layer. For each batch the gradients are cleared, the loss is computed, backward() fills the gradients and opt.step() updates all 20,490 parameters. Calling model.to("cuda") and moving each batch to the same device runs training on a GPU, and model.eval() switches to evaluation mode before testing.

In conclusion, PyTorch builds a CNN from nn.Conv2d, nn.MaxPool2d and nn.Linear inside an nn.Module, and the shape arithmetic above fixes the size of the final Linear layer.

Unit 5

Interactive Applications of Deep Learning and Deep Learning Research

Syllabus: Machine vision; Natural language processing; Generative adversarial networks; Deep reinforcement learning; Autoencoders; Deep generative models: Boltzmann machines; Restricted Boltzmann machines; Deep belief networks

One-page revision summary

  • Machine vision uses CNNs for image classification, object detection with bounding boxes, and segmentation that labels every pixel.
  • Transfer learning reuses a CNN pretrained on a large dataset such as ImageNet and trains only a new classifier head on a small dataset.
  • An NLP pipeline splits text into tokens, maps them to integer indices, turns them into dense word vectors and reads the sequence with an LSTM or a transformer.
  • Word2vec learns word vectors with skip-gram, which predicts context words from a target word, or CBOW, which predicts the target word from its context.
  • A GAN trains a generator, which turns random noise into fake samples, against a discriminator, which outputs the probability that a sample is real.
  • GAN training alternates discriminator and generator updates and can suffer from instability and mode collapse.
  • Deep reinforcement learning uses a neural network for the policy or value function of an agent that acts in an environment to maximise the discounted return.
  • A DQN stabilises Q-learning with experience replay and a target network, and explores with ε-greedy action selection.
  • An autoencoder squeezes its input through a bottleneck code and is trained, with the input as its own target, to minimise the reconstruction error.
  • Sparse, denoising and contractive autoencoders add a penalty or noise so that the network learns useful features instead of copying its input, and a variational autoencoder samples its code so that it can generate new data.
  • A Boltzmann machine is an energy-based model of stochastic binary units in which a state of energy E has probability e^(−E)/Z.
  • An RBM is a Boltzmann machine with no links inside the visible or hidden layer, so each layer can be sampled in one step given the other.
  • RBMs are trained by contrastive divergence, which replaces the intractable model term of the gradient with a short Gibbs chain started at the data.
  • A deep belief network stacks RBMs trained greedily, one layer at a time without labels, and can then be fine-tuned with backpropagation.

Learn these by heart

  • Convolution output size = (n − k + 2p)/s + 1, rounded down; Conv2D parameters = (k × k × input channels + 1) × filters.
  • GAN objective: min_G max_D E_x[ln D(x)] + E_z[ln(1 − D(G(z)))].
  • Discounted return: G_t = r_t+1 + γ r_t+2 + γ² r_t+3 + …, with 0 ≤ γ ≤ 1.
  • Q-learning: Q(s, a) ← Q(s, a) + α [r + γ max_a′ Q(s′, a′) − Q(s, a)].
  • RBM energy: E(v, h) = −Σ a_i v_i − Σ b_j h_j − Σ v_i W_ij h_j, and P(v, h) = e^(−E(v, h))/Z.
  • RBM conditionals: P(h_j = 1 | v) = σ(b_j + Σ_i v_i W_ij) and P(v_i = 1 | h) = σ(a_i + Σ_j W_ij h_j).
  • CD-1 weight update: ΔW_ij = η (⟨v_i h_j⟩data − ⟨v_i h_j⟩reconstruction).

2-mark questions

1 Differentiate image classification, object detection and image segmentation in machine vision. 2 marks
Model answer

Image classification assigns one label to a whole image, such as "cat". Object detection finds every object in the image and gives each one a class label and a bounding box. Image segmentation labels every pixel: semantic segmentation labels each pixel with a class, and instance segmentation also separates the individual objects.

2 What is a word vector? Why is it preferred to one-hot encoding in natural language processing? 2 marks
Model answer

A word vector (word embedding) is a dense, low-dimensional vector of real numbers learned from text, so that words used in similar contexts get nearby vectors. A one-hot vector is as long as the vocabulary, almost all zeros, and treats every pair of words as equally different, so it captures no meaning.

3 What is mode collapse in a generative adversarial network? 2 marks
Model answer

Mode collapse is a GAN training failure in which the generator produces only one or a few kinds of output, for example the same digit every time, because those samples fool the current discriminator. The outputs may look realistic, but they lack the variety of the real training data.

4 An agent receives rewards 1, 0 and 2 in three successive time steps. Find the discounted return with discount factor γ = 0.9. 2 marks
Model answer

The discounted return is G = r1 + γ r2 + γ² r3.

G = 1 + 0.9 × 0 + 0.81 × 2 = 1 + 0 + 1.62 = 2.62.

The discount factor γ, between 0 and 1, makes rewards that arrive sooner count more than rewards that arrive later.

5 What is a denoising autoencoder? 2 marks
Model answer

A denoising autoencoder receives a corrupted copy of each input, for example with random noise added or some pixels set to zero, and is trained to reconstruct the original clean input. Because it cannot simply copy its input to its output, it learns robust features of the data, and it can be used to remove noise from images.

6 What is a Boltzmann machine? Write its energy function. 2 marks
Model answer

A Boltzmann machine is an energy-based network of stochastic binary units, usually divided into visible and hidden units and joined by symmetric, undirected weights. A state x has energy E(x) = −Σ(i<j) w_ij x_i x_j − Σ_i b_i x_i and probability P(x) = e^(−E(x)) / Z, where the partition function Z sums e^(−E) over all states.

10-mark questions

1 Explain how deep learning is applied to machine vision. Describe the main vision tasks, and trace the output shape and parameter count of each layer of a small CNN image classifier. 10 marks
Model answer

Machine vision is the field in which computers interpret images and video. Deep learning, mainly through convolutional neural networks (CNNs), learns visual features directly from pixels instead of relying on hand-designed features.

The main machine vision tasks are:

  • Image classification: one label for the whole image.
  • Object detection: a class label and a bounding box for every object. Two-stage detectors such as Faster R-CNN first propose regions and then classify them; single-stage detectors such as YOLO predict boxes and classes in one pass.
  • Image segmentation: a class for every pixel (semantic segmentation, for example with U-Net) or a separate mask for every object (instance segmentation, for example with Mask R-CNN).

A CNN classifier works in these steps:

1. Convolution layers slide small filters over the image; early layers detect edges and textures, and deeper layers detect parts and whole objects.

2. ReLU activation adds non-linearity.

3. Max pooling halves the height and width, which cuts computation and tolerates small shifts.

4. Flatten turns the final feature maps into a vector.

5. A Dense softmax layer gives one probability per class.

CNN image classifier for a 32×32×3 image and 10 classesA top-to-bottom chain: Input 32×32×3, Conv2D 32 giving 30×30×32, MaxPool giving 15×15×32, Conv2D 64 giving 13×13×64, MaxPool giving 6×6×64, Flatten giving 2304 values, and Dense 10 with softmax giving one probability per class.Input 32×32×3Conv2D 32,relu: 30×30×32MaxPool 2×2:15×15×32Conv2D 64,relu: 13×13×64MaxPool2×2: 6×6×64Flatten: 2304Dense 10,softmax
CNN image classifier for a 32×32×3 image and 10 classes

Take a 32×32×3 colour image and 10 classes. Each convolution uses 3×3 filters, stride 1 and no padding, so its output size is (n − k + 2p)/s + 1; for the first layer, (32 − 3 + 0)/1 + 1 = 30. Each 2×2 max pool has stride 2. A Conv2D layer has (k × k × input channels + 1) × filters parameters.

Layer           Output     Params
Input           32×32×3         0
Conv2D 32, 3×3  30×30×32      896
MaxPool 2×2     15×15×32        0
Conv2D 64, 3×3  13×13×64   18,496
MaxPool 2×2     6×6×64          0
Flatten         2304            0
Dense 10        10         23,050
Total                      42,442

The second pool gives 6×6 because 13/2 is rounded down. Conv2D parameters: (3×3×3 + 1) × 32 = 896 and (3×3×32 + 1) × 64 = 18,496; Dense: 2304 × 10 + 10 = 23,050.

With little data, transfer learning helps: a CNN pretrained on a large dataset such as ImageNet is reused as a frozen feature extractor, and only a new classifier head is trained. Applications include face recognition, medical image analysis, self-driving cars and factory quality inspection.

In conclusion, convolution, pooling and dense layers give a CNN a hierarchy of features that powers classification, detection and segmentation.

2 Explain how deep learning is used in natural language processing. Describe text preprocessing, word vectors and a recurrent model that classifies the sentiment of movie reviews. 10 marks
Model answer

Natural language processing (NLP) lets computers work with human language: classifying documents, analysing sentiment, translating and answering questions. Deep learning replaced most hand-built language rules with models that learn from large amounts of text.

1. Preprocessing. Raw text is split into tokens, usually words, after converting to lower case and removing punctuation; stop words such as "the" may be dropped and words reduced to a stem. A vocabulary of the most frequent words is built, each token is replaced by its integer index, and sequences are padded or cut to a fixed length.

2. One-hot encoding. Each word becomes a vector as long as the vocabulary with a single 1. These vectors are huge and sparse, and every pair of words is equally far apart, so no meaning is captured.

3. Word vectors. An embedding maps each word to a dense vector of, say, 16 to 300 real numbers, so that words used in similar contexts lie close together. Word2vec learns them with a shallow network: skip-gram predicts the surrounding words from a target word, and CBOW predicts the target word from its context. Alternatively, an Embedding layer learns the vectors together with the task. Arithmetic such as king − man + woman ≈ queen shows that directions in this space carry meaning.

4. Recurrent model. Word order matters, so the embedded sequence is read by an RNN, usually an LSTM or GRU, which carries a hidden state from word to word and uses gates to keep long-range information.

Example: the IMDB dataset has 25,000 training and 25,000 test movie reviews labelled positive or negative. Keep the 10,000 most frequent words and use this model:

Sentiment classifier for IMDB movie reviewsA top-to-bottom chain: review text is split into tokens, the tokens become integer indices, an Embedding layer of 10,000 × 16 turns them into word vectors, an LSTM with 32 units reads the sequence, and Dense 1 with sigmoid outputs P(positive).PreprocessingReview textTokensInteger indicesEmbedding10,000 × 16LSTM, 32 unitsDense 1, sigmoidP(positive)word vectors
Sentiment classifier for IMDB movie reviews
  • Embedding (10,000 words × 16 values): 10,000 × 16 = 160,000 parameters.
  • LSTM with 32 units: 4 × (32 × (16 + 32) + 32) = 6,272 parameters, because its input, forget and output gates and its candidate cell state each have input weights, recurrent weights and a bias.
  • Dense 1 with sigmoid: 32 + 1 = 33 parameters, giving P(positive).

The model has 166,305 parameters and is trained with binary cross-entropy. For many classes, such as the 46 newswire topics of the Reuters dataset, the last layer becomes Dense 46 with softmax and the loss becomes categorical cross-entropy.

Modern NLP adds attention: encoder–decoder models translate sentences, and transformer models such as BERT and GPT process whole sequences in parallel with self-attention.

In conclusion, deep NLP turns text into token indices, then dense word vectors, then a sequence model whose output layer suits the task.

3 Explain the architecture and training of a generative adversarial network (GAN). Write its objective function, and find the discriminator and generator losses when D(x) = 0.9 for a real sample and D(G(z)) = 0.2 for a fake one. 10 marks
Model answer

A generative adversarial network (GAN) learns to create new data, such as realistic images, by setting two neural networks against each other in a game.

1. Generator G. It takes a random noise vector z, for example 100 numbers drawn from a normal distribution, and turns it into a fake sample G(z). For images it usually uses transposed convolutions to grow the noise into a picture.

2. Discriminator D. It is a binary classifier that receives either a real sample x or a fake sample G(z) and outputs D(·), the probability that its input is real.

GAN: generator and discriminator trained against each otherRandom noise z goes into the generator G, which outputs a fake sample G(z). The discriminator D receives fake samples and real samples x and outputs D(·), the probability that its input is real; the binary cross-entropy loss computed from it updates only D's weights in the discriminator step and only G's weights in the generator step.Random noise zGenerator GFake sample G(z)Real sample xDiscriminator DD(·):probability realBinary cross-entropy lossUpdate onlyD's weightsUpdate onlyG's weightslabel 0in D steplabel 1D stepG step
GAN: generator and discriminator trained against each other

3. Objective. The two networks play a minimax game:

min_G max_D V(D, G) = E_x[ln D(x)] + E_z[ln(1 − D(G(z)))]

D tries to make V large (D(x) → 1 and D(G(z)) → 0), while G tries to make it small by fooling D.

4. Training alternates two steps on each minibatch:

  • Discriminator step: label real samples 1 and fake samples 0, compute the binary cross-entropy loss and update only D's weights.
  • Generator step: generate fakes, label them 1 ("real"), pass them through D and update only G's weights. Minimising −ln D(G(z)) instead of ln(1 − D(G(z))) gives stronger gradients early in training, when D easily rejects fakes.

In theory, the game reaches its optimum when the generator's distribution equals the data distribution, and D then outputs 0.5 everywhere.

Worked example with D(x) = 0.9 and D(G(z)) = 0.2:

  • Discriminator loss L_D = −[ln D(x) + ln(1 − D(G(z)))] = −[ln 0.9 + ln 0.8] = 0.1054 + 0.2231 = 0.3285.
  • Generator loss L_G = −ln D(G(z)) = −ln 0.2 = 1.6094.

The discriminator is doing well, so its loss is small; the generator's loss is large, and its gradient pushes G to raise D(G(z)).

5. Difficulties. Training can be unstable and may not converge; a discriminator that becomes too strong leaves G with almost no gradient; and mode collapse makes G produce only a few kinds of output. Deep convolutional GANs (DCGANs) improve stability with strided convolutions instead of pooling, batch normalisation, ReLU in G and LeakyReLU in D.

6. Applications. GANs create realistic faces, turn sketches or maps into photos (image-to-image translation), raise image resolution, transfer artistic style and produce extra training data.

In conclusion, a GAN learns to imitate a data distribution without an explicit density formula: the generator improves only because the discriminator keeps telling real from fake.

4 Explain deep reinforcement learning with the agent–environment loop, Q-learning and the deep Q-network (DQN). Perform one Q-learning update for Q(s, a) = 2.0, r = 1, max Q(s′, a′) = 3.0, α = 0.1 and γ = 0.9. 10 marks
Model answer

Reinforcement learning (RL) trains an agent to choose actions by trial and error so that it collects as much reward as possible. Deep reinforcement learning uses a deep neural network for the agent's policy or value function, so that it can act directly from large inputs such as game screens.

1. Agent–environment loop. At time t the agent observes state s_t and picks action a_t by following its policy π; the environment returns a reward r_t+1 and the next state s_t+1. The problem is modelled as a Markov decision process, and the goal is to maximise the discounted return G_t = r_t+1 + γ r_t+2 + γ² r_t+3 + …, where the discount factor γ lies between 0 and 1.

Deep Q-network agent interacting with its environmentThe agent's Q-network chooses action a_t, which acts on the environment; the environment returns the state s_t+1 and reward r_t+1 to the agent. Each transition (s, a, r, s′) is also stored in a replay memory, from which random minibatches train the Q-network.Agent withQ-network θAction a_tReplay memoryState s_t+1,reward r_t+1Environmentstore (s,a, r, s′)randomminibatch
Deep Q-network agent interacting with its environment

2. Q-learning. The action value Q(s, a) is the expected return after taking action a in state s and acting optimally afterwards. After every step it moves towards the Bellman target:

Q(s, a) ← Q(s, a) + α [r + γ max_a′ Q(s′, a′) − Q(s, a)]

where α is the learning rate. Worked update:

  • Target = r + γ max Q(s′, a′) = 1 + 0.9 × 3.0 = 3.7
  • TD error = 3.7 − 2.0 = 1.7
  • New Q(s, a) = 2.0 + 0.1 × 1.7 = 2.17

3. Deep Q-network. A Q-table cannot hold every possible screen, so a DQN uses a neural network Q(s, a; θ) that takes the state (for example, a stack of recent game frames read by convolution layers) and outputs one Q-value per action. It is trained to reduce the squared error (y − Q(s, a; θ))², where y = r + γ max_a′ Q(s′, a′; θ⁻). Two ideas keep training stable:

  • Experience replay: transitions (s, a, r, s′) are stored in a replay memory and random minibatches are sampled from it, which breaks the correlation between consecutive steps and reuses past experience.
  • Target network: y is computed with a separate copy of the weights, θ⁻, which is refreshed from θ only at fixed intervals.

4. Exploration. With ε-greedy selection the agent takes a random action with probability ε and the best-known action otherwise; ε is lowered gradually as learning improves.

5. Other methods. Policy-gradient methods learn the policy π(a | s) directly, and actor–critic methods combine a policy network (the actor) with a value network (the critic).

Applications include playing video games from raw pixels, the board game Go, robot control and recommendation systems.

In conclusion, deep RL joins the trial-and-error learning of RL with the feature learning of deep networks, and replay memory and a target network make that combination stable.

5 Explain the architecture, training and main variants of an autoencoder. Count the parameters of a dense 784–128–32–128–784 autoencoder and compute a reconstruction error. 10 marks
Model answer

An autoencoder is a neural network trained to reproduce its input at its output. Because the target is the input itself, it learns without labels, and the useful part is the compact code it learns on the way.

1. Architecture.

  • Encoder f: maps the input x to a code h = f(x).
  • Code (bottleneck): the smallest layer, holding a compressed representation.
  • Decoder g: maps the code back to a reconstruction x̂ = g(h).
Dense autoencoder 784–128–32–128–784The input x of 784 values passes through the encoder (Dense 128, then the Dense 32 code h) and the decoder (Dense 128, then Dense 784 with sigmoid) to give the reconstruction x̂, which the reconstruction loss compares with the target, the input x itself.Encoder fDecoder gInput x:784 valuesDense 128, reluCode h: Dense 32Dense 128, relux̂: Dense784, sigmoidReconstructionlossTarget: input x
Dense autoencoder 784–128–32–128–784

2. Training. The network minimises a reconstruction loss L(x, x̂), usually the mean squared error, or binary cross-entropy when inputs are scaled to [0, 1], with backpropagation and gradient descent. For four pixels with x = (1, 0, 1, 0) and x̂ = (0.9, 0.2, 0.8, 0.1), the squared errors are 0.01, 0.04, 0.04 and 0.01, so MSE = 0.10/4 = 0.025.

3. Parameters. For 28×28 images flattened to 784 values, each Dense layer has inputs × units + units parameters:

Layer       Calculation       Params
Dense 128   784×128 + 128    100,480
Dense 32    128×32 + 32        4,128
Dense 128   32×128 + 128       4,224
Dense 784   128×784 + 784    101,136
Total                        209,968

The code keeps 32 values instead of 784, a compression of 24.5 times. In Keras the input is also the target:

import keras
from keras import layers

model = keras.Sequential([
  keras.Input(shape=(784,)),
  layers.Dense(128, activation="relu"),
  layers.Dense(32, activation="relu"),
  layers.Dense(128, activation="relu"),
  layers.Dense(784, activation="sigmoid"),
])
model.compile(optimizer="adam",
              loss="mse")
model.fit(x_train, x_train, epochs=10)

4. Variants.

  • Undercomplete: the code is smaller than the input, forcing the network to keep only the most important features. A linear autoencoder trained with MSE learns the same subspace as PCA.
  • Sparse: a penalty such as L1 on the code keeps most code units near zero.
  • Denoising: the input is corrupted with noise and the network learns to rebuild the clean version.
  • Contractive: a penalty on the encoder's Jacobian makes the code insensitive to small input changes.
  • Variational (VAE): the encoder outputs a mean and variance, the code is sampled from that distribution and a KL-divergence term is added to the loss, so decoding random codes generates new data.

Sparse, denoising and contractive training matter most when the code is not smaller than the input, because such a network could otherwise just copy its input.

5. Applications: dimensionality reduction, image denoising, anomaly detection (a large reconstruction error marks an unusual input), pretraining and generating new samples.

In conclusion, an autoencoder learns a compact code by squeezing data through a bottleneck and rebuilding it, and its variants add sparsity, robustness or the ability to generate.

6 Explain the restricted Boltzmann machine (RBM): its energy function, conditional probabilities and training by contrastive divergence. How are RBMs stacked to form a deep belief network? 10 marks
Model answer

A Boltzmann machine is an energy-based generative model of stochastic binary units in which low-energy joint states are the most probable. A general Boltzmann machine may link every unit to every other, which makes learning very slow; the restricted Boltzmann machine (RBM) removes the links inside each layer.

1. Structure. Every unit of the visible layer v (the data) is joined to every unit of the hidden layer h (learned features) by a symmetric weight W_ij, with no links inside either layer, so the graph is bipartite.

2. Energy. With visible biases a_i and hidden biases b_j:

E(v, h) = −Σ_i a_i v_i − Σ_j b_j h_j − Σ_i Σ_j v_i W_ij h_j

P(v, h) = e^(−E(v, h)) / Z, where Z sums e^(−E) over all states.

3. Conditionals. The units of one layer are independent given the other layer, so a whole layer is sampled in one step:

P(h_j = 1 | v) = σ(b_j + Σ_i v_i W_ij)

P(v_i = 1 | h) = σ(a_i + Σ_j W_ij h_j), with σ(x) = 1/(1 + e^(−x)).

4. Contrastive divergence (CD-1). The exact gradient ⟨v_i h_j⟩data − ⟨v_i h_j⟩model needs the intractable Z, so CD-1 replaces the model term with one step of Gibbs sampling:

  • Positive phase: clamp a training vector v⁰, compute P(h | v⁰) and sample h⁰.
  • Negative phase: reconstruct v¹ from h⁰, then compute P(h | v¹).
  • Update: ΔW_ij = η (v_i⁰ P(h_j = 1 | v⁰) − v_i¹ P(h_j = 1 | v¹)), and likewise for the biases.

Worked example: hidden unit h_1 has weights (0.5, −0.3, 0.2) from three visible units, bias b_1 = −0.1, and η = 0.1.

  • v⁰ = (1, 0, 1): input = 0.5 + 0.2 − 0.1 = 0.6, so P(h_1 = 1 | v⁰) = σ(0.6) = 0.6457.
  • Sampled reconstruction v¹ = (1, 1, 0): input = 0.5 − 0.3 − 0.1 = 0.1, so P(h_1 = 1 | v¹) = σ(0.1) = 0.5250.
  • ΔW_11 = 0.1 × (1 × 0.6457 − 1 × 0.5250) = 0.0121, so W_11 becomes 0.5121.

5. Deep belief network (DBN). It stacks RBMs trained greedily, one layer at a time, without labels:

Deep belief network built by stacking RBMsA deep belief network with the visible layer v (data) at the bottom and hidden layers h1, h2 and h3 above it, built from RBM 1, RBM 2 and RBM 3 trained one layer at a time. Only h2 and h3 stay joined by an undirected link; directed generative links point from h2 to h1 and from h1 to v, and a softmax output layer joined to h3 is used for fine-tuning.Hidden layer h3Softmaxoutput layerHidden layer h2Hidden layer h1Visible layerv (data)RBM 3:undirectedRBM 2:directedRBM 1:directedfine-tuning
Deep belief network built by stacking RBMs
  • RBM 1 is trained on the data v and gives hidden layer h1.
  • The activations of h1 train RBM 2, giving h2; RBM 3 gives h3 the same way.
  • In the finished DBN only the last two layers (h2, h3) stay undirected; the rest become directed generative links pointing back towards v.
  • For classification, a softmax output layer is added and all weights are fine-tuned with backpropagation.

In conclusion, the bipartite restriction makes CD training practical, and stacked RBMs form a DBN.

Public sources that settled doubtful points

Only the points the second AI pass doubted were looked up. These are the pages that confirmed or contradicted them; nothing here is copied from them.

41 pages

Further reading

Titles only, for your own study. Nothing on this page is copied from them. The units follow the official JNTUK R23 CSE syllabus (PDF) ↗.

  • Deep Learning · Ian Goodfellow, Yoshua Bengio and Aaron Courville
  • Deep Learning with Python · François Chollet
  • Deep Learning Illustrated: A Visual, Interactive Guide to Artificial Intelligence · Jon Krohn, Grant Beyleveld and Aglaé Bassens
  • Deep Learning from Scratch · Seth Weidman
  • Artificial Neural Networks · B. Yegnanarayana
  • Matrix Computations · Gene H. Golub and Charles F. Van Loan
  • Neural Networks: A Classroom Approach · Satish Kumar