The Wayback Machine - https://web.archive.org/web/20240927181342/https://www.geeksforgeeks.org/ml-linear-discriminant-analysis/
Open In App

Linear Discriminant Analysis in Machine Learning

Last Updated : 20 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

As we know that while dealing with a high dimensional dataset then we must apply some dimensionality reduction techniques to the data at hand so, that we can explore the data and utilize it for modeling in an efficient manner. In this article, we will learn about one such dimensionality reduction technique that is used to map high dimensional data to a comparatively lower dimension without much data loss.

What is Linear Discriminant Analysis?

Linear Discriminant Analysis (LDA), also known as Normal Discriminant Analysis or Discriminant Function Analysis, is a dimensionality reduction technique primarily utilized in supervised classification problems. It facilitates the modeling of distinctions between groups, effectively separating two or more classes. LDA operates by projecting features from a higher-dimensional space into a lower-dimensional one. In machine learning, LDA serves as a supervised learning algorithm specifically designed for classification tasks, aiming to identify a linear combination of features that optimally segregates classes within a dataset.

For example, we have two classes and we need to separate them efficiently. Classes can have multiple features. Using only a single feature to classify them may result in some overlapping as shown in the below figure. So, we will keep on increasing the number of features for proper classification. 

Linear Discriminant Analysis

 

Assumptions of LDA

LDA assumes that the data has a Gaussian distribution and that the covariance matrices of the different classes are equal. It also assumes that the data is linearly separable, meaning that a linear decision boundary can accurately classify the different classes.

Suppose we have two sets of data points belonging to two different classes that we want to classify. As shown in the given 2D graph, when the data points are plotted on the 2D plane, there’s no straight line that can separate the two classes of data points completely. Hence, in this case, LDA (Linear Discriminant Analysis) is used which reduces the 2D graph into a 1D graph in order to maximize the separability between the two classes. 
 

Linearly Seperable Dataset

Linearly Separable Dataset


Here, Linear Discriminant Analysis uses both axes (X and Y) to create a new axis and projects data onto a new axis in a way to maximize the separation of the two categories and hence, reduces the 2D graph into a 1D graph. 

Two criteria are used by LDA to create a new axis: 

  1. Maximize the distance between the means of the two classes.
  2. Minimize the variation within each class.


 

The perpendicular distance between the line and points

The perpendicular distance between the line and points


In the above graph, it can be seen that a new axis (in red) is generated and plotted in the 2D graph such that it maximizes the distance between the means of the two classes and minimizes the variation within each class. In simple terms, this newly generated axis increases the separation between the data points of the two classes. After generating this new axis using the above-mentioned criteria, all the data points of the classes are plotted on this new axis and are shown in the figure given below. 
 

Linear Discriminant Analysis

 


But Linear Discriminant Analysis fails when the mean of the distributions are shared, as it becomes impossible for LDA to find a new axis that makes both classes linearly separable. In such cases, we use non-linear discriminant analysis.

How does LDA work?

LDA works by projecting the data onto a lower-dimensional space that maximizes the separation between the classes. It does this by finding a set of linear discriminants that maximize the ratio of between-class variance to within-class variance. In other words, it finds the directions in the feature space that best separates the different classes of data.

Mathematical Intuition Behind LDA

Let’s suppose we have two classes and a d- dimensional samples such as x1, x2 … xn, where:

  • n1 samples coming from the class (c1) and n2 coming from the class (c2).

If xi is the data point, then its projection on the line represented by unit vector v can be written as vTxi

Let’s consider u1 and u2 to be the means of samples class c1 and c2 respectively before projection and u1hat denote the mean of the samples of class after projection and it can be calculated by:

[Tex]\widetilde{\mu_1}  = \frac{1}{n_1}\sum_{x_i \in c_1}^{n_1} v^{T}x_i = v^{T} \mu_1 [/Tex]

Similarly,

[Tex]\widetilde{\mu_2} = v^{T} \mu_2[/Tex]

