Artificial Intelligence & Applications — Comprehensive Revision Notes


Topic 1: Data Exploration and Visualisation

Why Data Visualisation?

Summary statistics alone can be misleading — datasets with identical summary statistics (mean, standard deviation, correlation) can have completely different distributions. This was demonstrated by Anscombe’s Quartet (1973) and the Datasaurus Dozen.

Key principle: Always produce both calculations and graphs. Each contributes to understanding.

Purposes of Visualisation

Data visualisation is a critical tool in AI for identifying summaries, structure, relationships, differences, and abnormalities in data. It communicates complex information effectively.

Chart Types by Purpose

PurposeChart Types
RelationshipScatter plots, bubble charts
CompositionPie charts, stacked bar charts
ConnectionNetwork graphs
LocationMaps, geographic plots
ComparisonBar charts, grouped bar charts

Grammar of Graphics

The grammar of graphics is a systematic framework for building plots from components. Learning the grammar helps you think about new graphics beyond pre-existing templates.

Core components:

ComponentRole
DataThe dataset being visualised
AestheticsMapping variables to visual properties (x, y, colour, shape, size)
GeometriesThe visual marks (points, lines, bars)
FacetsSubplots for subsets of data
StatisticsStatistical transformations (smoothing, binning)
CoordinatesThe coordinate system (Cartesian, polar)
ThemeNon-data visual styling

Data Preparation (Data Wrangling)

Data quality issues to address:

  • Missing values — remove or impute
  • Duplicate records — merge
  • Invalid values — generate best estimate
  • Noise — filter or smooth
  • Outliers — detect and handle

Feature engineering:

  • Feature selection — remove highly correlated features, features with many missing values, irrelevant features (IDs, row numbers)
  • Combining features — create new informative features
  • Feature transformation — mapping values to a new representation to make analysis easier (e.g., scaling, normalisation)

Topic 2: Supervised Learning

What is Machine Learning?

Machine learning is a set of methods that can automatically detect patterns in data. These patterns are then used to predict future data or perform decision-making under uncertainty.

The Learning Problem

We have a set of training data:

We use this data and an ML method to estimate a function such that .

The relationship is modelled as:

where is an unknown function and is a random error (noise) term.

Terminology:

TermAlso called
Input Feature, attribute, predictor, independent variable
Output Response, dependent variable, label, ground truth

Regression vs Classification

RegressionClassification
Output typeContinuous (quantitative)Categorical (qualitative)
ExamplePredicting house priceSpam or not spam?

Linear Regression

The model:

  • = constant (y-intercept)
  • = coefficient / slope

Least Squares Error — the “best fit” minimises the sum of squared differences between actual and predicted values:

This is minimised using gradient descent.

Strengths: Simple, interpretable, computationally efficient, works well for linearly separable data.

Limitations: Assumes linearity, sensitive to outliers, struggles with multicollinearity, poor with complex non-linear data.

Decision Trees

A decision tree partitions data recursively based on attribute values:

  1. Determine the best attribute to select as root (using a goodness measure)
  2. Partition examples into subsets according to values of that attribute
  3. Construct the tree recursively for each subset
  4. Exit when all examples belong to one class

Attribute Selection — Information Gain:

Entropy measures impurity:

where is the proportion of class in set .

Entropy after splitting on attribute :

Information Gain:

The attribute with the highest information gain is chosen as the split.

Example (Play Tennis):

AttributeEntropy after splitInformation Gain
Outlook0.6930.247 (highest)
Temperature0.9110.029
Humidity0.7880.152
Windy0.8920.048

So Outlook is chosen as the root node.

Strengths: Easy to visualise and interpret, handles non-linear relationships, no need for data normalisation, handles categorical and continuous data.

Limitations: Prone to overfitting (without pruning), sensitive to small data changes.

Random Forest (Ensemble Classification)

Random Forest combines multiple decision trees to reduce overfitting:

  1. Bootstrapping — train each tree on a random subset of data with replacement
  2. Feature subsampling — use a random subset of features at each split
  3. Tree building — grow individual trees independently
  4. Aggregation — combine results using majority vote (classification) or averaging (regression)

Strengths: Reduces overfitting, handles high-dimensional data.

