The Wayback Machine - https://web.archive.org/web/20240906070919/https://www.geeksforgeeks.org/quadratic-discriminant-analysis/
Open In App

Quadratic Discriminant Analysis

Last Updated : 07 Jan, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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):

P(Y=k | X=x) = \frac{P(X=x | Y=k) P(Y=k)}{P(X=x)}

= \frac{P(X=x | Y=k) P(Y=k)}{\sum_{j=1}^{K} P(X=x | Y=j) P(Y=j)}

In LDA, we assume that P(X | Y=k) can be estimated to the multivariate Normal distribution that is given by following equation:

f_k(x) = \frac{1}{(2\pi)^{p/2}|\mathbf\Sigma|^{1/2}} e^{-\frac{1}{2}(x-\mu_k)^T \mathbf{\Sigma}^{-1}(x-\mu_k)}

where, \mu_k = mean\, of\, the\, examples\, of \, category\, k \\ \mathbf{\sum} = covariance \, (we\, assume\, common\, covariance\, for\, all\, categories)

and P(Y=k) =\pi_k. Now, we try to write the above equation with the assumptions:

P(Y=k | X=x) = \frac{\pi_k  \frac{1}{(2\pi)^{p/2}|\mathbf\Sigma|^{1/2}} e^{-\frac{1}{2}(x-\mu_k)^T \mathbf{\Sigma}^{-1}(x-\mu_k)}}{\sum_{j=1}^{K} \frac{1}{(2\pi)^{p/2}|\mathbf\Sigma|^{1/2}} e^{-\frac{1}{2}(x-\mu_j)^T \mathbf{\Sigma}^{-1}(x-\mu_j)}}

Now, we take log both sides and maximizing the equation, we get the decision boundary:

\delta_k(x) = \log \pi_k  - \frac{1}{2}\mu_k^T \Sigma^{-1}\mu_k + x^T \Sigma^{-1}\mu_k

For two classes, the decision boundary is a linear function of x where both classes give equal value, this linear function is given as:

\left\{x: \delta_k(x) = \delta_{\ell}(x) \right\}, 1 \leq j,\ell \leq K

For multi-class (K>2), we need to estimate the pK means, pK variance, K prior proportions and \binom{p}{2}K = \left ( \frac{p(p-1)}{2} \right )K  . Now, we discuss in more detail about Quadratic Discriminant Analysis.

Quadratic Discriminant Analysis

Quadratic discriminant analysis is quite similar to Linear discriminant analysis except we relaxed the assumption that the mean and covariance of all the classes were equal. Therefore, we required to calculate it separately. 

Now, for each of the class y the covariance matrix is given by:

\Sigma_y = \frac{1}{N_y-1} \sum_{y_i = y} (x_i - \mu_y)(x_i -\mu_y)^T

By adding the following term and solving (taking log both side and ). The quadratic Discriminant function is given by:

\delta_k(x) = \log \pi_k  - \frac{1}{2}\mu_k^T \mathbf{\Sigma}_k^{-1}\mu_k + x^T \mathbf{\Sigma}_k^{-1}\mu_k - \frac{1}{2}x^T \Sigma_k^{-1}x -\frac{1}{2}\log |\Sigma_k|

Implementation

  • In this implementation, we will be using R and MASS library to plot the decision boundary of Linear Discriminant Analysis and Quadratic Discriminant Analysis. For this, we will use iris dataset:

R

# import libraries
library(caret)
library(MASS)
library(tidyverse)
 
# Code to plot decision plot
decision_boundary = function(model, data,vars, resolution = 200,...) {
  class='Species'
  labels_var = data[,class]
  k = length(unique(labels_var))
  # For sepals
  if (vars == 'sepal'){
  data = data %>% select(Sepal.Length, Sepal.Width)
  }
  else{
  data = data %>% select(Petal.Length, Petal.Width)
  }
   
   
  # plot with color labels
  int_labels = as.integer(labels_var)
  plot(data, col = int_labels+1L, pch = int_labels+1L, ...)
   
  # make grid
  r = sapply(data, range, na.rm = TRUE)
  xs = seq(r[1,1], r[2,1], length.out = resolution)
  ys = seq(r[1,2], r[2,2], length.out = resolution)
  dfs = cbind(rep(xs, each=resolution), rep(ys, time = resolution))
   
  colnames(dfs) = colnames(r)
  dfs = as.data.frame(dfs)
   
  p = predict(model, dfs, type ='class' )
  p = as.factor(p$class)
 
   
  points(dfs, col = as.integer(p)+1L, pch = ".")
   
  mats = matrix(as.integer(p), nrow = resolution, byrow = TRUE)
  contour(xs, ys, mats, add = TRUE, lwd = 2, levels = (1:(k-1))+.5)
   
  invisible(mats)
}
 