Now, In LDA we need to normalize |\widetilde{\mu_1} -\widetilde{\mu_2} |. Let y_i = v^{T}x_i  be the projected samples, then scatter for the samples of c1 is:

[Tex]\widetilde{s_1^{2}} = \sum_{y_i \in c_1} (y_i – \mu_1)^2[/Tex]

Similarly:

[Tex]\widetilde{s_2^{2}} = \sum_{y_i \in c_1} (y_i – \mu_2)^2[/Tex]

Now, we need to protect our data on the line having direction v which maximizes,

[Tex]J(v) = \frac{\widetilde{\mu_1} – \widetilde{\mu_2}}{\widetilde{s_1^{2}} + \widetilde{s_2^{2}}}[/Tex]

For maximizing the above equation we need to find a projection vector that maximizes the difference of means of reducing the scatters of both classes. Now, scatter matrix of s1 and s2 of classes c1 and c2 are:

[Tex]s_1 = \sum_{x_i \in c_1} (x_i – \mu_1)(x_i – \mu_1)^{T} [/Tex]

and s2

[Tex]s_2 = \sum_{x_i \in c_2} (x_i – \mu_2)(x_i – \mu_2)^{T} [/Tex]

After simplifying the above equation, we get scatter within the classes(sw) and scatter b/w the classes(sb):

[Tex]s_w = s_1 + s_2 \\ \\ s_b  = (\mu_1 – \mu_2) (\mu_1 – \mu_2 )^{T}[/Tex]

Now, we try to simplify the numerator part of J(v),

[Tex]J(v) = \frac{|\widetilde{\mu_1} – \widetilde{\mu_2}|}{\widetilde{s_1^{2}} + \widetilde{s_2^{2}}} = \frac{v^{T}s_{b}v}{v^{T}s_{w}v}[/Tex]

Now, To maximize the above equation we need to calculate differentiation with respect to v,

[Tex]\frac{d J(v)}{dv} = s_b v  – \frac{v^{t}s_{b} v (s_w v)}{v^{T} s_w v} \\ \\ = s_b v – \lambda s_w v =0 \\ \\ s_b v = \lambda s_w v \\ \\ s_w^{-1} s_b v = \lambda v \\ \\ M v = \lambda v \\ \\ where, \\ \\ \lambda = \frac{v^{T}s_{b} v}{v^{T} s_w v} and \\ \\ M  = s_w^{-1} s_b[/Tex]

Here, for the maximum value of J(v), we will use the value corresponding to the highest eigenvalue. This will provide us with the best solution for LDA.

Extensions to LDA

  1. Quadratic Discriminant Analysis (QDA): Each class uses its own estimate of variance (or covariance when there are multiple input variables).
  2. Flexible Discriminant Analysis (FDA): Where non-linear combinations of inputs are used such as splines.
  3. Regularized Discriminant Analysis (RDA): Introduces regularization into the estimate of the variance (actually covariance), moderating the influence of different variables on LDA.

Python Code Implementation of LDA

In this implementation, we will perform linear discriminant analysis using the Scikit-learn library on the Iris dataset.

Python3

# necessary import import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.datasets import load_iris from sklearn.preprocessing import StandardScaler, LabelEncoder from sklearn.model_selection import train_test_split from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score, confusion_matrix # load the iris dataset iris = load_iris() dataset = pd.DataFrame(columns=iris.feature_names, data=iris.data) dataset['target'] = iris.target # divide the dataset into class and target variable X = dataset.iloc[:, 0:4].values y = dataset.iloc[:, 4].values # Preprocess the dataset and divide into train and test sc = StandardScaler() X = sc.fit_transform(X) le = LabelEncoder() y = le.fit_transform(y) X_train, X_test,\ y_train, y_test = train_test_split(X, y, test_size=0.2) # apply Linear Discriminant Analysis lda = LinearDiscriminantAnalysis(n_components=2) X_train = lda.fit_transform(X_train, y_train) X_test = lda.transform(X_test) # plot the scatterplot plt.scatter( X_train[:, 0], X_train[:, 1], c=y_train, cmap='rainbow', alpha=0.7, edgecolors='b' ) # classify using random forest classifier classifier = RandomForestClassifier(max_depth=2, random_state=0) classifier.fit(X_train, y_train) y_pred = classifier.predict(X_test) # print the accuracy and confusion matrix print('Accuracy : ' + str(accuracy_score(y_test, y_pred))) conf_m = confusion_matrix(y_test, y_pred) print(conf_m)