Limitations: Less interpretable, computationally intensive, requires hyperparameter tuning.

K-Nearest Neighbours (KNN)

A lazy learning approach — no model is built; the entire dataset is retained.

Algorithm:

  1. User inputs (number of neighbours)
  2. For each unlabelled instance, calculate the distance to all training instances
  3. Find the nearest neighbours
  4. Classification: majority vote among neighbours
  5. Regression: average of the target values:

Distance metrics:

  • Euclidean:
  • Manhattan:

Strengths: Simple, no assumptions about distribution, effective for non-linear problems.

Limitations: Computationally expensive at prediction time, performance depends on choice of and distance metric, sensitive to irrelevant/noisy features.


Topic 3: Unsupervised Learning

Clustering

Clustering is a type of unsupervised learning that groups similar objects together. The training data contains no output labels.

Goals: data reduction, outlier detection, missing value imputation, pattern discovery.

Key principle: maximise within-cluster similarity, minimise between-cluster similarity.

Similarity measures (same as KNN):

  • Euclidean distance
  • Manhattan distance

Cluster Quality Measures

  • Cluster centre — for numeric data, the centre of mass (mean); for nominal data, the mode
  • Within-cluster variation (wc) — how compact/tight clusters are
  • Between-cluster variation (bc) — distances between different clusters

K-Means Algorithm

  1. Define the number of clusters
  2. Choose data objects randomly as initial centroids
  3. Assign each data object to its nearest centroid
  4. Recalculate the centroid of each cluster as the mean of its members
  5. Repeat steps 3–4 until cluster membership no longer changes

Finding optimal — Elbow Method:

Plot within-cluster sum of squares (WCSS) against . The “elbow” point where adding more clusters no longer significantly reduces WCSS is the optimal .

Strengths: Simple, efficient.

Weaknesses: Must specify in advance, sensitive to initialisation, sensitive to noise, struggles with non-globular cluster shapes.

Agglomerative (Hierarchical) Clustering

A bottom-up approach — no need to specify beforehand.

Algorithm:

  1. Treat all data objects as individual clusters; build an dissimilarity matrix
  2. While number of clusters > 1:
    • Find the pair with minimum distance
    • Merge them into a bigger cluster
    • Update the distance matrix
  3. Produces a dendrogram

Measuring distance between clusters:

MethodDescription
Single linkDistance between the two closest points
Complete linkDistance between the two furthest points
CentroidDistance between cluster centroids
Group averageAverage of all pairwise distances

Strengths: Deterministic, multiple clustering versions, no need to specify , can create arbitrary cluster shapes.

Weaknesses: Does not scale well to large datasets.


Topic 4: Deep Learning and Fully Connected Networks (FCNs)

Machine Learning vs Deep Learning

Traditional MLDeep Learning
Raw data → hand-crafted features → classifierRaw data → learned representations → classifier
Requires domain expertise for feature extractionFeatures learned automatically from data
Shallow representationsMultiple layers of increasingly meaningful representations

Biological Inspiration

Neural networks are inspired by the human visual cortex (V1 → V2 → V3 etc.), which performs progressively more complex processing. The basic element in an artificial neural network is the artificial neuron (node/unit).

Fully Connected Network (FCN) Architecture

A fully connected network has:

  • Input vector:
  • Hidden values:
  • Output value:

The forward computation:

Without an activation function, this is purely linear. The activation function introduces non-linearity.

One-Hot Encoding (OHE)

For multi-class classification, class labels are converted to binary vectors:

LabelOHE Vector
0 (zero)
3 (three)
6 (six)

Key Hyperparameters

HyperparameterDescription
EpochsNumber of times the entire training set passes through the network
Batch sizeNumber of samples per gradient update
Learning rateScalar that controls the step size of weight updates
Number of hidden unitsWidth of each hidden layer

Topic 5: Activation Functions in FCNs

Why Activation Functions?

Without non-linearity, no matter how many layers, the entire network collapses to a single linear function. Activation functions:

  • Allow backpropagation (derivative is related to input)
  • Enable stacking of multiple layers (non-linear combination)

Activation Functions Summary

