library(MASS) # includes linear discriminant function analysis
library(caret) # confusion matrix11.2 Linear discriminant function analysis
Packages
Data
For this exercise, we use the taxonomy dataset from Crawley (2012). It contains seven morphological measurements of 120 plants that belong to four taxa. Our goal is to find out how well these measurements discriminate between the taxa.
taxa <- read.table("data/taxonomy.txt", header = TRUE, stringsAsFactors = TRUE)
head(taxa) Taxon Petals Internode Sepal Bract Petiole Leaf Fruit
1 I 5.621498 29.48060 2.462107 18.20341 11.27910 1.128033 7.876151
2 I 4.994617 28.36025 2.429321 17.65205 11.04084 1.197617 7.025416
3 I 4.767505 27.25432 2.570497 19.40838 10.49072 1.003808 7.817479
4 I 6.299446 25.92424 2.066051 18.37915 11.80182 1.614052 7.672492
5 I 6.489375 25.21131 2.901583 17.31305 10.12159 1.813333 7.758443
6 I 5.785868 25.52433 2.655643 17.07216 10.55816 1.955524 7.880880
The response variable Taxon is a factor with four levels (I, II, III, IV). The seven explanatory variables are Petals, Internode, Sepal, Bract, Petiole, Leaf, and Fruit. Each taxon has 30 observations:
table(taxa$Taxon)
I II III IV
30 30 30 30
Classification models
Classification models predict a categorical response \(Y\), the class, from one or more predictors \(X\). In our example, \(Y\) is the Taxon and \(X\) are the seven morphological measurements. The models estimate the probability that an observation belongs to a class given its predictors, \(Pr[Y \mid X]\). There are two ways to do this (Figure 15.1) (James et al., 2021).
Discriminative models learn where the boundary between the classes lies, without describing the classes themselves. Some, such as logistic regression and neural networks, estimate \(Pr[Y \mid X]\) directly with a probability model. Others, such as support vector machines and random forests, learn the class boundary without a probability model.
Generative models, such as linear discriminant analysis (LDA), quadratic discriminant analysis (QDA), and naive Bayes, take the opposite route. They first describe each class: how the predictors are distributed within it, \(Pr[X \mid Y]\), and how common the class is (its prior probability). A new observation is then assigned to the class that most plausibly produced it, given these distributions and priors (using Bayes’ theorem). Note that, despite its name, linear discriminant analysis is a generative model, not a discriminative one. The name refers to the discriminant functions it uses to separate the classes (see How LDA works).
Because generative models describe how the predictors are distributed in each class, they can be used to simulate data and are often easier to interpret. However, they rely on assumptions about these distributions. LDA, for example, assumes multivariate normally distributed predictors with the same covariance matrix in every class. When such assumptions are violated, discriminative models such as logistic regression can perform better (James et al., 2021).
How LDA works
Linear discriminant analysis (LDA), also called discriminant function analysis (DFA), is a classification method for a categorical response and continuous predictors. It is used for two purposes: to classify observations, e.g., to assign a plant to a taxon based on its measurements, and to describe which predictors separate the classes and how well.
LDA assumes that the observations are independent, that the predictors follow a multivariate normal distribution within each class, and that all classes share the same covariance matrix, i.e., the predictors vary and covary alike in every class (James et al., 2021). The posterior probabilities rely on these assumptions. If the covariance matrices differ clearly between the classes, quadratic discriminant analysis (QDA) is an alternative.
To separate the classes, LDA combines the predictors into new variables, the discriminant functions (LD1, LD2, …). Each function is a weighted sum of the predictors, chosen so that the class means lie as far apart as possible relative to the spread within the classes. The discriminant functions are closely related to the generative model: with equal priors, assigning an observation to the class whose mean is closest in the space of all discriminant functions gives the same result as assigning it to the class with the highest posterior probability (see Classification models). With unequal priors, the prior probabilities must also be taken into account. For classification alone, the discriminant functions are therefore not needed. They are useful to describe and visualize which predictors separate the classes and how well.
Model fitting
We fit the LDA with the lda() function of the MASS package. As in regression, the formula has the form response ~ predictors; the . stands for all variables in taxa other than the response.
lda_model <- lda(Taxon ~ ., data = taxa)The fitted model (lda_model) contains, among others:
prior: the prior probabilities of the classesmeans: the mean of each predictor in each classscaling: the coefficients that turn the predictors into discriminant functionssvd: the singular values, i.e., the ratio of between-class to within-class standard deviation for each discriminant functionN: the number of observationscounts: the number of observations per class
Examine model
By default, the prior probabilities are the class proportions in the training data. Here, all four taxa have 30 cases, so the priors are equal:
lda_model$prior I II III IV
0.25 0.25 0.25 0.25
lda_model$svd[1] 20.589120 9.098563 8.750050
The singular values are analogous to the eigenvalues in principal component analysis (PCA). PCA finds components with maximal variance, whereas LDA finds discriminant functions that separate the classes as well as possible, i.e., with a maximal ratio of between-class to within-class standard deviation. The squared singular values are the ratios of between-class to within-class variance, i.e., the separation achieved by each discriminant function. Relative to their sum, they give each function’s share of the total separation, which the model printout below calls the “proportion of trace”:
lda_model$svd^2 / sum(lda_model$svd^2)[1] 0.7267985 0.1419332 0.1312682
Hence, the first discriminant function (LD1) accounts for 72.7% of the total separation between the taxa. Printing the model object gives an overview of all results:
lda_modelCall:
lda(Taxon ~ ., data = taxa)
Prior probabilities of groups:
I II III IV
0.25 0.25 0.25 0.25
Group means:
Petals Internode Sepal Bract Petiole Leaf Fruit
I 5.476128 27.91886 2.537955 18.60268 10.864184 1.508029 7.574642
II 7.035078 27.69834 2.490336 18.47557 8.541085 1.450260 7.418702
III 6.849666 27.99308 2.446003 18.26330 9.866983 2.588555 7.482349
IV 6.768464 27.78503 4.532560 18.42953 10.128838 1.645945 7.467917
Coefficients of linear discriminants:
LD1 LD2 LD3
Petals -0.01891137 -0.034749952 -0.559080267
Internode 0.03374178 -0.009670875 -0.008808043
Sepal 3.45605170 0.500418135 -0.401274694
Bract 0.07557480 -0.068774714 0.024930728
Petiole 0.25041949 0.343892260 1.249519047
Leaf -1.13036429 3.008335468 -0.647932763
Fruit 0.18285691 0.208370808 0.269924935
Proportion of trace:
LD1 LD2 LD3
0.7268 0.1419 0.1313
LDA extracts at most as many discriminant functions as the smaller of the number of classes minus one and the number of predictors (Venables and Ripley, 2002); here min(4 − 1, 7) = 3: LD1–LD3. The scaling coefficients show that LD1 is driven mainly by Sepal and LD2 by Leaf. The coefficients depend on the units of the predictors, so their size alone does not measure importance; here, standardized coefficients lead to the same conclusion. A plot of Sepal against Leaf shows how the taxa separate along these two predictors:
plot(taxa$Sepal, taxa$Leaf, type = "n", xlab = "Sepal", ylab = "Leaf")
text(taxa$Sepal, taxa$Leaf, labels = as.character(taxa$Taxon),
col = as.numeric(taxa$Taxon))
Model output
The predict() function applies the fitted model to data. Without new data, it predicts the training data. It returns a list with three components (see ?predict.lda):
class: the predicted class, i.e., the class with the highest posterior probabilityposterior: the posterior probability of each classx: the scores of each observation on the discriminant functions
lda_prediction <- predict(lda_model)
lda_prediction$class [1] I I I I I I I I I I I I I I I I I I
[19] I I III I I I I I I I I I II II II II II II
[37] II II II II II II II II II II II II II II II II II II
[55] II II II II II II III III III III III III III III III III III III
[73] III III III III III III III III III III III III III III III III III III
[91] IV IV IV IV IV IV IV IV IV IV IV IV IV IV IV IV IV IV
[109] IV IV IV IV IV IV IV IV IV IV IV IV
Levels: I II III IV
Combining the posterior probabilities with the predicted class shows that each observation is assigned to the class with the highest posterior probability:
data.frame(round(lda_prediction$posterior, 4), class = lda_prediction$class) I II III IV class
1 1.0000 0.0000 0.0000 0 I
2 0.9999 0.0001 0.0000 0 I
3 0.9997 0.0003 0.0000 0 I
4 0.9994 0.0000 0.0005 0 I
5 0.8825 0.0639 0.0536 0 I
6 0.9113 0.0019 0.0868 0 I
7 0.9452 0.0538 0.0010 0 I
8 0.9962 0.0028 0.0010 0 I
9 0.9338 0.0613 0.0049 0 I
10 1.0000 0.0000 0.0000 0 I
11 1.0000 0.0000 0.0000 0 I
12 0.9991 0.0004 0.0005 0 I
13 0.9988 0.0010 0.0003 0 I
14 1.0000 0.0000 0.0000 0 I
15 0.9212 0.0012 0.0776 0 I
16 1.0000 0.0000 0.0000 0 I
17 0.9996 0.0004 0.0000 0 I
18 0.9923 0.0005 0.0071 0 I
19 1.0000 0.0000 0.0000 0 I
20 0.9994 0.0006 0.0000 0 I
21 0.1829 0.1430 0.6741 0 III
22 0.9987 0.0013 0.0000 0 I
23 0.9972 0.0000 0.0028 0 I
24 0.9999 0.0000 0.0000 0 I
25 0.9892 0.0108 0.0000 0 I
26 0.9904 0.0002 0.0093 0 I
27 0.9964 0.0036 0.0001 0 I
28 0.9872 0.0027 0.0101 0 I
29 0.9028 0.0097 0.0875 0 I
30 1.0000 0.0000 0.0000 0 I
31 0.0001 0.9998 0.0001 0 II
32 0.0189 0.9810 0.0000 0 II
33 0.0005 0.9995 0.0001 0 II
34 0.0002 0.9998 0.0000 0 II
35 0.0418 0.9428 0.0154 0 II
36 0.0000 1.0000 0.0000 0 II
37 0.0027 0.9973 0.0000 0 II
38 0.1371 0.4889 0.3740 0 II
39 0.0046 0.9954 0.0000 0 II
40 0.0000 1.0000 0.0000 0 II
41 0.4450 0.5340 0.0210 0 II
42 0.0000 1.0000 0.0000 0 II
43 0.0004 0.9993 0.0002 0 II
44 0.0000 0.9991 0.0009 0 II
45 0.0747 0.5867 0.3386 0 II
46 0.0001 0.9999 0.0000 0 II
47 0.0000 1.0000 0.0000 0 II
48 0.0000 1.0000 0.0000 0 II
49 0.1831 0.7612 0.0557 0 II
50 0.0000 0.9963 0.0037 0 II
51 0.0006 0.9990 0.0004 0 II
52 0.0550 0.9450 0.0000 0 II
53 0.0266 0.9392 0.0342 0 II
54 0.0040 0.9944 0.0017 0 II
55 0.0000 0.9986 0.0014 0 II
56 0.0063 0.9588 0.0349 0 II
57 0.0002 0.9907 0.0090 0 II
58 0.0011 0.9975 0.0014 0 II
59 0.0129 0.9861 0.0010 0 II
60 0.0000 1.0000 0.0000 0 II
61 0.0786 0.0014 0.9200 0 III
62 0.0000 0.0001 0.9999 0 III
63 0.0078 0.1462 0.8461 0 III
64 0.1081 0.0375 0.8543 0 III
65 0.0005 0.0051 0.9944 0 III
66 0.0013 0.0002 0.9986 0 III
67 0.0001 0.0004 0.9995 0 III
68 0.0000 0.0000 1.0000 0 III
69 0.0916 0.0023 0.9061 0 III
70 0.0000 0.0000 1.0000 0 III
71 0.0020 0.0003 0.9978 0 III
72 0.0000 0.0000 1.0000 0 III
73 0.0000 0.0000 1.0000 0 III
74 0.0188 0.1651 0.8161 0 III
75 0.0037 0.1235 0.8728 0 III
76 0.0008 0.0089 0.9903 0 III
77 0.0002 0.0000 0.9997 0 III
78 0.0000 0.0000 1.0000 0 III
79 0.0000 0.0008 0.9992 0 III
80 0.0001 0.0000 0.9999 0 III
81 0.0000 0.0000 1.0000 0 III
82 0.0008 0.0000 0.9992 0 III
83 0.0000 0.0002 0.9998 0 III
84 0.0000 0.0011 0.9989 0 III
85 0.0000 0.0000 1.0000 0 III
86 0.0000 0.0000 1.0000 0 III
87 0.0000 0.0018 0.9982 0 III
88 0.0001 0.0000 0.9999 0 III
89 0.0115 0.0020 0.9865 0 III
90 0.0000 0.0000 1.0000 0 III
91 0.0000 0.0000 0.0000 1 IV
92 0.0000 0.0000 0.0000 1 IV
93 0.0000 0.0000 0.0000 1 IV
94 0.0000 0.0000 0.0000 1 IV
95 0.0000 0.0000 0.0000 1 IV
96 0.0000 0.0000 0.0000 1 IV
97 0.0000 0.0000 0.0000 1 IV
98 0.0000 0.0000 0.0000 1 IV
99 0.0000 0.0000 0.0000 1 IV
100 0.0000 0.0000 0.0000 1 IV
101 0.0000 0.0000 0.0000 1 IV
102 0.0000 0.0000 0.0000 1 IV
103 0.0000 0.0000 0.0000 1 IV
104 0.0000 0.0000 0.0000 1 IV
105 0.0000 0.0000 0.0000 1 IV
106 0.0000 0.0000 0.0000 1 IV
107 0.0000 0.0000 0.0000 1 IV
108 0.0000 0.0000 0.0000 1 IV
109 0.0000 0.0000 0.0000 1 IV
110 0.0000 0.0000 0.0000 1 IV
111 0.0000 0.0000 0.0000 1 IV
112 0.0000 0.0000 0.0000 1 IV
113 0.0000 0.0000 0.0000 1 IV
114 0.0000 0.0000 0.0000 1 IV
115 0.0000 0.0000 0.0000 1 IV
116 0.0000 0.0000 0.0000 1 IV
117 0.0000 0.0000 0.0000 1 IV
118 0.0000 0.0000 0.0000 1 IV
119 0.0000 0.0000 0.0000 1 IV
120 0.0000 0.0000 0.0000 1 IV
The scores in x are the coordinates of the observations on the discriminant functions, i.e., the predictors transformed into the new LD axes:
head(lda_prediction$x) LD1 LD2 LD3
1 -0.6240211 -1.6810963 3.0303236
2 -1.0988293 -1.6768377 2.8176493
3 -0.2850537 -2.3155720 2.5934923
4 -2.5680633 -0.2811099 3.1292050
5 -0.4189485 0.2502168 0.4620391
6 -1.2922825 0.7685348 1.4317043
Plotting the scores shows how well the discriminant functions separate the classes. ldahist() draws one histogram of the scores per taxon, stacked on top of each other, here for LD1:
ldahist(data = lda_prediction$x[, 1], g = taxa$Taxon)
Taxon IV has clearly higher LD1 scores than the other taxa and does not overlap with them, so LD1 alone separates IV. Taxa I, II, and III overlap on LD1, so LD1 cannot tell them apart.
Plotting the model object draws scatterplots of the scores for each pair of discriminant functions. They show how the other taxa are separated: LD2 separates III from I and II, and LD3 separates I from the other taxa.
plot(lda_model, col = as.numeric(taxa$Taxon))
Training error
To check how well the model fits the training data, we cross-tabulate the predicted and observed taxa in a confusion matrix (see Classification accuracy):
conf <- table(list(predicted = lda_prediction$class, observed = taxa$Taxon))
conf observed
predicted I II III IV
I 29 0 0 0
II 0 30 0 0
III 1 0 30 0
IV 0 0 0 30
We can calculate precision and recall with simple matrix arithmetic:
# Precision
diag(conf) / rowSums(conf) I II III IV
1.0000000 1.0000000 0.9677419 1.0000000
# Recall
diag(conf) / colSums(conf) I II III IV
0.9666667 1.0000000 1.0000000 1.0000000
The confusionMatrix() function of the caret package (Kuhn, 2026) calculates these and further measures at once:
confusionMatrix(conf)Confusion Matrix and Statistics
observed
predicted I II III IV
I 29 0 0 0
II 0 30 0 0
III 1 0 30 0
IV 0 0 0 30
Overall Statistics
Accuracy : 0.9917
95% CI : (0.9544, 0.9998)
No Information Rate : 0.25
P-Value [Acc > NIR] : < 2.2e-16
Kappa : 0.9889
Mcnemar's Test P-Value : NA
Statistics by Class:
Class: I Class: II Class: III Class: IV
Sensitivity 0.9667 1.00 1.0000 1.00
Specificity 1.0000 1.00 0.9889 1.00
Pos Pred Value 1.0000 1.00 0.9677 1.00
Neg Pred Value 0.9890 1.00 1.0000 1.00
Prevalence 0.2500 0.25 0.2500 0.25
Detection Rate 0.2417 0.25 0.2500 0.25
Detection Prevalence 0.2417 0.25 0.2583 0.25
Balanced Accuracy 0.9833 1.00 0.9944 1.00
confusionMatrix() reports recall as Sensitivity and precision as Pos Pred Value. The other per-class statistics are based on the same one-class-versus-all comparison:
- Specificity: share of the other classes’ cases not assigned to the class, TN / (TN + FP)
- Neg Pred Value: share of cases not assigned to the class that truly belong to another class, TN / (TN + FN)
- Prevalence: observed share of the class, column total / N
- Detection Rate: correctly classified cases of the class as a share of all cases, TP / N
- Detection Prevalence: predicted share of the class, row total / N
- Balanced Accuracy: (Sensitivity + Specificity) / 2
Specificity, Neg Pred Value and Balanced Accuracy come from two-class problems. With several classes, TN is large for every class, so Specificity and Neg Pred Value are close to 1, and Balanced Accuracy is pushed upward by Specificity. They add little information. The output also includes Cohen’s Kappa, which is no longer recommended for accuracy assessment (Foody, 2020).
Test error
The measures above describe the training error, which is too optimistic (see The bias-variance trade-off). To estimate the test error, each observation must be predicted by a model that has not seen it. The lda() function does this with leave-one-out cross-validation (LOOCV) when we set CV = TRUE. It then returns the cross-validated predicted classes and posterior probabilities instead of a fitted model:
lda_cv <- lda(Taxon ~ ., data = taxa, CV = TRUE)
conf_cv <- table(list(predicted = lda_cv$class, observed = taxa$Taxon))
confusionMatrix(conf_cv)Confusion Matrix and Statistics
observed
predicted I II III IV
I 29 1 0 0
II 0 28 0 0
III 1 1 30 0
IV 0 0 0 30
Overall Statistics
Accuracy : 0.975
95% CI : (0.9287, 0.9948)
No Information Rate : 0.25
P-Value [Acc > NIR] : < 2.2e-16
Kappa : 0.9667
Mcnemar's Test P-Value : NA
Statistics by Class:
Class: I Class: II Class: III Class: IV
Sensitivity 0.9667 0.9333 1.0000 1.00
Specificity 0.9889 1.0000 0.9778 1.00
Pos Pred Value 0.9667 1.0000 0.9375 1.00
Neg Pred Value 0.9889 0.9783 1.0000 1.00
Prevalence 0.2500 0.2500 0.2500 0.25
Detection Rate 0.2417 0.2333 0.2500 0.25
Detection Prevalence 0.2500 0.2333 0.2667 0.25
Balanced Accuracy 0.9778 0.9667 0.9889 1.00
With cross-validation, three of the 120 plants are misclassified instead of one, and the overall accuracy drops from 99.2% to 97.5%. One plant of taxon I is predicted as III, and two plants of taxon II are predicted as I and III. Taxon IV is still classified without error. Accordingly, recall is lowest for taxon II (28 of 30 = 0.93), and precision is lowest for taxon III (30 of 32 = 0.94). The 95% confidence interval of the accuracy is 0.93–0.99. Overall, the seven measurements discriminate the four taxa very well, also for plants not used to fit the model.
In a report, the results could be summarized as follows:
We classified the four taxa with linear discriminant analysis (LDA) using seven morphological variables (n = 120; 30 plants per taxon). Classification accuracy was assessed with leave-one-out cross-validation. The overall accuracy was 97.5% (95% CI: 92.9–99.5%), with 117 of 120 plants classified correctly. Taxon IV was classified without error. Recall ranged from 93.3% (taxon II) to 100% (taxa III and IV), and precision from 93.8% (taxon III) to 100% (taxa II and IV). The first discriminant function accounted for 72.7% of the separation between the taxa and separated taxon IV from the other taxa.