Module 1 - Complete Notes
Module 1 - Complete Notes
DEFINITION:
• Self-supervised learning is a machine learning process where the model trains itself to
learn one part of the input from another part of the input. It is also known as
predictive or pretext learning.
• In this process, the unsupervised problem is transformed into a supervised problem by
auto-generating the labels. To make use of the huge quantity of unlabeled data, it is
crucial to set the right learning objectives to get supervision from the data itself.
• The process of the self-supervised learning method is to identify any hidden part of
the input from any unhidden part of the input.
What is the difference between self-supervised and unsupervised learning?
• Self-supervised learning and unsupervised learning methods can be considered
complementary learning techniques as both do not need labeled datasets.
Unsupervised learning can be considered as the superset of self-supervised learning as
it does not have any feedback loops. On the contrary, self-supervised learning has a
lot of supervisory signals that act as feedback in the training process.
• An easier way to put it is that the ‘unsupervised’ learning technique focuses a lot on
the model and not on the data whereas the ‘self-supervised learning’ technique works
the other way around. However, unsupervised learning methods are good at
clustering, and dimensionality reduction, while self-supervised learning is a pretext
method for regression and classification tasks.
Limitations of Supervised Learning
Supervised learning requires explicit "input-output" pairs (labels), which presents three major
hurdles:
• High Costs & Time: Manual labeling is labor-intensive. For instance, labeling one
hour of speech can take 10+ hours of human work.
• Need for Domain Expertise: Fields like medical imaging (e.g., Radiology on NIH)
or law require highly paid specialists to annotate data, making it prohibitively
expensive.
• Human Bias: Annotations are subjective. Different humans may label the same
image or sentiment differently, introducing noise that limits model accuracy.
Self-Supervised Learning Workflow
• Unlabeled Data Input: Massive volumes of raw data (images, text, audio, or IoT
sensor logs) are fed into the system without manual annotations.
• Pretext Task (Self-Supervision): The model creates its own "labels" by solving
artificial puzzles. Common tasks include:
Masking: Predicting hidden parts of a sentence or image.
Rotation: Predicting the angle an image has been rotated.
Contrastive Learning: Determining if two views belong to the same object.
• Representation Learning: Through these tasks, the model develops a deep "feature
extraction layer" that understands the data's underlying patterns, such as shapes,
textures, or grammar.
• Fine-Tuning: The pre-trained model is adapted for a specific "downstream task"
using a very small labeled dataset.
• Downstream Task: The final model is deployed for real-world applications like
medical image classification, object detection, or speech recognition.
key characteristics of SSL
• Uses Unlabeled Data: The model learns directly from raw data without needing
humans to label it.
• Dynamic Label Generation: The model generates training labels by understanding
the data structure itself.
• Mix of Learning Methods: SSL is a middle ground between supervised learning
(with labels) and unsupervised learning (without labels).
• Learns Useful Features: By learning from the data itself, the model can understand
important patterns and details which helps it perform better on new data.
• Wide Applications: It is widely used in areas like image recognition, natural
language processing and speech recognition, where labeled data can be expensive or
limited.
• Helps Transfer Learning: SSL makes it easier to adapt models to new tasks by using
the knowledge gained from pre-training on unlabeled data.
MODULE 1 : Pretext Tasks
Pretext tasks are recognized as the core driving mechanism behind self-supervised
and autonomous foundation models. They enable learning from the massive amounts of
unlabeled data available in the real world by generating their own supervision signals, a
process often referred to as synthetic supervision. Instead of relying on costly human
annotations, the model learns by solving carefully designed artificial tasks derived directly
from the raw data.
1. Definition and Core Concept
A Pretext Task (also called a proxy or auxiliary task) is an artificial learning objective
constructed such that the ground-truth labels are automatically obtained from the data
itself. This means the model supervises its own learning.
Key Characteristics
(a) Internal Learning Signal (Synthetic Supervision)
Unlike supervised learning, where labels are externally provided, pretext tasks create labels
internally.
For example:
In NLP, a word in a sentence is masked, and the model is trained to predict the
missing word using surrounding context.
In Computer Vision, an image may be rotated, and the model predicts the rotation
angle.
Here, the input data itself provides the target, eliminating the need for manual labeling.
(b) No Human Annotation Required
Because labels are generated automatically:
The approach scales efficiently to millions or billions of samples
Training cost and time are drastically reduced
Learning becomes feasible for large-scale foundation models
This property makes pretext tasks ideal for learning from raw text, images, videos, and
sensor data.
2. Representation Learning & Downstream:
The goal of a pretext task is not to solve the artificial task itself. Instead, it serves as a tool
to force the model to learn useful and transferable internal representations of data.
(a) Representation Learning - Feature Discovery
• Definition: The process of automatically transforming raw, high-dimensional data
(pixels, audio waves, sensor logs) into a dense mathematical format (embeddings) that
captures the "essence" of the information. Through these tasks, the model develops a
deep "feature extraction layer" that understands the data's underlying patterns, such as
shapes, textures, or grammar.
To perform well on the pretext task, the model must capture:
Visual structure (edges, shapes, depth, lighting)
Linguistic structure (syntax, semantics, grammar)
Temporal dependencies (motion, sequence flow)
These learned features form a rich, general-purpose embedding space that captures the true
structure of the data.
(b) Downstream - “Discard and Transfer” Strategy
Once pre-training is complete:
1. The task-specific head (used only for solving the pretext task) is discarded
2. The feature extractor / backbone network is retained
3. These learned representations are transferred to downstream tasks, such as:
o Object detection
o Medical image diagnosis
o Speech recognition
o Sentiment analysis
This approach significantly improves performance, especially when labeled data for the
downstream task is limited.
Figure 6: Colourisation
In this pretext task, we predict the colours of a grey image. It can be formulated for any
image, we just remove the colour and feed this greyscale image to the network to predict its
colour. This task is useful in some respects like for colourising the old greyscale films. we
can apply this pretext task). The intuition behind this task is that the network needs to
understand some meaningful information like that the trees are green, the sky is blue and so
on.
3.3 Reconstruction-Based Pretext Tasks
Learn global and local context by reconstructing data
This means:
The model is shown incomplete or damaged data
It must rebuild the original input
To do this, it must understand what should be there
Masked Language Models (MLMs) are a type of machine learning model designed to
predict missing or "masked" words in a sentence. These models are trained on large
datasets of text where certain words are intentionally hidden during training. The goal
of the model is to guess the hidden word based on the surrounding context. This
approach helps the model learn the relationships between words and develop a deeper
understanding of language structure.
How Do Masked Language Models Work?
The process of training a masked language model involves two main steps:
1. Masking Words
During training, the model is presented with sentences where some words are
randomly replaced with a special token, such as "[MASK]." In the below example,
two words have been replaced with mask tokens while another word replaced by
different word token.
3. 3.2 Context-Aware
What Does “Context-Aware” Mean in SSL?
A self-supervised model is context-aware if it:
Learns representations by predicting missing, future, or related parts of data
Preserves global and local dependencies
Understands semantic consistency beyond simple similarity
Core idea:
“Use context as supervision instead of labels.”
Fill in the blanks
We hide a part of an image and predict the hidden part from the remaining surrounding part
of the image. This works because the network will learn the implicit structure of the data like
to represent that cars run on roads, buildings are composed of windows & doors and so on.
The objective of temporal pretext tasks is to enable the model to learn motion patterns
and temporal dependencies present in video data.
Instead of relying on static appearance, the model is forced to understand how visual content
evolves over time.
These tasks exploit the natural ordering of video frames as a free source of supervision.
Examples:
Temporal Order Prediction (Shuffle & Learn)
Future Frame Prediction
Odd-One-Out in Video Clips
3.4.1 Future Frame Prediction
Videos are composed of sequences of frames and this notion is the idea behind self-
supervision, which can be leveraged for some pretext tasks like predicting the order of
frames, fill in the blanks and object tracking.
3.4.2 Shuffle & Learn
Figure 7: Interpolation
Given a bunch of frames, we extract three frames and if they are extracted in the right order
we label it as positive, else if they are shuffled, label it as negative. This now becomes a
binary classification problem to predict if the frames are in the right order or not. So, given a
start and end point, we check if the middle is a valid interpolation of the two.
As shown in the example above, two images belonging to the same class lie close to each
other in the embedding space (“d+”), and those belonging to different classes lie at a greater
distance from each other (“d-”). Thus, a contrastive learning model (denotes by “theta” in the
example above) tries to minimize the distance “d+” and maximize the distance “d-.”
Two methods
1. Instance Discrimination Method
2. Image Subsampling/Patching Method
Instance Discrimination Method
In this class of Contrastive Learning, the entirety of images are made to undergo
transformations and used as positive samples to an anchor image. For example, if we select
an image of a dog as the anchor, we can mirror the image or convert it to grayscale to use
as the positive sample. The negative sample can be any other image in the dataset.
The image below shows the basic framework of the instance discrimination-based
contrastive learning technique. The distance function can be anything, from Euclidean
distance to cosine distances in the embedding space.
Some image augmentation methods popularly used for Instance Discrimination-based
Contrastive Learning is listed as follows:
1. Colour Jittering: Here, the brightness, contrast, and saturation of an RGB image are
changed randomly. This technique is helpful to ensure a model is not memorizing a
given object by the scene's colors. While output image colors can appear odd to
human interpretation, such augmentations help a model consider the edges and
shape of objects rather than only the colors.
2. Image Rotation: An image is rotated randomly within 0-90 degrees. Since rotating
an image doesn’t change the core information contained in it (i.e., a dog in an image
will still be a dog), models are trained to be rotation invariant for robust prediction.
3. Image Flipping: The image is flipped (mirrored) about its center, either vertically or
horizontally. This is an extension of the concept of image rotation-based
augmentation.
4. Image Noising: Random noise is added to the images pixel-wise. This technique
allows the model to learn how to separate the signal from the noise in the image and
makes it more robust to changes in the image during test time. For example,
randomly changing some pixels in the image to white or black is known as salt-and-
pepper noise (an example is shown below).
Here, “s_i” and “s_j” are the two samples with corresponding labels “y_i” and “y_j” that need
to be compared, “theta” is the embedding network, and “epsilon” is a hyperparameter,
defining the lower bound distance between samples of different classes.
The labels for the samples are generated by whether the samples belong to the same
distribution. For example, if the two samples are cropped versions of the same image or the
augmented versions of the same sample, the labels will be the same.
2. Triplet Loss
The triplet loss is a lot similar to the contrastive loss, both of which try to minimize the
distance between similar distributions and maximize the distance between unlike
distributions. The primary difference in the triplet loss is that a positive and a negative
sample are simultaneously taken as input with the anchor sample to compute the loss.
Mathematically it is represented as follows:
Given three samples:
Anchor
Positive (same class as anchor)
Negative (different class)
Let:
be the embedding function
= margin
For example, raccoons and ringtails look a lot similar (see the image below). Both have
striped, bushy tails and similar body fur colors. When sampling the negative samples against
raccoons, choosing ringtails will enable the model to differentiate between classes more
effectively, than say, when choosing an elephant as the negative sample.
3. N-pair Loss
The N-pair loss is an extension of the triplet loss function. Instead of sampling a single
negative sample, an “N” number of negative samples are sampled along with one anchor
and one positive sample. The mathematical representation for this loss is as follows:
N-Pair Loss Formula
Given:
One anchor sample
One positive sample (same class as anchor)
negative samples
The N-Pair Loss is:
4. InfoNCE
InfoNCE, where NCE stands for Noise-Contrastive Estimation, is another type of contrastive
loss function.
If “S = {s_1, s_2, …, s_N}” denotes the set of “N” random samples containing one positive
sample and “N-1” negative samples, the loss function can be mathematically represented as
follows:
Given:
An anchor
A positive sample
negative samples
Let:
be the embedding
= similarity (usually cosine similarity)
= temperature
Symbo Meanin
l g
sim(· Cosine
) similarity
Temperatur
e
Total number of
embeddings
Excludes self-
comparison
MODULE 1: SIMCLR
SimCLR: A Simple Framework for Contrastive Learning of Visual
Representations
SimCLR, developed by researchers at Google Brain, is a self-supervised learning framework
that learns visual representations without requiring labeled data. It is built upon contrastive
learning, where the model is trained to bring similar (positive) image pairs closer and push
dissimilar (negative) pairs apart in the feature space.
SimCLR a self-supervised learning framework that trains models to understand images
without labels by teaching them to recognize different "views" (augmented versions) of the
same image as similar, while treating views from different images as dissimilar, using a
contrastive loss function and large batch sizes for strong feature learning
Traditional deep learning relies heavily on labeled datasets, which are expensive and time-
consuming to create. Self-supervised learning, and specifically SimCLR, tackles this by:
Eliminating the need for manual labels: Models learn from raw, unlabeled data.
Learning robust visual features: These features can be used for a variety of
downstream tasks.
Enabling strong performance with simple linear classifiers: After SSL
pretraining, even a basic classifier on top of the learned features can achieve
competitive results.
Random Crop
By randomly cropping images, the contrastive prediction tasks are sampled that
include global to local view (B→A) or adjacent view (D→C) prediction.
Where:
is the ResNet encoder
are high-level feature representations
Key points:
The same encoder weights are used for both views
The encoder learns semantic features such as shapes, textures, and object
structure
These representations are still not directly optimized for contrastive loss
Purpose:
To extract meaningful visual features from augmented images.
Linear evaluation of models with varied depth and width
Unsupervised learning benefits more from bigger models than its supervised
counterpart.
1.3. Projection Head
The encoded features and are passed through a projection head, usually a small MLP
(Multi-Layer Perceptron).
Where:
is the projection head (e.g., Linear → ReLU → Linear)
are low-dimensional vectors in the contrastive feature space
Why projection head?
Contrastive loss performs better in projection space than representation space
The encoder output remains more general and transferable
The projection head absorbs task-specific constraints
Purpose:
To map representations into a space where similarity comparison is more effective.
Linear evaluation of representations with different projection heads g() and various
dimensions of z = g(h). h has 2048 dimensional
It is found that it is beneficial to define the contrastive loss on zi’s rather than hi’s.
Linear evaluation models (ResNet-50) trained with different batch size and epochs
Large batch size is beneficial, longer training time is also beneficial.
The contrastive prediction task is defined on pairs of augmented examples derived
from the minibatch, resulting in 2N data points.
Given a positive pair, the other 2(N-1) augmented examples within a minibatch
as negative examples.
The loss function for a positive pair of examples (i, j) is defined as:
where sim(,) is cosine similarity, τ is the temperature parameter.
The final loss is computed across all positive pairs, both (i, j) and (j, i), in a mini-
batch.
It is named as NT-Xent (the normalized temperature-scaled cross entropy loss).
Advantages
Label-efficient: Needs fewer or no labels for pretraining
Modular: Works with different architectures
Simple to implement: No complex pretext tasks or auxiliary networks
Scalable with larger batch sizes and stronger augmentations
Limitations
Requires very large batch sizes for many negative examples (128+ images)
Compute-intensive (especially with ResNet-50/101 backbones)
Contrastive loss may not capture higher-order semantics (like object relationships)
MoCo’s architecture:
MoCo’s main components are the query and the keys, encoder and momentum encoder,
feature queue, one hot target, and the contrastive loss. As shown in the following
figure, MoCo aims to find the matching similarity between extracted features from the query
encoder and the keys’ momentum encoder. The keys are a set of samples stored in a
dictionary.
Figure 1: MoCo architecture with query and ky dictionary [1].
Dictionary as a Queue
Momentum contrast uses a dictionary queue encoded with keys, The queue is updated by
adding the representation of the current image to the queue and removing the oldest
representation. The dictionary acts as a "memory bank" that stores a history of feature
representations. The queue is updated using a momentum-based update rule, which allows the
model to maintain a smooth and stable representation of the feature space.
During training, the images are split into two groups: a query group and a key group. The
query group is used to compute a query feature representation, while the key group is used to
compute a set of key feature representations. The query feature representation is then
compared to the key feature representations stored in the dictionary using a contrastive loss
function.
Momentum Update
Momentum update is a key component in Momentum Contrastive learning, a technique
commonly used in self-supervised learning tasks such as image or video representation
learning. It helps improve the stability and convergence speed of the learning process by
introducing a momentum term during the update of the model's parameters.
In MoCo, the momentum update is used to update the model's parameters based on the
current gradient and the momentum term. The momentum update can be visualized as
follows:
Initialize the model's parameters and momentum parameters.
At each training iteration:
a). Compute the gradients of the loss function with respect to the
parameters using the current mini-batch of data.
b).Update the momentum parameters using the momentum update equation:
where Vt is the velocity term at time step t, α is the momentum
coefficient, and gt is the gradient at time step t.
Update the model's parameters using the momentum parameters:
represents the updated parameters at time step t+1.
The momentum update equation calculates the velocity term by combining the previous
velocity ø {t-1} and the current gradient gt. The momentum coefficient α determines the
contribution of the previous velocity compared to the current gradient. A higher α value gives
more weight to the previous velocity, resulting in a smoother and more stable update
trajectory.
The momentum update allows the model to accumulate information from previous gradients
and helps the optimization process by maintaining a consistent direction of updates. This can
help the model escape shallow local minima and converge faster to better representations.
Keep in mind that while the momentum update is an essential component of MoCo, the
specific implementation details and hyperparameters may vary depending on the exact
architecture and training setup.
MODULE 1 : What is Meta Learning?
Meta-learning is learning to learn algorithms, which aim to create AI systems that can adapt
to new tasks and improve their performance over time, without the need for extensive
retraining.
Meta-learning algorithms typically involve training a model on a variety of different tasks, with
the goal of learning generalizable knowledge that can be transferred to new tasks. This is
different from traditional machine learning, where a model is typically trained on a single task
and then used for that task alone.
Meta-learning, also called "learning to learn" algorithms, is a branch of machine
learning that focuses on teaching models to self-adapt and solve new problems with
little to no human intervention.
It entails using a different machine learning algorithm that has already been trained to
act as a mentor and transfer knowledge. Through data analysis, meta-learning gains
insights from this mentor algorithm's output and improves the developing algorithm's
ability to solve problems effectively.
To increase the flexibility of automatic learning, meta-learning makes use of
algorithmic metadata. It comprehends how algorithms adjust to a variety of problems,
improving the functionality of current algorithms and possibly even learning the
algorithm itself.
Meta-learning optimizes learning by using algorithmic metadata, including
performance measures and data-derived patterns, to strategically learn, select, alter,
or combine algorithms for specific problems.
The process of learning to learn or the meta-training process can be crudely summed up in
the following diagram:
Optimizes algorithms to
Optimization-based meta- Few-shot learning in
quickly solve new tasks
learning reinforcement learning.
with limited data.
Gradient-based meta-
learning algorithm that
Reptile Few-shot learning.
updates model parameters
through iterations.
Learning to learn by
Meta-learning approach
gradient descent by Few-shot learning and
that optimizes meta-
gradient descent (L2L- transfer learning.
optimization algorithms.
GD2)
Advantages of Meta-learning
1. Meta-Learning offers more speed: Meta-learning approaches can produce learning
architectures that perform better and faster than hand-crafted models.
1. Better generalization: Meta-learning models can frequently generalize to new tasks
more effectively by learning to learn, even when the new tasks are very different from
the ones they were trained on.
1. Scaling: Meta-learning can automate the process of choosing and fine-tuning
algorithms, thereby increasing the potential to scale AI applications.
1. Fewer data required: These approaches assist in the development of more general
systems, which can transfer knowledge from one context to another. This reduces
the amount of data you need in solving problems in the new context.
1. Improved performance: Meta-learning can help improve the performance of
machine learning models by allowing them to adapt to different datasets and learning
environments. By leveraging prior knowledge and experience, meta-learning models
can quickly adapt to new situations and make better decisions.
1. Fewer hyperparameters: Meta-learning can help reduce the number of
hyperparameters that need to be tuned manually. By learning to optimize these
parameters automatically, meta-learning models can improve their performance and
reduce the need for manual tuning.
Meta-learning Optimization
During the training process of a machine learning algorithm, hyperparameters determine
which parameters should be used. These variables have a direct impact on how successfully
a model trains. Optimizing hyperparameters may be done in several ways.
1. Grid Search: The Grid Search technique makes use of manually set
hyperparameters. All suitable combinations of hyperparameter values (within a given
range) are tested during a grid search. After that, the model selects the best
hyperparameter value. But because the process takes so long and is so ineffective,
this approach is seen as conventional. Grid Search may be found in the Sklearn
library.
1. Random Search: The optimal solution for the created model is found using
the random search approach, which uses random combinations of the
hyperparameters. Even though it has characteristics similar to grid search, it has
been shown to produce superior results overall. The disadvantage of random search
is that it produces a high level of volatility while computing. Random Search may be
found in the Sklearn library. Random Search is superior to Grid Search.
Applications of Meta-learning
Meta-learning algorithms are already in use in various applications, some of which are:
1. Online learning tasks in reinforcement learning
1. Sequence modeling in Natural language processing
1. Image classification tasks in Computer vision
1. Few-shot learning: Meta-learning can be used to train models that can quickly
adapt to new tasks with limited data. This is particularly useful in scenarios where the
cost of collecting large amounts of data is prohibitively high, such as in medical
diagnosis or autonomous driving.
1. Model selection: Meta-learning can help automate the process of model selection
by learning to choose the best model for a given task based on past experience. This
can save time and resources while also improving the accuracy and robustness of
the resulting model.
1. Hyperparameter optimization: Meta-learning can be used to automatically tune
hyperparameters for machine-learning models. By learning from past experience,
meta-learning models can quickly find the best hyperparameters for a given task,
leading to better performance and faster training times.
1. Transfer learning: Meta-learning can be used to facilitate transfer learning, where
knowledge learned in one domain is transferred to another domain. This can be
especially useful in scenarios where data is scarce or where the target domain is
vastly different from the source domain.
1. Recommender systems: Meta-learning can be used to build better recommender
systems by learning to recommend the most relevant items based on past user
behavior. This can improve the accuracy and relevance of recommendations, leading
to better user engagement and satisfaction.
Conclusion: Although Meta-Learning approaches are currently computationally expensive,
they are an exciting frontier for AI Research and can be a big step forward in our quest to
achieve Artificial General Intelligence, as computers would have the ability to not only make
accurate classifications and estimates but would able to improve their parameters (and
hyperparameters) to get better at multiple tasks in multiple problem contexts.
What is Zero-Shot Learning?
Zero-shot learning (ZSL) is a machine learning technique where a model can classify data it
has never seen before. Instead of relying on training data for each possible category, ZSL
uses semantic information about the categories to make predictions. This approach mimics
how humans can identify new objects by sensing their characteristics or details.
Key Characteristics of Zero-Shot Learning
No Training Data for New Classes: The model is not exposed to any examples of
the new classes during training.
Utilizes Prior Knowledge: The model relies on external knowledge or semantic
descriptions to understand and classify the new classes.
Zero-shot learning (ZSL) is a machine learning technique where a model can classify
data it has never seen before.
For example, if a machine has learned about animals like cats, lions, and horses by
understanding features like “small and fluffy,” “big wild cat,” or “long face,” it can use
this knowledge to identify a new animal, like a tiger. Even if it has never seen a tiger
before, it can use a description like “a lion-like animal with dark stripes” to identify it
correctly. This makes it easier for machines to learn and adapt without needing lots of
examples.
What is One-Shot Learning?
One-shot learning is a machine learning approach where a model is trained to recognize or
classify new categories using only a single example. This technique is designed to handle
situations where it is impractical to gather multiple examples of every possible category. OSL
focuses on learning to generalize from a very limited amount of data, mimicking the human
ability to recognize new objects or concepts from just one observation.
Key Characteristics of One-Shot Learning
Single Example per Class: The model is provided with exactly one example for
each new class during the training or evaluation phase. It must learn to generalize
and make accurate predictions based on this single instance.
Similarity-Based Methods: OSL often employs similarity metrics or distance-based
approaches to compare new instances with the single example and determine their
class. Techniques such as Siamese Networks or Prototypical Networks are
commonly used.
5. Challenges
ZSL: Depends heavily on the quality of semantic information and may struggle with
very dissimilar classes.
OSL: Performance relies on the representativeness of the single example; poor
examples can lead to inaccurate predictions.
FSL: Risks overfitting to the small dataset; performance is sensitive to the quality and
diversity of the examples provided.
6. Methodologies
ZSL: Techniques include semantic embedding models and attribute-based methods.
The model uses high-level descriptions to make inferences.
OSL: Methods involve similarity-based networks and metric learning, focusing on
comparing new examples to the single provided example.
FSL: Uses meta-learning approaches, such as MAML, to enable rapid adaptation to
new classes with few examples.
Summary of Differences between Zero-Shot Learning (ZSL), One-Shot Learning (OSL),
and Few-Shot Learning (FSL)
Few examples
Number of Exactly one
No training examples (typically a few to
Training example per new
for new classes several dozen) per
Examples class
new class
Useful when
Ideal for scenarios Effective when a
examples for new
Applications with only one few examples can
classes are
example available be collected
impractical
Conclusion
Zero-Shot Learning (ZSL), One-Shot Learning (OSL), and Few-Shot Learning (FSL) each
offer unique approaches to handling limited training data in machine learning. ZSL excels in
classifying new categories without prior examples by leveraging semantic information, while
OSL focuses on recognizing new classes from a single example using similarity-based
methods. FSL, on the other hand, adapts to new tasks with a small number of examples
through meta-learning techniques. Despite their differences, these methods collectively
enhance the versatility and efficiency of AI models, making them invaluable in scenarios
where large datasets are challenging to obtain.
where is the part of the support set for which , and represents the prototype of class . The
prototype calculation is visualized below for a 2-dimensional feature space and 3 classes
(Figure credit - Snell et al.). The colored dots represent encoded support elements with the
color-corresponding class labels, and the black dots next to the class label are the averaged
prototypes.
Distance-Based Classification
For a query sample :
1. Compute embedding:
Note that the negative sign is necessary since we want to increase the probability for close-
by vectors and have a low probability for distant vectors. We train the network based on
the cross-entropy error of the training query set examples. Thereby, the gradient flows
through both the prototypes and the query set encodings . For the distance function
, we can choose any function as long as it is differentiable concerning both of its inputs.
The most common function, which we also use here, is the squared euclidean distance, but
there have been several works on different distance functions as well.
MODULE 1 : Graph Machine Learning
What is Graph Machine Learning?
Graph machine learning is a subfield of machine learning that focuses on
using graph-structured data to perform predictive and analytical tasks.
In graphs, data is represented as nodes (vertices) and edges (links), capturing
complex relationships and interactions between entities.
Unlike traditional data, which is often tabular, graph data is inherently
interconnected, making it suitable for modeling social networks, biological
networks, communication networks, and more.
Example 1 :
Example 2:
Example 3:
Graph machine learning leverages algorithms designed to exploit these
connections, such as Graph Neural Networks (GNNs), to learn from the
structure and attributes of graphs. These algorithms can perform tasks like
node classification, link prediction, and graph clustering.
Node-level task
Node-level tasks are concerned with predicting the identity or role of each node
within a graph. A classic example of a node-level prediction problem is Zach’s karate
[Link] dataset represents one social network of people who are members of a
karate club.
After a disagreement, the club split into two groups. One group supported Mr. Hi
(the instructor) and the other supported John H (the administrator).
Each node represents a karate club member
Each edge shows social interactions between members outside karate
Because of the conflict, every member chose one [Link] task is to predict which
group a person will [Link] this dataset, a person is more likely to support the
leader they are socially closer [Link], the distance between a member and each
leader in the network helps determine their loyalty.
Input: graph with unlabled nodes
Allegiance to John A Allegiance to Mr. Hi→Mr. HiJohn A
Output: graph node labels
On the left we have the initial conditions of the problem, on the right we have a
possible solution, where each node has been classified based on the alliance. The
dataset can be used in other graph problems like unsupervised learning.
Edge-level task
Another type of prediction problem in graphs is edge prediction. Edge
prediction means finding whether a connection exists between two
nodes. For example, in image understanding, deep learning models not only
detect objects in an image, but also try to understand how those objects are
related (such as “person riding a bike” or “cup on a table”).
In this case:
Nodes represent objects in the image
Edges represent relationships between objects
The task is to predict whether an edge should exist between two objects
and what type of relationship it is. To find unknown connections, we can
first assume that every object is connected to every other object, and then
remove weak or unimportant connections, leaving only meaningful
relationships.
In (b), above, the original image (a) has been segmented into five entities:
each of the fighters,
Graph-level task
In a graph-level task, our goal is to predict the property of an entire graph. For
example, for a molecule represented as a graph, we might want to predict what the
molecule smells like, or whether it will bind to a receptor implicated in a disease.
Input: graphs
Output: labels for each graph, (e.g., "does the graph contain two rings?")
This is analogous to image classification problems with MNIST and CIFAR, where
we want to associate a label to an entire image. With text, a similar problem is
sentiment analysis where we want to identify the mood or emotion of an entire
sentence at once.
By learning from the topology and features of graphs, these models can
uncover hidden patterns, predict future connections, and identify influential
nodes within the network. The ability to handle and analyze graph data opens
up new possibilities for solving complex problems in various domains, from
recommending friends on social media to predicting molecular properties in
drug discovery.
How does graph machine learning work?
Graph machine learning works by leveraging the unique structure and relationships
inherent in graph data to perform various predictive and analytical tasks. Here’s a
breakdown of the process:
Graph Representation: Data is represented as a graph, consisting of nodes
(representing entities) and edges (representing relationships). Each node and
edge can have associated features, providing additional context.
Feature Extraction: Features from nodes, edges, and the overall graph
structure are extracted. This can include node attributes (e.g., user profiles in
social networks) and structural features (e.g., node degree, centrality
measures).
Graph Neural Networks (GNNs): GNNs are the primary models used in graph
machine learning. They extend traditional neural networks to operate on
graph data by aggregating information from a node’s neighbors. This process,
called message passing or neighborhood aggregation, allows the model to
learn representations that capture both local and global graph structures.
Propagation and Aggregation: During training, each node’s feature vector is
updated by combining its own features with aggregated features from its
neighbors. This iterative process enables nodes to gather information from
multi-hop neighborhoods, enriching their representations.
Learning and Optimization: The GNN is trained using standard machine
learning techniques, such as backpropagation and gradient descent. The
objective is to minimize a loss function tailored to the specific task, like node
classification, link prediction, or graph classification.
Prediction and Inference: Once trained, the model can be used to make
predictions. For example, in node classification, the model predicts the label
of each node based on its learned representation. In link prediction, the model
estimates the likelihood of new or missing edges. Graph machine learning
models excel in capturing the complex dependencies and patterns within
graph-structured data, making them powerful tools for applications ranging
from social network analysis to drug discovery.
Who is connected to
Connectivity Graph structure
whom
Example:
Each row → one node
Each column → one feature (age, embedding, type)
Even though varies across graphs: Neural networks can handle this easily
🔹 Edge features
Similarly:
Each row stores attributes of one edge (weight, type, distance).
🔹 Global features
One vector per graph:
Example:
Molecule energy
Scene category
So far, no problem.
This image shows how a GNN processes a graph node features pass through
stacked graph convolution layers with regularization, gradually refining
representations until the model outputs predictions such as the probability of links
between nodes.
GNN layers, followed by a linear model with a sigmoid activation for classification.
The design space for our GNN has many levers that can customize the model:
1. The number of GNN layers, also called the depth.
2. The dimensionality of each attribute when updated. The update function is a
1-layer MLP with a relu activation function and a layer norm for normalization
of activations.
3. The aggregation function used in pooling: max, mean or sum.
4. The graph attributes that get updated, or styles of message passing: nodes,
edges and global representation. We control these via boolean toggles (on or
off). A baseline model would be a graph-independent GNN (all message-
passing off) which aggregates all data at the end into a single global attribute.
Node Prediction
Edge Prediction
Graph Prediction
Node :
We will consider the case of binary classification, but this framework can easily be
extended to the multi-class or regression case. If the task is to make binary
predictions on nodes, and the graph already contains node information, the
approach is straightforward — for each node embedding, apply a linear classifier.
However, it is not always so simple. For instance, you might have information in the
graph stored in edges, but no information in nodes, but still need to make predictions
on nodes. We need a way to collect information from edges and give them to nodes
for prediction. We can do this by pooling. Pooling proceeds in two steps:
1. For each item to be pooled, gather each of their embeddings and concatenate
them into a matrix.
2. The gathered embeddings are then aggregated, usually via a sum operation.
For a more in-depth discussion on aggregation operations go to the Comparing
aggregation operations section.
We represent the pooling operation by the letter ρ, and denote that we are gathering
information from edges to nodes as pEn→Vn.
Edge :
If we only have node-level features, and are trying to predict binary edge-level
information, the model looks like this.
Graph:
If we only have node-level features, and need to predict a binary global property, we
need to gather all available node information together and aggregate them. This is
similar to Global Average Pooling layers in CNNs. The same can be done for edges.
1. Input Layer: The input layer initializes the node features, usually from raw data or
pre-trained embeddings.
1. Hidden Layers: Hidden layers perform the graph convolution operations,
progressively aggregating and transforming node features.
A. Graph Convolutional Layers: These layers perform the convolution
operation on the graph. Each layer updates the feature representation of a
node by aggregating the features of its neighbors.
B. Activation Functions: Non-linear functions such as ReLU are applied to
the output of each convolutional layer to introduce non-linearity into the
model.
C. Pooling Layers: These layers reduce the dimensionality of the graph by
merging nodes, which helps in capturing hierarchical structures.
1. Output Layer: The output layer produces the final node embeddings or predictions,
depending on the task (e.g., node classification, link prediction).
1. Fully Connected Layers: These layers are used at the end of the network to
perform tasks such as classification or regression.
Types of Graph Convolutional Networks (GCNs)
GCNs can be broadly categorized into two types: Spectral-based and Spatial-based GCNs.
1. Spectral-based GCNs
Spectral-based GCNs are defined in the spectral domain using the graph Laplacian and
Fourier transform. The convolution operation is performed by multiplying the graph signal
with a filter in the spectral domain. This approach leverages the eigenvalues and
eigenvectors of the graph Laplacian to perform convolution.
Key Models:
ChebNet: Uses Chebyshev polynomials to approximate the graph convolution
operation, allowing for efficient computation on large graphs.
GCN (Kipf & Welling): Simplifies the spectral convolution by using a first-order
approximation, making it computationally efficient and scalable.
2. Spatial-based GCNs
Spatial-based GCNs perform convolution directly in the spatial domain by aggregating
features from neighboring nodes. This approach is more intuitive and easier to implement
compared to spectral-based methods. Key Models:
GraphSAGE: Aggregates features from a fixed-size set of neighbors using mean,
LSTM, or pooling functions.
GAT (Graph Attention Network): Introduces an attention mechanism to assign
different weights to the neighbors of a node based on their importance.
where:
is the matrix of node features at layer
is the normalized adjacency matrix
is the trainable weight matrix at layer
σ is an activation function, such as ReLU
4. Normalization
Normalization of the adjacency matrix is crucial to ensure numerical stability and improve
model performance. A common normalization technique is:
Key Characteristics:
GATs use a self-attention mechanism that learns to assign different importance to each
neighbor in a graph, making them more adaptable to varied graph structures. They operate
directly on graph data without needing to define explicit neighborhood rules, which lends
flexibility across domains. GATs are often more robust to noisy or incomplete data compared
to traditional graph neural networks. Hyperparameters include the number of attention
heads, aggregation functions, and hidden layer sizes. Their performance depends on graph
size and network complexity, and training may be sensitive to data order and initializations.
Working Principle of Graph Attention Networks (GAT)
A Graph Attention Network (GAT) processes data represented as a graph, where entities are
nodes and relationships are edges. The input consists of node feature matrices and an
adjacency matrix describing connections between nodes. Each node’s features are
initialized with contextual information, such as attributes or embeddings relevant to the
[Link] core mechanism involves attention layers. For each node, the network
computes attention coefficients for its neighbors based on their features and connectivity.
These coefficients determine the extent to which a node aggregates information from each
connected node, allowing the model to focus more on relevant neighbors. The process is
typically repeated across multiple layers, with key parameters including the number of
attention heads, activation functions, and layer depth. Weights are learned during training
using backpropagation to optimize a loss function appropriate for the task, such as node
classification or link [Link] attention-based aggregation, the output is a set of
updated node representations that capture both the original features and the influence of
connected nodes. These outputs can be used directly for downstream tasks or passed to
additional layers or modules depending on the system design and operational requirements.
Constraints such as fixed graph schemas or edge sparsity are addressed during
preprocessing and model configuration to ensure efficient computation and compliance with
enterprise data policy.
Steps:
1. Linear Transformation
Each node in the graph has an input feature vector .
To project these features into a higher-level representation space, a shared learnable
weight matrix is applied to all nodes:
This step ensures that all node features are in the same feature space before computing
attention and allows the model to learn task-specific representations.
2. Attention Mechanism
For every node , attention scores are computed with each of its neighboring nodes .
The transformed features of nodes and are concatenated and passed through a learnable
attention function:
3. Normalization (Softmax)
Since node may have many neighbors, the raw attention scores are normalized using the
Softmax function:
This ensures:
Attention weights are positive
The sum of attention coefficients for a node equals 1
More important neighbors receive higher weights
4. Aggregation
Each node updates its representation by aggregating information from its neighbors using
the normalized attention coefficients:
Here, neighbors with higher attention weights contribute more to the updated node
[Link] activation function (such as ELU or ReLU) introduces non-linearity.
5. Multi-Head Attention
Instead of using a single attention mechanism, GAT employs multiple attention heads.
Each head learns independent attention coefficients:
Benefits of Multi-Head Attention:
Improves model stability
Captures different types of relationships
Reduces variance in attention learning
In hidden layers, outputs are concatenated; in the final layer, they are typically averaged.