FunctionFormulaRangeProsCons
LinearSimpleCannot learn non-linear patterns
SigmoidSmooth, probabilistic outputVanishing gradient for
TanhZero-centred, steeper than sigmoidVanishing gradient for
ReLUFast, avoids vanishing gradientDying ReLU (neurons output 0 permanently)
Leaky ReLUFixes dying ReLUSmall negative slope is a hyperparameter
Softmax, sums to 1Outputs probabilitiesUsed only in output layer for multi-class

When to Use Which

  • Hidden layers: ReLU (default), Leaky ReLU if dying neurons are an issue
  • Binary classification output: Sigmoid
  • Multi-class classification output: Softmax
  • Regression output: Linear (no activation)

Topic 6: Loss Functions, Forward and Backpropagation

Loss Functions

The loss function measures how badly the AI system performed:

The total loss over the training set:

Binary Cross-Entropy (BCE)

For binary classification (output via sigmoid):

Categorical Cross-Entropy (CCE)

For multi-class classification (output via softmax):

Mean Squared Error (MSE)

For regression:

Summary: Loss + Output Activation Pairing

TaskOutput ActivationLoss Function
Binary classificationSigmoidBinary cross-entropy
Multi-class classificationSoftmaxCategorical cross-entropy
RegressionLinear (none)Mean squared error

Gradient Descent and Backpropagation

Gradient — indicates the direction and rate of steepest ascent of the error function. To minimise the loss, we move in the opposite direction of the gradient.

Backpropagation computes the gradient of the loss with respect to each weight using the chain rule.

Weight update rule:

where is the learning rate.

SGD vs Mini-Batch SGD

SGDMini-Batch SGD
Samples per update1 random sampleA batch of samples
Gradient estimateNoisySmoother
SpeedFast per stepMore stable convergence

Training loop: Input → Predict → Error → Backprop → Update → Repeat

Dropout (Regularisation)

Dropout randomly drops (zeroes out) some neuron outputs during training with probability . This prevents overfitting by making the model less sensitive to noise and more generic.

model.add(Dropout(0.3))  # 30% dropout probability

Optimisers

OptimiserDescription
SGDBasic stochastic gradient descent
RMSpropAdapts learning rate per parameter
AdamCombines momentum and adaptive learning rates; often the default choice

Topic 7: Evaluating ML/DL Models

Model Validation Strategies

Goal: avoid overfitting and find the best hyperparameter combination.

Holdout

Split data into three sets:

SetPurposeTypical Split
TrainingLearn model parameters60%
ValidationTune hyperparameters, detect overfitting20%
TestFinal evaluation on unseen data20%

K-Fold Cross-Validation

  1. Split dataset into subsets (folds)
  2. For each fold: train on folds, validate on the remaining fold
  3. Average results across all runs

Overfitting vs Underfitting

UnderfittingGood FitOverfitting
Training errorHighLowVery low
Validation errorHighLowHigh
Model complexityToo simpleJust rightToo complex

Solutions to overfitting:

  • Early stopping — stop training when validation loss starts increasing
  • Regularisation (L2): adds penalty to loss
  • Dropout
  • More training data

Hyperparameter Optimisation

MethodDescriptionProsCons
Grid SearchExhaustive search over all combinationsSystematic, thoroughExpensive for large spaces
Random SearchRandom sampling from distributionsMore efficient in high dimensionsNo guarantee of finding best

Classification Metrics

Confusion Matrix:

Predicted PositivePredicted Negative
Actual PositiveTrue Positive (TP)False Negative (FN)
Actual NegativeFalse Positive (FP)True Negative (TN)

Key metrics:

Why accuracy alone is not enough: In imbalanced datasets (e.g., 91 benign vs 9 malignant tumours), a model that always predicts “benign” achieves 91% accuracy but is useless. Use precision, recall, and F1-score instead.

AUC-ROC: Area Under the Receiver Operating Characteristic Curve — measures the model’s ability to distinguish between classes across all thresholds.


Topic 8: Convolutional Neural Networks (CNNs)

Why CNNs?

FCNs treat input as flat vectors, losing spatial locality — the relationship between neighbouring pixels. CNNs are designed to preserve and exploit spatial structure.