par(mfrow=c(2,2))
# run the linear discriminant analysis and plot the decision boundary with Sepals variable
model = lda(Species ~ Sepal.Length + Sepal.Width, data=iris)
lda_sepals = decision_boundary(model, iris, vars= 'sepal' , main = "LDA_Sepals")
 
# run the quadratic discriminant analysis and plot the decision boundary with Sepals variable
model_qda = qda(Species ~ Sepal.Length + Sepal.Width, data=iris)
qda_sepals = decision_boundary(model_qda, iris, vars= 'sepal', main = "QDA_Sepals")
 
# run the linear discriminant analysis and plot the decision boundary with Petals variable
model = lda(Species ~ Petal.Length + Petal.Width, data=iris)
lda_petal =decision_boundary(model, iris, vars='petal', main = "LDA_petals")
 
# run the quadratic discriminant analysis and plot the decision boundary with Petals variable
model_qda = qda(Species ~ Petal.Length + Petal.Width, data=iris)
qda_petal =decision_boundary(model_qda, iris, vars='petal', main = "QDA_petals")

                    

LDA and QDA visualization

References:



Previous Article
Next Article

Similar Reads

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
Linear Discriminant Analysis in R Programming
One of the most popular or well established Machine Learning technique is Linear Discriminant Analysis (LDA ). It is mainly used to solve classification problems rather than supervised classification problems. It is basically a dimensionality reduction technique. Using the Linear combinations of predictors, LDA tries to predict the class of the giv
6 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
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
Discriminant Function Analysis Using R
Discriminant Function Analysis (DFA) is a statistical method used to find a discriminant function that can separate two or more groups based on their independent variables. In other words, DFA is used to determine which variables contribute most to group separation. DFA is a helpful tool in various fields such as finance, biology, marketing, etc. I
6 min read
Linear Discriminant Analysis in Machine Learning
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
8 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
Factor Analysis | Data Analysis
Factor analysis is a statistical method used to analyze the relationships among a set of observed variables by explaining the correlations or covariances between them in terms of a smaller number of unobserved variables called factors. Table of Content What is Factor Analysis?What does Factor mean in Factor Analysis?How to do Factor Analysis (Facto
13 min read
Difference Between Factor Analysis and Principal Component Analysis
Factor Analysis (FA) and Principal Component Analysis (PCA) are two pivotal techniques used for data reduction and structure detection. Despite their similarities, they serve distinct purposes and operate under different assumptions. This article explores the key differences between FA and PCA. Understanding Principal Component Analysis (PCA)Princi
4 min read
Data Analysis through Ethnographic Content Analysis
Ethnographic Content Analysis (ECA) is a qualitative research method that combines the systematic approach of content analysis with the depth and contextual richness of ethnography. This hybrid methodology is particularly useful for exploring complex social phenomena, uncovering patterns, and understanding cultural contexts. In this article, we wil
8 min read
Python Bokeh - Plotting Quadratic Curves on a Graph
Bokeh is a Python interactive data visualization. It renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise construction of novel graphics with high-performance interactivity. Bokeh can be used to plot quadratic curves on a graph. Plotting quadratic curves on a graph can be done using
2 min read
Solve Quadratic Equation in R
R language is the language of data visualization and data analytics. It is used to solve complex problems or to visualize the given datasets. In this article, we are going to learn how we can solve quadratic equations using R Programming Language. What is a Quadratic Formula?The quadratic formula is used to find the x-intercepts of the quadratic eq
5 min read
Quadratic Bezier Curve: Convert Edges from Lines to Curved Paths
Network visualizations are essential tools for representing complex relationships between entities. Traditionally, these visualizations use straight lines to connect nodes, but curved paths can offer a more aesthetically pleasing and informative representation. This article will guide you through the process of converting edges from straight lines
5 min read
Analysis of test data using K-Means Clustering in Python
This article demonstrates an illustration of K-means clustering on a sample random data using open-cv library. Pre-requisites: Numpy, OpenCV, matplot-lib Let's first visualize test data with Multiple Features using matplot-lib tool. # importing required tools import numpy as np from matplotlib import pyplot as plt # creating two test data X = np.ra
2 min read
Python | NLP analysis of Restaurant reviews
Natural language processing (NLP) is an area of computer science and artificial intelligence concerned with the interactions between computers and human (natural) languages, in particular how to program computers to process and analyze large amounts of natural language data. It is the branch of machine learning which is about analyzing any text and
6 min read
Single-Table Analysis with dplyr using R Language
The dplyr package is used to perform simulations in the data by performing manipulations and transformations. It can be installed into the working space using the following command : install.packages("dplyr") Let's create the main dataframe: C/C++ Code #installing the required libraries library(dplyr) #creating a data frame data_frame = data.frame(
5 min read
Multidimensional data analysis in Python
Multi-dimensional data analysis is an informative analysis of data which takes many relationships into account. Let's shed light on some basic techniques used for analysing multidimensional/multivariate data using open source libraries written in Python. Find the link for data used for illustration from here.Following code is used to read 2D tabula
5 min read
Exploratory Data Analysis in Python | Set 2
In the previous article, we have discussed some basic techniques to analyze the data, now let's see the visual techniques. Let's see the basic techniques - # Loading Libraries import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from scipy.stats import trim_mean # Loading Data data = pd.read_csv("state.c
4 min read
Heteroscedasticity in Regression Analysis
Prerequisite: Linear Regression In Simple Linear Regression or Multiple Linear Regression we make some basic assumptions on the error term [Tex]\epsilon [/Tex]. Simple Linear Regression: [Tex] \begin{equation} Y_i = \beta_0 + \beta_1 X_i + \epsilon_i \end{equation} [/Tex] Multiple Linear Regression: [Tex] \begin{equation} Y_i = \beta_0 + \beta_1 X_
3 min read
ML | Adjusted R-Square in Regression Analysis
Prerequisite: Linear Regression, R-square in Regression Why Adjusted-R Square Test: R-square test is used to determine the goodness of fit in regression analysis. Goodness of fit implies how better regression model is fitted to the data points. More is the value of r-square near to 1, better is the model. But the problem lies in the fact that the v
3 min read
Facebook Sentiment Analysis using python
This article is a Facebook sentiment analysis using Vader, nowadays many government institutions and companies need to know their customers' feedback and comment on social media such as Facebook. What is sentiment analysis? Sentiment analysis is one of the best modern branches of machine learning, which is mainly used to analyze the data in order t
6 min read
Python | Customer Churn Analysis Prediction
Customer Churn It is when an existing customer, user, subscriber, or any kind of return client stops doing business or ends the relationship with a company. Types of Customer Churn - Contractual Churn : When a customer is under a contract for a service and decides to cancel the service e.g. Cable TV, SaaS. Voluntary Churn : When a user voluntarily
5 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
Survival Analysis in R
Survival analysis in R Programming Language deals with the prediction of events at a specified time. It deals with the occurrence of an interesting event within a specified time and failure of it produces censored observations i.e incomplete observations. Survival analysis in R Programming Language Biological sciences are the most important applica
5 min read
Analysis required in Natural Language Generation (NLG) and Understanding (NLU)
Language is the method to share and communicate our understanding and knowledge with one another. Language plays an essential factor when it comes to sharing our knowledge, ideas, and vision. Hence, if we can discover a computational approach of language, we can develop a very sturdy means of communication. We adopt various techniques to completely
11 min read
Stock Price Analysis With Python
Python is a great language for making data-based analyses and visualizations. It also has a wide range of open-source libraries that can be used off the shelf for some great functionalities. Python Dash is a library that allows you to build web dashboards and data visualizations without the hassle of complex front-end HTML, CSS, or JavaScript. In t
3 min read
Principal Component Analysis with R Programming
Principal component analysis(PCA) in R programming is an analysis of the linear components of all existing attributes. Principal components are linear combinations (orthogonal transformation) of the original predictor in the dataset. It is a useful technique for EDA(Exploratory data analysis) and allows you to better visualize the variations presen
3 min read
Social Network Analysis Using R Programming
Social Network Analysis (SNA) is the process of exploring or examining the social structure by using graph theory. It is used for measuring and analyzing the structural properties of the network. It helps to measure relationships and flows between groups, organizations, and other connected entities. Before we start let us see some network analysis
6 min read
Predictive Analysis in R Programming
Predictive analysis in R Language is a branch of analysis which uses statistics operations to analyze historical facts to make predict future events. It is a common term used in data mining and machine learning. Methods like time series analysis, non-linear least square, etc. are used in predictive analysis. Using predictive analytics can help many
4 min read
Conceptual Framework for Solving Data Analysis Problems
Data Science is an interdisciplinary field that focuses on extracting knowledge from data sets which are typically huge in amount. The field encompasses analysis, preparing data for analysis, and presenting findings to inform high-level decisions in an organization. As such, it incorporates skills from computer science, mathematics, statistics, inf
4 min read
Practice Tags :