The Wayback Machine - https://web.archive.org/web/20240529102219/https://www.geeksforgeeks.org/normal-and-shrinkage-linear-discriminant-analysis-for-classification-in-scikit-learn/
Open In App

Normal and Shrinkage Linear Discriminant Analysis for Classification in Scikit Learn

Last Updated : 02 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 supervised learning algorithm that projects the data onto a lower-dimensional space and separates the classes using a linear decision boundary. LDA is commonly used for classification tasks, where the goal is to predict the class label of a sample based on its features.

In LDA, the projection onto a lower-dimensional space is performed by finding a set of directions in the original feature space that maximizes the separation between the classes. These directions, known as the discriminant directions, are calculated using the class means and covariances.

Once the discriminant directions are found, the data is projected onto the space spanned by these directions and a linear decision boundary is constructed to separate the classes. The decision boundary is a hyperplane that is orthogonal to the discriminant directions and maximally separates the classes.

The LinearDiscriminantAnalysis class has two main modes of operation: normal and shrinkage. In normal mode, LDA assumes that the class covariance matrices are equal and estimated using the sample covariance of the entire dataset. In shrinkage mode, LDA uses a shrinkage estimator to regularize the covariance matrix and improve the stability of the model.

Performing linear discriminant analysis (LDA) for classification in scikit-learn involves the following steps:

  1. Import the LinearDiscriminantAnalysis class from sklearn.discriminant_analysis module.
  2. Generate or load the data for the classification task. The data should be a 2D array of feature values and a 1D array of class labels.
  3. Split the data into training and test sets using the train_test_split() function from the sklearn.model_selection module.
  4. Create an instance of the LinearDiscriminantAnalysis class and specify any desired hyperparameters, such as the solver (the solver parameter) and the shrinkage value (the shrinkage parameter).
  5. Fit the LinearDiscriminantAnalysis estimator to the training data using the fit() method.
  6. Use the estimator to make predictions on the test set using the predict() method.
  7. Evaluate the performance of the model by calculating metrics such as classification accuracy or the confusion matrix.

Here is a complete code of how to use the LinearDiscriminantAnalysis class to perform LDA for classification in scikit-learn:

Python3




import numpy as np
from sklearn.discriminant_analysis
import LinearDiscriminantAnalysis
from sklearn.model_selection import train_test_split
  
# Generate random data
X = np.random.randn(100, 10)
y = np.random.randint(2, size=100)
  
# Split the data into training and test sets
X_train, X_test,\
    y_train, y_test = train_test_split(X, y,
                                       test_size=0.3)
  
# Create a LinearDiscriminantAnalysis estimator
# and fit it to the training data
estimator = LinearDiscriminantAnalysis(shrinkage=None)
estimator.fit(X_train, y_train)
  
# Obtain predictions for the test set
y_pred = estimator.predict(X_test)
  
# Print the classification accuracy
print(estimator.score(X_test, y_test))


Output:

0.5

This code will fit a LinearDiscriminantAnalysis estimator to the training data using normal mode and use it to make predictions on the test set. The classification accuracy is then printed using the score() method of the estimator.

Shrinkage Linear Discriminant Analysis:

Shrinkage linear discriminant analysis (LDA) is a variant of LDA that uses a shrinkage estimator to regularize the covariance matrices of the classes. In normal LDA, the covariance matrices are estimated using the sample covariance of the entire dataset, which can be unstable and lead to overfitting. Shrinkage LDA addresses this issue by using a shrinkage estimator, such as the Ledoit-Wolf estimator, to regularize the covariance matrices and improve their stability.

To use shrinkage mode, you can set the solver parameter of the LinearDiscriminantAnalysis estimator to the solver of your choice(Eigen or lsqr) and specify a value for the shrinkage parameter. For example:

# Create a LinearDiscriminantAnalysis estimator
# with shrinkage and fit it to the training data
estimator = LinearDiscriminantAnalysis(solver='svd', shrinkage=0.5)
estimator.fit(X_train, y_train)

This code will create a LinearDiscriminantAnalysis estimator that uses shrinkage mode with a shrinkage value and fit it to the training

Python3




import numpy as np
from sklearn.discriminant_analysis
import LinearDiscriminantAnalysis
from sklearn.model_selection import train_test_split
  