CNN Architecture Components

1. Convolutional Layer

A kernel (filter) slides over the image, performing element-wise multiplication and summation to produce a feature map.

Key parameters:

  • Kernel size — e.g., ,
  • Stride — step size of the filter movement
  • Padding:
    • valid — no padding, output smaller than input
    • same — zero-padding, output same size as input

Output feature map size:

Important: The filter must have the same number of channels as the input (e.g., a filter on an RGB image is actually ).

Number of learnable parameters in a conv layer:

2. Pooling Layer

Reduces spatial dimensions while retaining key information. Max Pooling takes the maximum value in each pooling window.

MaxPooling2D(pool_size=(2, 2), strides=(2, 2))

3. Fully Connected (Classification) Layer

After feature extraction through conv and pooling layers, the feature maps are flattened into a 1D vector and fed to dense layers for classification.

Example: Parameter Calculation

For a 32×32 input image (no padding, stride=1):

LayerConfigOutput ShapeParameters
Conv13×3, 16 filters30×30×16
Conv23×3, 32 filters28×28×32
FC10 outputs10
Total255,632

Pooling layers help reduce the number of parameters in subsequent FC layers.

LeNet Architecture

A classic CNN for handwritten digit recognition (MNIST):

Input (28×28×1)
→ Conv2D(20, kernel=5, valid) → ReLU → MaxPool(2×2)
→ Conv2D(50, kernel=5, valid) → ReLU → MaxPool(2×2)
→ Flatten → Dense(500) → ReLU
→ Dense(10) → Softmax

Topic 9: CNNs Part II — Improving Generalisability

Techniques for Better CNNs

Spatial Dropout

Like standard dropout but drops entire feature maps in convolutional layers rather than individual neurons.

Batch Normalisation

Normalises the output of each layer within a mini-batch to stabilise training.

Why it helps:

  • Prevents vanishing/exploding gradients
  • Reduces sensitivity to weight initialisation
  • Acts as a slight regulariser

Formula:

  1. Normalise within mini-batch:

where and are the batch mean and variance.

  1. Scale and shift (learnable parameters):

where (scale) and (shift) are learned during training.

Placement: Typically after the convolutional/dense layer and before the activation function:

Conv2D → BatchNormalization → ReLU

Topic 10: Transfer Learning and Pre-trained CNNs

What is a Pre-trained Model?

A saved network previously trained on a large dataset (e.g., ImageNet with 1.4M images, 1000 classes). Useful when you have a small dataset — improves accuracy and saves training time.

Examples: VGG-16, GoogLeNet/Inception, ResNet, MobileNet, BERT, GPT.

Using a Pre-trained Model

Feature Extraction (Shallow Mode)

  1. Load pre-trained convolutional base without the top classifier
  2. Freeze all convolutional layers (trainable = False)
  3. Add new custom dense layers on top for your specific task
  4. Train only the new dense layers

Why not reuse the classifier? The original classifier was trained for 1000 ImageNet classes — not your task.

Fine-Tuning (Deep Mode)

Two approaches:

  1. Full fine-tuning: Set entire model as trainable (conv_base.trainable = True), train end-to-end with a low learning rate
  2. Partial fine-tuning: Freeze early layers, only unfreeze later layers (e.g., from block5_conv1 onwards)

Rationale: Early layers learn generic features (edges, textures) transferable across tasks. Later layers learn task-specific features.


Topic 11: Handling Class Imbalance

The Problem

When one class vastly outnumbers another (e.g., 998 negatives vs 2 positives), classifiers become biased toward the majority class. A model predicting “always negative” achieves 99.8% accuracy but is useless.

The standard cross-entropy loss is dominated by the majority class gradients.

Algorithm-Level Solutions

Weighted Cross-Entropy

Assign higher weights to minority classes in the loss function:

Weighted BCE:

class_weights = {0: 1.0, 1: 5.0}  # higher weight for minority
model.fit(..., class_weight=class_weights)

Focal Loss

Reduces the influence of easy (majority) samples and focuses training on hard (minority) samples. Adds a modulating factor to cross-entropy.

Data-Level Solutions