Output:

Accuracy : 0.9333333333333333 [[10 0 0] [ 2 10 0] [ 0 0 8]]

Scatter plot of the iris data mapped into 2D

Scatter plot of the iris data mapped into 2D

Advanatages & Disadvantages of using LDA

Advanatages of using LDA

  1. It is a simple and computationally efficient algorithm.
  2. It can work well even when the number of features is much larger than the number of training samples.
  3. It can handle multicollinearity (correlation between features) in the data.

Disadvantages of LDA

  1. It assumes that the data has a Gaussian distribution, which may not always be the case.
  2. It assumes that the covariance matrices of the different classes are equal, which may not be true in some datasets.
  3. It assumes that the data is linearly separable, which may not be the case for some datasets.
  4. It may not perform well in high-dimensional feature spaces.

Applications of LDA 

  1. Face Recognition: In the field of Computer Vision, face recognition is a very popular application in which each face is represented by a very large number of pixel values. Linear discriminant analysis (LDA) is used here to reduce the number of features to a more manageable number before the process of classification. Each of the new dimensions generated is a linear combination of pixel values, which form a template. The linear combinations obtained using Fisher’s linear discriminant are called Fisher’s faces.
  2. Medical: In this field, Linear discriminant analysis (LDA) is used to classify the patient’s disease state as mild, moderate, or severe based on the patient’s various parameters and the medical treatment he is going through. This helps the doctors to intensify or reduce the pace of their treatment.
  3. Customer Identification: Suppose we want to identify the type of customers who are most likely to buy a particular product in a shopping mall. By doing a simple question and answers survey, we can gather all the features of the customers. Here, a Linear discriminant analysis will help us to identify and select the features which can describe the characteristics of the group of customers that are most likely to buy that particular product in the shopping mall.


Similar Reads

Normal and Shrinkage Linear Discriminant Analysis for Classification in Scikit Learn
In this article, we will try to understand the difference between Normal and Shrinkage Linear Discriminant Analysis for Classification. We will try to implement the same using sci-kit learn library in Python. But first, let's try to understand what is LDA. What is Linear discriminant analysis (LDA)? Linear discriminant analysis (LDA) is a supervise
4 min read
Linear and Quadratic Discriminant Analysis using Sklearn
Linear Discriminant Analysis (LDA) and Quadratic Discriminant Analysis (QDA) are two well-known classification methods that are used in machine learning to find patterns and put things into groups. They are especially helpful when you have labeled data and want to classify new observations notes into pre-defined categories. In this we will implemen
5 min read
Regularized Discriminant Analysis
Regularized Discriminant analysis Linear Discriminant analysis and QDA work straightforwardly for cases where a number of observations is far greater than the number of predictors n>p. In these situations, it offers very advantages such as ease to apply (Since we don't have to calculate the covariance for each class) and robustness to the deviat
3 min read
Quadratic Discriminant Analysis
Linear Discriminant Analysis Now, Let's consider a classification problem represented by a Bayes Probability distribution P(Y=k | X=x), LDA does it differently by trying to model the distribution of X given the predictors class (I.e. the value of Y) P(X=x| Y=k): [Tex]P(Y=k | X=x) = \frac{P(X=x | Y=k) P(Y=k)}{P(X=x)}[/Tex] [Tex]= \frac{P(X=x | Y=k)
4 min read
Gaussian Discriminant Analysis
Gaussian Discriminant Analysis (GDA) is a supervised learning algorithm used for classification tasks in machine learning. It is a variant of the Linear Discriminant Analysis (LDA) algorithm that relaxes the assumption that the covariance matrices of the different classes are equal. GDA works by assuming that the data in each class follows a Gaussi
7 min read
Getting started with Machine Learning || Machine Learning Roadmap
Machine Learning (ML) represents a branch of artificial intelligence (AI) focused on enabling systems to learn from data, uncover patterns, and autonomously make decisions. In today's era dominated by data, ML is transforming industries ranging from healthcare to finance, offering robust tools for predictive analytics, automation, and informed deci
11 min read
Locally Linear Embedding in machine learning
LLE(Locally Linear Embedding) is an unsupervised approach designed to transform data from its original high-dimensional space into a lower-dimensional representation, all while striving to retain the essential geometric characteristics of the underlying non-linear feature structure. LLE operates in several key steps: Firstly, it constructs a neares
8 min read
Loss function for Linear regression in Machine Learning
The loss function quantifies the disparity between the prediction value and the actual value. In the case of linear regression, the aim is to fit a linear equation to the observed data, the loss function evaluate the difference between the predicted value and true values. By minimizing this difference, the model strives to find the best-fitting lin
7 min read
Linear Algebra Operations For Machine Learning
Linear algebra is the backbone of many machine learning algorithms and techniques. Understanding the fundamental operations of linear algebra is crucial for anyone aspiring to delve deep into the world of machine learning. At its core, linear algebra provides a framework for handling and manipulating data, which is often represented as vectors and
15+ min read
Linear Regression in Machine learning
Machine Learning is a branch of Artificial intelligence that focuses on the development of algorithms and statistical models that can learn from and make predictions on data. Linear regression is also a type of machine-learning algorithm more specifically a supervised machine-learning algorithm that learns from the labelled datasets and maps the da
15+ min read
Step by Step Predictive Analysis - Machine Learning
Predictive analytics involves certain manipulations on data from existing data sets with the goal of identifying some new trends and patterns. These trends and patterns are then used to predict future outcomes and trends. By performing predictive analysis, we can predict future trends and performance. It is also defined as the prognostic analysis,
3 min read
Machine Learning and Analysis of Site Position Data
The content has been removed as per the author's request.
1 min read
Data Preprocessing, Analysis, and Visualization for building a Machine learning model
In this article, we are going to see the concept of Data Preprocessing, Analysis, and Visualization for building a Machine learning model. Business owners and organizations use Machine Learning models to predict their Business growth. But before applying machine learning models, the dataset needs to be preprocessed. So, let's import the data and st
5 min read
R-squared in Regression Analysis in Machine Learning
The most important thing we do after making any model is evaluating the model. We have different evaluation matrices for evaluating the model. However, the choice of evaluation matrix to use for evaluating the model depends upon the type of problem we are solving whether it's a regression, classification, or any other type of problem.  In this arti
4 min read
Sentiment Analysis of Restaurant Reviews - Machine Learning Project
Online reviews are essential in our decision-making process for choosing where to eat, what to buy, and which services to use. But how do businesses interpret the significance of these reviews for their service quality? That's where sentiment analysis comes in. This article provides an overview of sentiment analysis, common terms, and how Natural L
6 min read
Support vector machine in Machine Learning
In this article, we are going to discuss the support vector machine in machine learning. We will also cover the advantages and disadvantages and application for the same. Let's discuss them one by one. Support Vector Machines : Support vector machine is a supervised learning system and is used for classification and regression problems. Support vec
9 min read
Azure Virtual Machine for Machine Learning
Prerequisites: About Microsoft Azure, Cloud Based Services Some of the Machine Learning and Deep Learning algorithms may require high computation power which may not be supported by your local machine or laptop. In that case, creating a Virtual Machine on a cloud platform can provide you the expected computation power. We can have a system with hig
4 min read
Machine Learning Model with Teachable Machine
Teachable Machine is a web-based tool developed by Google that allows users to train their own machine learning models without any coding experience. It uses a web camera to gather images or videos, and then uses those images to train a machine learning model. The user can then use the model to classify new images or videos. The process of creating
7 min read
Artificial intelligence vs Machine Learning vs Deep Learning
Nowadays many misconceptions are there related to the words machine learning, deep learning, and artificial intelligence (AI), most people think all these things are the same whenever they hear the word AI, they directly relate that word to machine learning or vice versa, well yes, these things are related to each other but not the same. Let's see
4 min read
Need of Data Structures and Algorithms for Deep Learning and Machine Learning
Deep Learning is a field that is heavily based on Mathematics and you need to have a good understanding of Data Structures and Algorithms to solve the mathematical problems optimally. Data Structures and Algorithms can be used to determine how a problem is represented internally or how the actual storage pattern works & what is happening under
6 min read
Machine Learning - Learning VS Designing
In this article, we will learn about Learning and Designing and what are the main differences between them. In Machine learning, the term learning refers to any process by which a system improves performance by using experience and past data. It is kind of an iterative process and every time the system gets improved though one may not see a drastic
3 min read
Passive and Active learning in Machine Learning
Machine learning is a subfield of artificial intelligence that deals with the creation of algorithms that can learn and improve themselves without explicit programming. One of the most critical factors that contribute to the success of a machine learning model is the quality and quantity of data used to train it. Passive learning and active learnin
3 min read
Automated Machine Learning for Supervised Learning using R
Automated Machine Learning (AutoML) is an approach that aims to automate various stages of the machine learning process, making it easier for users with limited machine learning expertise to build high-performing models. AutoML is particularly useful in supervised learning, where you have labeled data and want to create models that can make predict
8 min read
Meta-Learning in Machine Learning
Traditional machine learning requires a huge dataset that is specific to a particular task and wishes to train a model for regression or classification purposes using these datasets. That’s radically far from how humans take advantage of their past experiences to learn quickly a new task from only a handset of examples. What is Meta Learning?Meta-l
13 min read
Continual Learning in Machine Learning
As we know Machine Learning (ML) is a subfield of artificial intelligence that specializes in growing algorithms that learn from statistics and make predictions or choices without being explicitly programmed. It has revolutionized many industries by permitting computer systems to understand styles, make tips, and perform tasks that were soon consid
10 min read
Few-shot learning in Machine Learning
What is a Few-shot learning?Few-shot learning is a type of meta-learning process. It is a process in which a model possesses the capability to autonomously acquire knowledge and improve its performance through self-learning. It is a process like teaching the model to recognize things or do tasks, but instead of overwhelming it with a lot of example
8 min read
What Is Meta-Learning in Machine Learning in R
In traditional machine learning, models are typically trained on a specific dataset for a specific task, and their performance is optimized for that particular task. However, in R Programming Language the focus is on building models that can leverage prior knowledge or experience to quickly adapt to new tasks with minimal additional training data.
7 min read
Types of Federated Learning in Machine Learning
Federated Learning is a powerful technique that allow a single machine to learn from many different source and converting the data into small pieces sending them to different Federated Learning (FL) is a decentralized of the machine learning paradigm that can enables to model training across various devices while preserving your data the data priva
5 min read
Machine Learning-based Recommendation Systems for E-learning
In today's digital age, e-learning platforms are transforming education by giving students unprecedented access to a wide range of courses and resources. Machine learning-based recommendation systems have emerged as critical tools for effectively navigating this vast amount of content. The article delves into the role of recommendation systems in e
9 min read
Understanding PAC Learning: Theoretical Foundations and Practical Applications in Machine Learning
In the vast landscape of machine learning, understanding how algorithms learn from data is crucial. Probably Approximately Correct (PAC) learning stands as a cornerstone theory, offering insights into the fundamental question of how much data is needed for learning algorithms to reliably generalize to unseen instances. PAC learning provides a theor
8 min read