# Generate random data
X = np.random.randn(100, 10)
y = np.random.randint(2, size=100)
  
# Split the data into training and test sets
X_train, X_test,\
    y_train, y_test = train_test_split(X, y,
                                       test_size=0.3)
  
# Create a LinearDiscriminantAnalysis estimator
# with shrinkage and fit it to the training data
estimator = LinearDiscriminantAnalysis(solver='eigen',
                                       shrinkage='auto')
estimator.fit(X_train, y_train)
  
# Obtain predictions for the test set
y_pred = estimator.predict(X_test)
  
# Print the classification accuracy
print(estimator.score(X_test, y_test))


Output:

0.43333333333333335


Similar Reads

Shrinkage Covariance Estimation in Scikit Learn
The Ledoit and Wolf proposed a formula for shrinkage which is generally used for regularizing the usual maximum likelihood estimation. This formula is called the Ledoit-Wolf covariance estimation formula. This formula is able to compute asymptotically optimal shrinkage parameters by minimizing the mean-square-error criterion features. OAS Estimator
3 min read
Support Vector Regression (SVR) using Linear and Non-Linear Kernels in Scikit Learn
Support vector regression (SVR) is a type of support vector machine (SVM) that is used for regression tasks. It tries to find a function that best predicts the continuous output value for a given input value. SVR can use both linear and non-linear kernels. A linear kernel is a simple dot product between two input vectors, while a non-linear kernel
5 min read
Map Data to a Normal Distribution in Scikit Learn
A Normal Distribution, also known as a Gaussian distribution, is a continuous probability distribution that is symmetrical around its mean. It is defined by its norm, which is the center of the distribution, and its standard deviation, which is a measure of the spread of the distribution. The normal distribution is often used to model continuous an
5 min read
Classification of text documents using sparse features in Python Scikit Learn
Classification is a type of machine learning algorithm in which the model is trained, so as to categorize or label the given input based on the provided features for example classifying the input image as an image of a dog or a cat (binary classification) or to classify the provided picture of a living organism into one of the species from within t
5 min read
Gaussian Process Classification (GPC) on the XOR Dataset in Scikit Learn
Gaussian process classification (GPC) is a probabilistic approach to classification that models the conditional distribution of the class labels given the feature values. In GPC, the data is assumed to be generated by a Gaussian process, which is a stochastic process that is characterized by its mean and covariance functions. The mean function in G
4 min read
MNIST Classification Using Multinomial Logistic + L1 in Scikit Learn
In this article, we shall implement MNIST classification using Multinomial Logistic Regression using the L1 penalty in the Scikit Learn Python library. Multinomial Logistic Regression and L1 Penalty MNIST is a widely used dataset for classification purposes. You may think of this dataset as the Hello World dataset of Machine Learning. Logistic Regr
4 min read
Probabilistic Predictions with Gaussian Process Classification (GPC) in Scikit Learn
Gaussian Process Classification (GPC) is a probabilistic model for classification tasks. It is based on the idea of using a Gaussian process to model the relationship between the input features and the target labels of a classification problem. GPC makes use of Bayesian inference to make predictions, which means that it can output not only the most
7 min read
Plot Multinomial and One-vs-Rest Logistic Regression in Scikit Learn
Logistic Regression is a popular classification algorithm that is used to predict the probability of a binary or multi-class target variable. In scikit-learn, there are two types of logistic regression algorithms: Multinomial logistic regression and One-vs-Rest logistic regression. Multinomial logistic regression is used when the target variable ha
4 min read
Create a Scatter Plot using Sepal length and Petal_width to Separate the Species Classes Using scikit-learn
In this article, we are going to see how to create Scatter Plot using Sepal length and Petal_width to Separate the Species classes using scikit-learn in Python. The Iris Dataset contains 50 samples of three Iris species with four characteristics (length and width of sepals and petals). Iris setosa, Iris virginica, and Iris versicolor are the three
2 min read
Save and Load Machine Learning Models in Python with scikit-learn
In this article, let's learn how to save and load your machine learning model in Python with scikit-learn in this tutorial. Once we create a machine learning model, our job doesn't end there. We can save the model to use in the future. We can either use the pickle or the joblib library for this purpose. The dump method is used to create the model a
4 min read
Practice Tags :