TechniqueDescriptionRisk
Random oversamplingDuplicate minority samplesOverfitting
Random undersamplingRemove majority samplesLoss of information
Data augmentationApply transformations (rotation, flip, shift, zoom, shear)Requires careful tuning
SMOTESynthetically generate minority samples by interpolating between nearest neighboursOnly for structured/tabular data

SMOTE (Synthetic Minority Over-sampling Technique)

  1. Select a minority class instance
  2. Find its -nearest neighbours (from minority class)
  3. Create a synthetic sample by interpolating:

where is random.

Critical rule: Perform oversampling/augmentation only on training data, never on the test set.

Performance Metrics for Imbalanced Data

Use precision, recall, and F1-score rather than accuracy alone.


Topic 12: Autoencoders

The Curse of Dimensionality

As the number of features increases without increasing training samples, the feature space becomes sparse. Distance metrics lose meaning, and models overfit easily.

Solution: Dimensionality reduction.

What is an Autoencoder?

An unsupervised neural network that learns a compressed representation of input data and then reconstructs it.

Components:

ComponentRole
EncoderCompresses input into lower-dimensional latent space
Latent space (code)Compressed representation
DecoderReconstructs input from latent representation

Loss function (MSE):

Key idea: The network is trained to reproduce its own input (), forcing the latent space to capture essential features.

Types of Autoencoders

1. Vanilla Autoencoder

Fully connected layers. Input → Encoder (Dense) → Latent code → Decoder (Dense) → Reconstructed output.

2. Denoising Autoencoder

Input is a noisy version of the data; the network learns to reconstruct the clean version. This improves robustness.

3. Convolutional Autoencoder (CAE)

Uses Conv2D layers in the encoder and either UpSampling2D (fixed) or Conv2DTranspose (learnable) in the decoder.

Encoder: Conv2D + MaxPooling (downsample)
Decoder: Conv2D + UpSampling/Conv2DTranspose (upsample)

Applications

  • Denoising — remove noise/artefacts from images
  • Image colourisation — convert grayscale to colour
  • Dimensionality reduction — alternative to PCA
  • Anomaly detection — high reconstruction error = anomaly

Topic 13: Object Detection and Segmentation

Computer Vision Task Hierarchy

LevelTaskOutput
ClassificationWhat is in the image?Class label
Object DetectionWhere are the objects?Bounding boxes + labels
Semantic SegmentationPixel-wise classificationClass label per pixel
Instance SegmentationPixel-wise + distinguish instancesMask per object instance

R-CNN (Region-based CNN)

  1. Generate ~2000 region proposals using Selective Search
  2. Warp each region to fixed size
  3. Extract features using a CNN (e.g., AlexNet)
  4. Classify each region with an SVM
  5. Refine bounding boxes with regression

Cons: Very slow — requires ~2000 CNN forward passes per image.

Fast R-CNN

Key improvement: Run the CNN only once per image to produce a shared feature map.

  1. Generate region proposals with Selective Search
  2. Run entire image through CNN → feature map
  3. For each proposal, extract features via RoI (Region of Interest) Pooling
  4. Classify and refine bounding boxes in one unified network

Con: Still uses slow Selective Search for proposals.

Faster R-CNN

Replaces Selective Search with a Region Proposal Network (RPN) — a small CNN that generates proposals from the feature map itself.

Architecture:

  1. Backbone CNN → shared feature map
  2. RPN → generates proposals from the feature map
  3. RoI Pooling → extracts fixed-size features for each proposal
  4. Classification head → classifies and refines boxes

Everything is end-to-end trainable.

U-Net (Semantic Segmentation)

An encoder-decoder architecture with skip connections between corresponding encoder and decoder layers.

  • Encoder (downsampling path): extracts context using Conv + MaxPool
  • Decoder (upsampling path): restores spatial resolution
  • Skip connections: combine location information from the encoder with context from the decoder

Advantages: No dense layers (input can be any size), combines localisation and context.

Mask R-CNN (Instance Segmentation)

Extends Faster R-CNN by adding a mask branch that outputs a binary segmentation mask for each detected object, providing pixel-level segmentation alongside bounding boxes and class labels.


Topic 14: Natural Language Processing (NLP)

