Reading history

Linear Discriminant Analysis (LDA) in Python: Classifier and Dimension Reduction

6 min read 1 views

Learn Linear Discriminant Analysis in Python: use LDA as a classifier, reduce dimensions with class labels, and compare it with PCA and logistic regression.

Linear Discriminant Analysis (LDA) does two jobs. It is a fast classifier with no settings to tune, and it is a way to shrink many columns down to a few. Unlike PCA, it uses the class labels, so it keeps the directions that best separate the classes. In this lesson you will use LDA on wine data both ways and compare it with logistic regression and PCA.

In this lesson you will learn

  • The idea behind LDA in plain words
  • How to use LinearDiscriminantAnalysis as a classifier
  • How to use LDA to reduce dimensions
  • Why LDA can make at most classes − 1 components
  • When to choose LDA, PCA or logistic regression

You should know PCA, logistic regression and pipelines.

The Idea

Imagine two classes of points, red and blue, and a torch shining their shadows onto a wall. Turn the torch one way and the shadows overlap. Turn it another way and the red shadows land on the left and the blue on the right. LDA searches for the best angle. It looks for a direction where:

  • the class averages are as far apart as possible, and
  • the points inside each class are as tightly packed as possible.

PCA asks a different question: “Where is the most spread?” It ignores the labels. The biggest spread may have nothing to do with the classes, so PCA can throw away the very direction that separates them.

PCA: biggest spread (ignores labels)LDA: best class separationGrape type 0Grape type 1Grape type 2

LDA as a Classifier

The wine dataset has 178 wines from three grape types, with 13 chemical measurements each. LDA assumes each class forms a bell-shaped cloud and that all classes have the same shape. It then picks the class whose cloud a new point most likely came from.

from sklearn.datasets import load_wine
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

# 178 wines from 3 grape types, 13 chemical measurements each
X, y = load_wine(return_X_y=True)

lda = LinearDiscriminantAnalysis()
logreg = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
print(f"LDA                 : {cross_val_score(lda, X, y, cv=5).mean():.3f}")
print(f"logistic regression : {cross_val_score(logreg, X, y, cv=5).mean():.3f}")

lda.fit(X, y)
print("\nclass priors     :", lda.priors_.round(3))
print("probabilities for first wine:", lda.predict_proba(X[:1]).round(4))

Output

LDA                 : 0.966
logistic regression : 0.983

class priors     : [0.331 0.399 0.27 ]
probabilities for first wine: [[1. 0. 0.]]
  • LDA scores 96.6% with no scaling and no settings. Logistic regression is a little higher at 98.3%, but it needed scaling.
  • LDA does not need scaling for classification. Its maths already accounts for the spread of each column.
  • priors_ holds the share of each class in the training data. LDA uses these as starting odds.
  • LDA gives probabilities with predict_proba. For the first wine it is almost certain of class 0. On data that is this well separated, LDA is often very confident.

LDA for Dimension Reduction

Now we squeeze 13 columns into 2 with PCA and with LDA, then classify with k-nearest neighbours. Both reducers sit inside a pipeline so they only learn from training folds. LDA uses the labels, so fitting it outside the pipeline would leak them.

from sklearn.datasets import load_wine
from sklearn.decomposition import PCA
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.model_selection import cross_val_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_wine(return_X_y=True)

# Squeeze 13 columns down to 2, then classify with 5 nearest neighbours.
# Both reducers sit inside the pipeline, so they only see training folds.
pca = make_pipeline(StandardScaler(), PCA(n_components=2), KNeighborsClassifier())
lda = make_pipeline(StandardScaler(), LinearDiscriminantAnalysis(n_components=2),
                    KNeighborsClassifier())
print(f"PCA to 2-D then kNN: {cross_val_score(pca, X, y, cv=5).mean():.3f}")
print(f"LDA to 2-D then kNN: {cross_val_score(lda, X, y, cv=5).mean():.3f}")

# How much of the class separation does each LDA axis carry?
reducer = LinearDiscriminantAnalysis(n_components=2).fit(StandardScaler().fit_transform(X), y)
print("\nLDA explained variance ratio:", reducer.explained_variance_ratio_.round(3))
print("most components LDA can make: classes - 1 =", len(set(y)) - 1)

Output

PCA to 2-D then kNN: 0.966
LDA to 2-D then kNN: 0.989

LDA explained variance ratio: [0.687 0.313]
most components LDA can make: classes - 1 = 2
  • With only 2 columns kept, LDA’s version scores 98.9% and PCA’s scores 96.6%. LDA kept the directions that matter for the classes.
  • The first LDA direction carries 68.7% of the class separation and the second carries the rest.
  • LDA can make at most classes − 1 components. With 3 grape types that is 2. Three class centres always lie on one flat plane, so 2 directions are enough to tell them apart.

LDA, PCA or Logistic Regression?

LDAPCALogistic regression
Uses labelsYesNoYes
Reduces dimensionsYes, up to classes − 1Yes, up to the number of columnsNo
ClassifiesYesNoYes
Main assumptionBell-shaped classes with equal spreadNone about classesFewer assumptions
Good whenFew rows, classes well separatedNo labels, or for compressionGeneral default

A relative: QDA

QuadraticDiscriminantAnalysis lets each class have its own shape. Its boundaries can curve, but it needs more data per class to estimate those shapes.

Common Mistakes

  1. Asking for too many components. n_components cannot exceed classes − 1, so binary problems get only 1.
  2. Fitting LDA on all the data before cross-validation. LDA uses labels, so this leaks them. Keep it in a pipeline.
  3. Using LDA on very skewed or outlier-heavy data. Its bell-shape assumption breaks. Transform or clean the data first.
  4. Mixing up the two LDAs. Latent Dirichlet Allocation is a topic model for text and has nothing to do with this method.

Practice Exercises

Exercise 1. For a spam filter with two classes, how many LDA components can you get?

Show answer

One, because classes − 1 = 2 − 1 = 1. LDA would turn every email into a single score.

Exercise 2. LDA can overfit when there are many columns and few rows. Which option helps?

Show answer
LinearDiscriminantAnalysis(solver="lsqr", shrinkage="auto")

Shrinkage pulls the estimated spread towards a simpler shape, which steadies the model when data is scarce. It works with the "lsqr" and "eigen" solvers.

Frequently Asked Questions

Do I need to scale data before LDA?

Not for classification: the predictions do not change. Scaling can still help you compare the sizes of the learned coefficients, and it does no harm.

Is LDA still used today?

Yes. It is quick, has almost nothing to tune and works well with small datasets. It is a common first step for face recognition, medical data and any task with few rows and many columns.

Summary

  • LDA finds directions that push class averages apart and keep each class tight.
  • It works as a classifier and as a label-aware dimension reducer.
  • It gives at most classes − 1 components.
  • Keep it inside a pipeline, because it learns from the labels.

Next: Association Rules and Apriori in Python.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *