Supervised & Unsupervised Learning Techniques
Supervised & Unsupervised Learning Techniques
GenAI
CA208E
Unit-2
Supervised and Unsupervised Learning Techniques
Contents of Unit-2
Supervised Learning
• Linear Regression
• Logistic Regression
• Decision Trees
• Evaluation Metrics (Accuracy, Precision, Recall, F1-score)
• Case Studies in Text Classification
Unsupervised Learning
• Clustering
• K-Means
• Hierarchical Clustering
• Dimensionality Reduction: PCA, t-SNE
• Applications in GenAI pipelines (e.g., prompt clustering)
Machine Learning
In machine learning, regression analysis is a statistical technique that predicts continuous numeric values
based on the relationship between independent and dependent variables. The main goal of regression
analysis is to plot a line or curve that best fit the data and to estimate how one variable affects another. In
machine learning, regression is a type of supervised learning. The key objective of regression-based tasks
is to predict output labels or responses, which are continuous numeric values, for the given input data.
The output will be based on what the model has learned in the training phase.
Linear regression is a type of supervised machine-learning algorithm that learns from the labelled
datasets and maps the data points with most optimized linear functions which can be used for prediction
on new datasets. It assumes that there is a linear relationship between the input and output, meaning the
output changes at a constant rate as the input changes. This relationship is represented by a straight line.
For example, we want to predict a student's exam score based on how many hours they studied. We
observe that as students study more hours, their scores go up. In the example of predicting exam scores
based on hours studied. Here,
• Independent variable (input): Hours studied because it's the factor we control or observe.
• Dependent variable (output): Exam score because it depends on how many hours were studied.
Simple linear regression
• One dependent variable (interval or ratio)
• Independent Variables − These variables are used to predict the value of the dependent
variable. These are also called predictors. In dataset, these are represented as features.
• Dependent Variables − These are the variables whose values we want to predict. These are
the main factors in regression analysis. In dataset, these are represented as target variables
• Regression line − It is a straight line or curve that a regressor plots to fit the data points best.
• Overfitting and underfitting − Overfitting is when the regression model works well with the
training dataset but not with the testing dataset. It's also referred to as the problem of high
variance. Underfitting is when the model doesn't work well with training datasets. It's also
referred to as the problem of high bias.
• Outliers − These are data points that don't fit the pattern of the rest of the data. They are the
extremely high or extremely low values in the data set.
• Multicollinearity − multicollinearity occurs when independent variables (features) have
dependency among them.
A regression line can be a Positive Linear Relationship or a Negative Linear Relationship.
If the dependent variable expands on the Y-axis and the independent variable progress on X-axis, then
such a relationship is termed a Positive linear relationship (below LHS figure). If the
dependent variable decreases on the Y-axis while the independent variable increases on the X-axis, we
refer to this relationship as a negative linear relationship (below RHS figure).
How Does Linear Regression Work?
Linear regression works by modelling the relationship between two variables, x (independent
variable) and y (dependent variable), using a straight line. The independent variable, x, is represented
on the horizontal axis, while the dependent variable, y, is plotted on the vertical axis. The goal is to
find a line that best fits the data points and explains the relationship between the variables. For simple
linear regression (with one independent variable), the best-fit line is represented by the equation
𝑦=a𝑥+𝑏
Where:
• y is the predicted value (dependent variable)
• x is the input (independent variable)
• a is the slope of the line (how much y changes when x changes)
• b is the intercept (the value of y when x = 0)
The best-fit line will be the one that optimizes the values of a (slope) and b (intercept) so that the
predicted y values are as close as possible to the actual data points.
To find the value of b, a using the following equation:
(σ 𝑦) (σ 𝑥 2 ) −(σ 𝑥) (σ 𝑥𝑦 1
b= 2 2 or b = (σ 𝑦 − 𝑎 σ 𝑥)
𝑛 σ 𝑥 −(σ 𝑥) 𝑛
𝑛 σ 𝑥𝑦 − (σ 𝑥)(σ 𝑦)
a=
𝑛 σ 𝑥 2 −. (σ 𝑥)2
Example 1: Predict the glucose level given the age.
a b
a b
a b
For 𝑥 = 43:
𝑦 ′ = 0.385 43 + 65.14 = 81.67
For 𝑥 = 21:
𝑦 ′ = 0.385 21 + 65.14 = 73.23
For 𝑥 = 25:
𝑦 ′ = 0.385 25 + 65.14 = 74.75
For 𝑥 = 42:
𝑦 ′ = 0.385 42 + 65.14 = 81.29
For 𝑥 = 57:
𝑦 ′ = 0.385 57 + 65.14 = 87.13
For 𝑥 = 59:
𝑦 ′ = 0.385 59 + 65.14 = 87.90
Find the error (residual) for each subject
Error = 𝑦 − 𝑦 ′
Squared Error = ቀ𝑦 − 𝑦 ′ )2
Example (for Subject 1, 𝑥 = 43, actual 𝑦 = 99):
Error = 99 − 81.67 = 17.33
Squared Error = ൫17.33)2 = 299.8
∑(y−y′)2
𝑛
∑(y−y′)2 = 432
𝑖=1
432
MSE = ≈ 72
6
Root MSE (RMSE),
RMSE = MSE ≈ 8.48
Conclusion: “On average, predictions are about ±9 glucose units away from actual values.”
Advantages of Linear Regression Disadvantages of Linear Regression
When you know the relationship between the Diversely, linear regression assumes a linear
independent and dependent variable have a linear relationship between dependent and independent
relationship, this algorithm is the best to use variables. That means it assumes that there is a
because of it’s less complexity compared to other straight-line relationship between them. It assumes
algorithms. independence between attributes.
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from [Link] import mean_squared_error, r2_score
Python Code for Linear Regression # Step 5: Train (fit) the model on training data
# Model will learn the best line (y = aX + b) that fits the data
[Link](X_train, y_train)
In machine learning, multiple linear regression (MLR) is a statistical technique that is used to predict
the outcome of a dependent variable based on the values of multiple independent variables. The
multiple linear regression algorithm is trained on data to learn a relationship (known as a regression
line) that best fits the data. This relation describes how various factors affect the result. This relation is
used to forecast the value of dependent variable based on the values of independent variables.
Use the following steps to fit a multiple linear regression model to this dataset.
Step 1: Calculate x12, x22, x1y, x2y and x1x2.
Step 2: Calculate Regression Sums.
Step 3: Calculate b0, b1, and b2.
Step 5: Place b0, b1, and b2 in the estimated linear regression equation.
Step 1: Calculate x12, x22, x1y, x2y and x1x2.
Step 2: Calculate Regression Sums.
Step 5: Place b0, b1, and b2 in the estimated linear regression equation.
Example: predict the CO2 emission of a car where the weight is 2300kg, and the volume is
1300cm3
Challenges of Multiple Linear Regression
Challenge Description
High correlation between independent variables, leading to unstable model
Multicollinearity
coefficients and difficulty in interpreting the impact of individual variables.
The model fits the training data too closely, leading to poor performance on
Overfitting
new, unseen data.
The model fails to capture the underlying patterns in the data, resulting in
Underfitting
poor performance on both training and test data.
Multiple linear regression assumes a linear relationship between the
Non-linearity independent and dependent variables. Non-linear relationships can lead to
inaccurate predictions.
Outliers can significantly impact the model's performance, especially in
Outliers
small datasets.
Missing Data Missing data can lead to biased and inaccurate results.
Difference Between Simple and Multiple Linear Regression
The sigmoid function is a mathematical function for mapping predicted values to probabilities. It can map
any real value into another value within 0 and 1. When the result of the sigmoid function is greater than
0.5, we classify the label as class 1 or positive class; if it’s less than 0.5, we can classify it as a negative
class or 0.
1
S(Z) = −𝑧
1+𝑒
Suppose a dataset of students entrance marks for JEE and based on the historic data of those who are
selected or not selected in IIT. Based on Logistic Regression, the values of learnt parameters are b=1 and
a=8. Assume marks of x=60. Computer the resultant class. Here ax+b = 8*60+1 = 481
1
P(x) = 1
P(x) = 1+𝑒 −481 = 0.44
1+𝑒 −𝑧
It has been observed that 0.44<0.5, therefore the candidate with marks=60 won’t be selected.
Cust Income Lot_size Ownership
1 60.0 18.4 Owner
2 64.8 21.6 Owner
3 84.0 17.6 Non-Owner
4 59.4 16.0 Non-Owner
5 108.0 17.6 Owner
6 75.0 19.6 Non-Owner
Example: Construct a Logistic Regression model with the values of learnt parameters b0 = -25.9482,
b1 = 0.1109 and b2 = 0.9638, where b1 and b2 are for income and lot_size variables respectively. Using
Logistic Regression model with probability cutoff 0.75. Classify the given 6 custimers as “owner” or
“non-owner”. Present the results in classification matrix also.
Types of Logistic Regression: Logistic regression can be classified into three main types based on
the nature of the dependent variable:
1. Binomial Logistic Regression: This type is used when the dependent variable has only two
possible categories. Examples include Yes/No, Pass/Fail or 0/1. It is the most common form of
logistic regression and is used for binary classification problems.
2. Multinomial Logistic Regression: This is used when the dependent variable has three or more
possible categories that are not ordered. For example, classifying animals into categories like
"cat," "dog" or "sheep." It extends the binary logistic regression to handle multiple classes.
3. Ordinal Logistic Regression: This type applies when the dependent variable has three or more
categories with a natural order or ranking. Examples include ratings like "low," "medium" and
"high." It takes the order of the categories into account when modeling.
Assumptions of Logistic Regression
1. Independent observations: Each data point is assumed to be independent of the others means
there should be no correlation or dependence between the input samples.
2. Binary dependent variables: It takes the assumption that the dependent variable must be binary,
means it can take only two values.
3. Linearity relationship between independent variables and log odds: The model assumes a linear
relationship between the independent variables and the log odds of the dependent variable which
means the predictors affect the log odds in a linear way.
4. No outliers: The dataset should not contain extreme outliers as they can distort the estimation of
the logistic regression coefficients.
5. Large sample size: It requires a sufficiently large sample size to produce reliable and stable
results.
Advantages of Logistic Regression Models
• One of the simplest machine learning algorithms and easy to implement
• The predicted parameters (trained weights) give inference about the importance of each feature
• Can be updated easily to reflect new data, unlike decision trees or support vector machines
• Outputs are well-calibrated probabilities along with classification results
• Logistic Regression is less prone to overfitting
• Logistic Regression proves to be very efficient when the dataset has features that are linearly separable
• Can easily be extended to multi-class classification using a softmax classifier, this is known as
Multinomial Logistic Regression
• Node - a feature(attribute)
• Branch - a decision(rule)
• Leaf - an outcome(categorical or
continuous)
Calculate Entropy: For each attribute, the algorithm calculates the entropy of the
dataset based on the values of that attribute. Entropy is computed using the formula:
Calculate the Information Gain for each attribute. Information Gain is a measure
of the effectiveness of an attribute in classifying the data. It is computed as the
difference between the entropy of the original dataset and the weighted average of
the entropies of the subsets created by splitting the data based on that attribute.
Select Best Attribute: The algorithm selects the attribute with the highest
Information Gain as the attribute to split the dataset at that node. This process is
repeated recursively for each subset until a stopping condition is met, such as
reaching a certain depth or having subsets that are pure (i.e., all instances belong to
the same class).
By using entropy and information gain, the ID3 algorithm intelligently chooses how
to split the data at each node of the decision tree, resulting in a tree structure that
effectively classifies instances based on the given attributes.
Consider the weather dataset as given below:
Here, the attribute with maximum information gain is Outlook. So, the decision tree built so far –
Here, when Outlook = = overcast, it is of pure class(Yes). Now, we have to repeat
same procedure for the data with rows consist of Outlook value as Sunny and then
for Outlook value as Rain. Now, finding the best attribute for splitting the data
with Outlook=Sunny values{Dataset rows = [1, 2, 8, 9, 11]}.
Here, when Outlook = Rain and Wind = Strong, it is a pure class of category "no". And When Outlook =
Rain and Wind = Weak, it is again a pure class of category "yes".
And this is our final desired tree for the given dataset.
Height Hair Eyes Attractive?
Small Blonde Brown No
Tall Dark Brown No
Tall Blonde Blue Yes
Tall Dark Blue No
Small Dark Blue No
Tall Red Blue Yes
Tall Blonde Brown No
Small Blonde Blue Yes
Example: The above dataset (adapted from Quinlan) shows some attributes of people and whether
they are considered attractive. Use the ID3 algorithm to build a decision tree that classifies which
attributes make a person attractive.
You are required to show the following steps:
a. Calculate the entropy of the dataset 𝑆.
b. Calculate the information gain for each attribute (Height, Hair, Eyes).
Advantages and Disadvantages of ID3 Algorithm
Advantages
• Inexpensive to construct
• Extremely fast at classifying unknown records Easy to interpret for small-sized trees.
• Robust to noise (especially when methods to avoid over-fitting are employed).
• Can easily handle redundant or irrelevant attributes (unless the attributes are interacting).
Disadvantages
• The space of possible decision trees is exponentially large. Greedy approaches are often
unable to find the best tree.
• Does not take into account interactions between attributes.
• Each decision boundary involves only a single attribute.
Advantages of Decision Tree Algorithm
• Easy to Interpret and Visualize: Decision trees provide a clear, hierarchical structure that is
simple for humans to understand and visualize, especially for smaller trees.
• Handles Both Data Types: They can work with both categorical (like color) and numerical
(like age) data, often without requiring extensive data transformation.
• Little Data Preparation: They require less data cleaning and normalization compared to other
algorithms.
• Non-Linearity: Decision trees can model complex, non-linear relationships in the data.
• Handles Missing Values: Some decision tree algorithms can handle missing values in the data
without requiring significant imputation.
Disadvantages of Decision Tree Algorithm
• Overfitting: A major issue, decision trees can grow too complex and memorize the training
data, leading to poor performance on new, unseen data.
• Instability: Even small changes in the training data can lead to a significantly different tree
structure and predictions.
• Bias Towards Dominant Classes/Features: They can be biased towards features with many
distinct values or dominant classes, potentially ignoring other important features.
• Computational Cost: As trees get deeper to accommodate complex data, they can become
computationally expensive to build and prune.
• Difficulty with Complex Interactions: Decision trees may struggle to capture highly
complex interactions between features.
Evaluation Metrics in Machine Learning
When building machine learning models, it’s important to understand how well they perform.
Evaluation metrics help us to measure the effectiveness of our models. Whether we are solving a
classification problem, predicting continuous values or clustering data, selecting the right evaluation
metric allows us to assess how well the model meets our goals. In this article, we will see commonly
used evaluation metrics and discuss how to choose the right metric for our model.
Confusion matrix is a simple table used to measure how well a classification model is performing. It
compares the predictions made by the model with the actual results and shows where the model was
right or wrong. This helps you understand where the model is making mistakes so you can improve it. It
breaks down the predictions into four categories:
• True Positive (TP): The model correctly predicted a positive outcome i.e the actual outcome
was positive.
• True Negative (TN): The model correctly predicted a negative outcome i.e the actual outcome
was negative.
• False Positive (FP): The model incorrectly predicted a positive outcome i.e the actual outcome
was negative. It is also known as a Type I error.
• False Negative (FN): The model incorrectly predicted a negative outcome i.e the actual
outcome was positive. It is also known as a Type II error.
Accuracy is a fundamental metric used for evaluating the performance of a classification model. It tells
us the proportion of correct predictions made by the model out of all predictions.
While accuracy provides a quick snapshot, it can be misleading in cases of imbalanced datasets. For
example, in a dataset with 90% class A and 10% class B, a model predicting only class A will still achieve
90% accuracy but it will fail to identify any class B instances.
Accuracy is good but it gives a False Positive sense of achieving high accuracy. The problem arises due to
the possibility of misclassification of minor class samples being very high.
Precision measures how many of the positive predictions made by the model are actually correct. It's
useful when the cost of false positives is high such as in medical diagnoses where predicting a disease
when it’s not present can have serious consequences.
TP
Precision =
TP + FP
Where:
TP = True Positives
FP = False Positives
It helps ensure that when the model predicts a positive outcome, it’s likely to be correct.
Recall or Sensitivity measures how many of the actual positive cases were correctly identified by the
model. It is important when missing a positive case (false negative) is more costly than false positives.
TP
Recall =
TP + FN
Where:
FN = False Negatives
In scenarios where catching all positive cases is important (like disease detection), recall is a key metric.
F1 Score is the harmonic mean of precision and recall. It is useful when we need a balance between
precision and recall as it combines both into a single number. A high F1 score means the model performs
well on both metrics. Its range is [0,1].
Lower recall and higher precision gives us great accuracy but then it misses a large number of instances.
More the F1 score better will be performance. It can be expressed mathematically in this way:
Precision × Recall
F1 Score = 2 ×
Precision + Recall
Scenario: A medical diagnosis system classifies 1,000 patients.
• True Positives (TP): 120 correctly diagnosed with the disease.
• False Positives (FP): 20 patients incorrectly diagnosed with the disease.
• True Negatives (TN): 800 correctly diagnosed as not having the disease.
• False Negatives (FN): 60 patients incorrectly diagnosed as not having the disease.
Formulas:
• Accuracy: (TP + TN) / (TP + TN + FP + FN)
• Precision: TP / (TP + FP)
• Recall (Sensitivity): TP / (TP + FN)
• F1-Score: 2 * (Precision * Recall) / (Precision + Recall)
Clustering or cluster analysis is a machine learning
technique, which groups the unlabeled dataset. It can be
defined as "A way of grouping the data points into different
clusters, consisting of similar data points. The objects with the
possible similarities remain in a group that has less or no
similarities with another group.“
It is an unsupervised learning method, hence no
supervision is provided to the algorithm, and it deals with the
unlabeled dataset.
After applying this clustering technique, each cluster or group is provided with a cluster-ID. ML
system can use this id to simplify the processing of large and complex datasets.
K-Means Clustering is an unsupervised
machine learning algorithm that helps group
data points into clusters based on their inherent
similarity. It groups the objects based on
attributes or features into k number of group,
where k is a positive integer number. The
grouping is done by minimizing the squares of
distances between data and the corresponding
cluster centroid. Initially, we specify how many
clusters we will made, when we put it in
category. We calculate its mean, that is why we
called k-mean clustering
Steps in k-mean clustering algorithm
(185,72) 0 K1
(170,56) 0 K2
(168,60)
(179,68)
(182,72)
(188,77)
Prob. 1: Assume the following eight points (with (x, y) representing locations): A1(2, 10), A2(2,
5), A3(8, 4), A4(5, 8), A5(7, 5), A6(6, 4), A7(1, 2), A8(4, 9) Assume the initial cluster centroids
are: A1(2, 10), A4(5, 8) and A7(1, 2). The distance function between two points a = (x1, y1) and b
= (x2, y2) is defined as-
Ρ(a, b) = |x2 – x1| + |y2 – y1|
Use K-Means Algorithm to find the three cluster centers after the second iteration.
Prob. 2: Given are the points A = (1,2), B = (2,2), C = (2, 1), D = (-1, 4), E = (-2, -1), F = (-1,-1).
Starting from initial clusters Cluster1 = {A} which contains only the point A and Cluster2 = {D}
which contains only the point D, run the K-means clustering algorithm and report the final
clusters. Draw the points on a 2-D grid and check if the clusters make sense.
K-Means Clustering Algorithm-
Iteration-01:
• We calculate the distance of each point from each of the center of the three clusters.
• The distance is calculated by using the given distance function.
The following illustration shows the calculation of distance between point A1(2, 10) and each of the
center of the three clusters-
Calculating Distance Between A1(2, 10) and C1(2, 10)-
Ρ(A1, C1) = |x2 – x1| + |y2 – y1|= |2 – 2| + |10 – 10| = 0
Calculating Distance Between A1(2, 10) and C2(5, 8)-
Ρ(A1, C2) = |x2 – x1| + |y2 – y1| = |5 – 2| + |8 – 10| = 3 + 2 = 5
Calculating Distance Between A1(2, 10) and C3(1, 2)-
Ρ(A1, C3) = |x2 – x1| + |y2 – y1| = |1 – 2| + |2 – 10| = 1 + 8 = 9
In the similar manner, we calculate the distance of other points from each of the center of the three
clusters. Next, We draw a table showing all the results. Using the table, we decide which point
belongs to which cluster. The given point belongs to that cluster whose center is nearest to it.
New clusters are-
Cluster-01:
• A1(2, 10)
Cluster-02:
• A3(8, 4)
• A4(5, 8)
• A5(7, 5)
• A6(6, 4)
• A8(4, 9)
Cluster-03:
• A2(2, 5)
• A7(1, 2)
Now, we re-compute the new cluster clusters.
• The new cluster center is computed by taking mean of all the points contained in that cluster.
For Cluster-01: We have only one point A1(2, 10) in Cluster-01. So, cluster center remains the same.
For Cluster-02:
Center of Cluster-02 = ((8 + 5 + 7 + 6 + 4)/5, (4 + 8 + 5 + 4 + 9)/5) = (6, 6)
For Cluster-03:
Center of Cluster-03 = ((2 + 1)/2, (5 + 2)/2) = (1.5, 3.5)
This is completion of Iteration-01!!
Iteration-02:
We calculate the distance of each point from each of the center of the three clusters. The following
illustration shows the calculation of distance between point A1(2, 10) and each of the center of the
three clusters-
Calculating Distance Between A1(2, 10) and C1(2, 10)-
Ρ(A1, C1) = |x2 – x1| + |y2 – y1| = |2 – 2| + |10 – 10| = 0
Calculating Distance Between A1(2, 10) and C2(6, 6)-
Ρ(A1, C2) = |x2 – x1| + |y2 – y1| = |6 – 2| + |6 – 10| = 4 + 4 = 8
Calculating Distance Between A1(2, 10) and C3(1.5, 3.5)-
Ρ(A1, C3) = |x2 – x1| + |y2 – y1| = |1.5 – 2| + |3.5 – 10| = 0.5 + 6.5 = 7
In the similar manner, we calculate the distance of other points from each of the center of the three
clusters.
Next,
• We draw a table showing all the results.
• Using the table, we decide which point belongs to which cluster.
• The given point belongs to that cluster whose center is nearest to it.
New clusters are-
Cluster-01:
• A1(2, 10)
• A8(4, 9)
Cluster-02:
• A3(8, 4)
• A4(5, 8)
• A5(7, 5)
• A6(6, 4)
Cluster-03:
• A2(2, 5)
• A7(1, 2)
Advantages of K-Means Clustering Algorithm
1. Agglomerative Clustering
2. Divisive clustering
PCA uses linear algebra to transform data into new features called principal components. It finds these
by calculating eigenvectors (directions) and eigenvalues (importance) from the covariance matrix.
PCA selects the top components with the highest eigenvalues and projects the data onto them simplify
the dataset.
In PCA method, the transformation is design in such
way that the data set be represented by a reduced
number of “effective” features and yet retains most of
the intrinsic information contained in the data; in other
words, the data set undergoes a dimensionality
reduction. Transforming the variables to a new set of
variables, are known as the principal components.
1. Removes Correlated Features: find out the correlation among the features (correlated variables).
Finding correlation manually in thousands of features is nearly impossible, frustrating and time-
consuming. PCA does this for you efficiently. After implementing the PCA on your dataset, all
the Principal Components are independent of one another. There is no correlation among them.
2. Improves Algorithm Performance: PCA is a very common way to speed up your Machine
Learning algorithm by getting rid of correlated variables which don't contribute in any decision
making. The training time of the algorithms reduces significantly with less number of features.
3. Reduces Overfitting: Overfitting mainly occurs when there are too many variables in the dataset.
So, PCA helps in overcoming the overfitting issue by reducing the number of features.
4. Improves Visualization: It is very hard to visualize and understand the data in high dimensions.
PCA transforms a high dimensional data to low dimensional data (2 dimension) so that it can be
visualized easily.
Disadvantages of PCA
• Independent variables become less interpretable: After implementing PCA on the dataset, your
original features will turn into Principal Components. Principal Components are the linear
combination of your original features. Principal Components are not as readable and
interpretable as original features.
• Data standardization is must before PCA: You must standardize your data before implementing
PCA, otherwise PCA will not be able to find the optimal Principal Components. All the
categorical features are required to be converted into numerical features before PCA can be
applied.
• Information Loss: Although Principal Components try to cover maximum variance among the
features in a dataset, if we don't select the number of Principal Components with care, it may
miss some information as compared to the original list of features. PCA assumes that the
principal components are orthogonal.
T-distributed Stochastic Neighbour Embedding
(t-SNE) is an unsupervised non-linear
dimensionality reduction technique used for
exploring high dimensional data. It is used for
visualizing high-dimensional data in a lower-
dimensional space mainly in 2D or 3D. Unlike
linear methods such as Principal Component
Analysis (PCA), t-SNE focus on preserving the
local structure and pattern of the data.
1. Measure pairwise similarities: First, t-SNE calculates how similar each pair of cells is to each other.
It does this by looking at the “distance” between them, often using a method like Gaussian (normal)
distribution. The idea is that if two cells have very similar gene expression profiles, they should have
a high similarity score, and if they’re far apart, the similarity should be low.
2. Create probabilities: These similarities are turned into probabilities (think of it like a “likelihood”
that two cells are close neighbours). The closer two points are, the higher the probability that they
are neighbours.
3. Map to lower dimensions: Now, t-SNE creates a new 2D space and tries to position the data points
there. The goal is to place points so that similar cells in the original space are still close together in
the new space, and dissimilar cells are far apart.
4. Optimize the layout: This is where the “stochastic” part comes in. t-SNE uses a technique called
gradient descent, which is a way of adjusting the positions of the points in the lower-dimensional
space step by step, trying to make the distribution of similarities in the lower space match the
original distribution as closely as possible.
Advantages of t-SNE
• Great for Visualization: t-SNE is particularly used to convert complex high-dimensional data
into 2D or 3D for visualization making patterns and clusters easy to observe.
• Preserve Local Structure: Unlike linear techniques like PCA t-SNE focus on maintaining the
local relationships between data points meaning similar data points remain close in the lower-
dimensional space.
• Non-Linear Capability: It captures non-linear dependencies in the data which makes it suitable
for complex datasets where linear methods fail.
• Cluster Separation: Helps in clearly visualizing clusters and class separability in datasets like
MNIST making it easier for interpretation and exploration.
Disadvantages of t-SNE
• Non-deterministic Output: The output can vary with each run due to its randomness unless a
fixed random_state is used.
• Not Scalable for Large Datasets: It struggles with very large datasets (e.g., millions of points)
unless optimized or approximated versions are used.
• Not Good for Downstream Tasks: t-SNE is mainly for visualization and is not suitable for
dimensionality reduction when feeding data into other ML algorithms.
• No Global Structure Preservation: It may distort global distances and structures in the data
focusing more on preserving local neighbourhoods.
Feature PCA t-SNE
Type of Dimensionality Reduction Linear dimensionality reduction technique Non-linear dimensionality reduction technique
Structure Preservation Preserves global structure of data Preserves local structure (clusters) of data
Works well for global patterns but may not capture local One of the best techniques for visualizing local
Effectiveness
clusters effectively clusters
Deterministic algorithm i.e it produces the same result Non-deterministic algorithm as results may vary
Algorithm Type
every time due to randomness
Transforms data into a new coordinate system to maximize Minimizes the distance between points in a
Transformation Method
variance Gaussian probability distribution
Allows control over variance preservation using Preserves distances rather than variance and is
Variance Preservation Control
eigenvalues controlled by hyperparameters
Computational Efficiency Computationally efficient especially for large datasets Computationally expensive for large datasets
Data Separability Works well for linearly separable datasets Better suited for non-linearly separable datasets
Sensitivity to Data Ordering Can be sensitive to the ordering of data points Less sensitive to data ordering
What is Prompt clustering?
Prompt clustering is a technique in AI and prompt engineering that involves grouping similar prompts
together based on their content, structure, or intended purpose. This method is used to organize, analyze,
and optimize large sets of prompts, improving efficiency in prompt management and AI system
performance.
Prompt clustering leverages similarity measures and grouping algorithms to identify patterns and
relationships among different prompts. It helps in understanding the diversity of prompts used in an AI
system and can lead to insights for prompt optimization and standardization.
Key aspects of Prompt clustering include:
1. Similarity Analysis: Identifying commonalities between different prompts.
2. Grouping: Categorizing prompts into clusters based on defined criteria.
3. Pattern Recognition: Discovering recurring themes or structures in prompt sets.
4. Efficiency Optimization: Streamlining prompt libraries and reducing redundancy.
5. Insight Generation: Providing a bird's-eye view of prompt usage and effectiveness.
Methods of Prompt clustering