NLP vs LLMs

  • NLP — the broader field of techniques for analysing human language (includes statistical models like N-gram, TF-IDF, BoW)
  • LLMs — a specific type of deep learning model within NLP, trained on massive datasets (e.g., GPT, BERT)

Levels of Linguistic Analysis

  • Syntax — what is grammatically correct
  • Semantics — what is the meaning

Ambiguity Types

TypeDescriptionExample
LexicalWords with multiple meanings”bank” (financial vs river)
SemanticSentences with multiple meanings”I saw him with a telescope”
AnaphoricPronouns referring to earlier mentions”He told his dog to sit, and it did”

NLP Pipeline

  1. Sentence segmentation — split text into sentences
  2. Tokenisation — split sentences into words/tokens
  3. Stemming — crude chopping of word endings (e.g., “eating” → “eat”)
  4. Lemmatisation — proper reduction using vocabulary (e.g., “better” → “good”, “drove” → “drive”)
  5. Stop word removal — remove common words (“the”, “a”, “is”)
  6. POS tagging — assign part of speech (noun, verb, adjective, etc.)
  7. Named Entity Recognition — identify persons, locations, times

Bag of Words (BoW)

Represents a document as a vector of word frequencies. Ignores word order entirely.

Process:

  1. Build a vocabulary of known words
  2. For each document, count occurrences of each vocabulary word
  3. Resulting vector represents the document

TF-IDF (Term Frequency — Inverse Document Frequency)

Measures importance of a word to a document within a corpus.

Words that appear frequently in one document but rarely across the corpus get high TF-IDF scores.

Cosine Similarity

Measures similarity between two document vectors:

N-gram Language Models

Uses the probabilities of word sequences to predict the next word.

Markov assumption: the probability of a word depends only on the previous words:

MLE for conditional probabilities:

Types:

  • Unigram:
  • Bigram:
  • Trigram:

Limitations: Computationally expensive for large ; gives zero probability to unseen sequences (sparsity).


Topic 15: Regression and Text Classification with FCNs

Regression with Deep Learning

For regression tasks, the output is continuous.

Key differences from classification:

ClassificationRegression
Output activationSoftmax / SigmoidLinear (none)
Loss functionCross-entropyMSE
Output unitsNumber of classes1 (or number of target values)

Data Normalisation for Regression

When features have different scales, normalisation is essential:

Min-Max Scaling:

Z-Score (Standardisation):

Important: Compute normalisation statistics (, , min, max) on the training set only, then apply to test set.

Text Classification with FCNs

Approach (e.g., IMDB sentiment analysis):

  1. Load pre-processed text data (each review = list of word indices)
  2. One-hot encode the word sequences into fixed-size binary vectors (dimension = vocabulary size)
  3. Build an FCN with Dense layers and appropriate activation

Binary classification (IMDB):

Dense(16, relu) → Dense(16, relu) → Dense(1, sigmoid)
Loss: binary_{c}rossentropy

Multi-class classification (Reuters, 46 topics):

Dense(64, relu) → Dense(64, relu) → Dense(46, softmax)
Loss: categorical_crossentropy

Topic 16: Recurrent Neural Networks (RNNs)

Why RNNs?

FCNs treat input as flat vectors — they discard sequential information. Word order matters in NLP: “not bad” ≠ “bad”.

RNN Architecture

An RNN processes sequences one element at a time, maintaining a hidden state that acts as memory.

At each time step :

  • Input:
  • Hidden state:
  • Output:

The same weights (, , ) are shared across all time steps.

Backpropagation Through Time (BPTT)

The RNN is “unrolled” across time steps, and gradients are computed backwards through all steps. This is how RNNs learn temporal dependencies.

Padding Sequences

Since neural networks expect fixed-size inputs, sequences of different lengths are padded (typically with zeros) to the same length:

[1, 2, 3]    → [0, 1, 2, 3]
[4, 5]       → [0, 0, 4, 5]
[6, 7, 8, 9] → [6, 7, 8, 9]

Word Embeddings

Instead of sparse one-hot vectors, word embeddings map each word to a dense vector where similar words have similar representations.

Embedding layer:

Embedding(vocab_size, embedding_dim, input_length=max_len)
  • vocab_size — number of distinct words
  • embedding_dim — size of each embedding vector
  • input_length — length of input sequences

Word2Vec

A method for learning word embeddings from context:

  • CBOW (Continuous Bag of Words): predicts target word from context words
  • Skip-gram: predicts context words from target word

RNN for Text Classification (IMDB)

Embedding(10000, 300, input_length=200)
→ SimpleRNN(32)
→ Dense(1, sigmoid)

The final hidden state summarises the entire input sequence into a fixed-size vector for classification.

Stacking RNNs: Use return_sequences=True for intermediate RNN layers to pass full sequence to the next RNN layer.

RNN for Word Prediction

Embedding(vocab_size, embedding_dim, input_length=max_len)
→ SimpleRNN(hidden_units)
→ Dense(vocab_size, softmax)

Output: probability distribution over entire vocabulary for the next word.

LSTM (Long Short-Term Memory)

Standard RNNs suffer from the vanishing gradient problem — gradients decay exponentially over long sequences, making it hard to learn long-term dependencies.

LSTMs solve this with a memory cell and gates:

GateFunction
Forget gateDecides what to discard from memory
Input gateDecides what new information to store
Output gateDecides what to output from memory

Topic 17: Actionability in AI — Search Algorithms

Search Problem Definition

ComponentDescription
Initial stateStarting point
State spaceAll reachable states
ActionsOperations available at each state
Goal stateDesired endpoint
Goal testCheck if current state is the goal
Path costCost associated with a path

Search Algorithm Properties

PropertyDescription
CompletenessWill it find a solution if one exists?
OptimalityWill it find the best (lowest-cost) solution?
Time complexityHow long does it take?
Space complexityHow much memory does it need?

Breadth-First Search (BFS)

Explores all neighbours at the current depth before moving deeper. Uses a queue (FIFO).

PropertyBFS
CompleteYes
OptimalYes (if all actions have equal cost)
StrategyShallowest node first

Depth-First Search (DFS)

Explores as deep as possible along one branch before backtracking. Uses a stack (LIFO).

PropertyDFS
CompleteNo (can get stuck in infinite loops)
OptimalNo
StrategyDeepest node first

Uniform Cost Search (UCS)

Expands the node with the lowest cumulative path cost. Uses a priority queue.

PropertyUCS
CompleteYes
OptimalYes

Uses a heuristic function — an estimate of the distance from node to the goal.

Expands the node with the lowest heuristic value .

PropertyGreedy
CompleteNo
OptimalNo
StrategyClosest to goal (by heuristic)

Combines UCS and Greedy. Evaluation function:

where:

  • = backward cost (cumulative cost from start to )
  • = forward cost (heuristic estimate from to goal)

Always expands the node with the lowest .

PropertyA*
CompleteYes
OptimalYes (if is admissible — never overestimates)

Search Algorithms Comparison

AlgorithmCompleteOptimalUses Heuristic
BFSYesYes (equal costs)No
DFSNoNoNo
UCSYesYesNo
GreedyNoNoYes
A*YesYesYes

Topic 18: Uncertainty Quantification and Explainability (XAI)

Monte Carlo Dropout for Uncertainty

Deep learning models are typically “black boxes” — they give predictions but no confidence measure.

MC Dropout method:

  1. Train the model with dropout as usual
  2. At inference, keep dropout active (don’t disable it)
  3. Run multiple forward passes on the same input → different predictions each time
  4. Average the predictions → final output
  5. Standard deviation of the predictions → uncertainty estimate

High std = model is uncertain; Low std = model is confident.

Explainable AI (XAI)

XAI aims to make AI decisions interpretable and understandable to humans.

Grad-CAM (Gradient-weighted Class Activation Mapping)

Provides visual explanations for CNN decisions by highlighting important image regions.

How it works:

  1. Take the feature maps from the last convolutional layer
  2. Compute the gradient of the predicted class with respect to each feature map
  3. Compute a weighted sum of feature maps using these gradients → produces a 2D heatmap
  4. Upsample the heatmap to match the original image size
  5. Overlay the heatmap on the original image

The result shows which regions contributed most to the prediction — warm colours indicate high importance.


End of revision notes.