<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/linear-discriminant-analysis-in-r-an-introduction/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://www.displayr.com/linear-discriminant-analysis-in-r-an-introduction/?utm_medium=Feed&utm_source=Syndication"> R – Displayr</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>How does Linear Discriminant Analysis work and how do you use it in R? This post answers these questions and provides an introduction to Linear Discriminant Analysis.</p>
<p><em>Linear Discriminant Analysis</em> (LDA) is a well-established machine learning technique for predicting categories. Its main advantages, compared to other classification algorithms such as neural networks and random forests, are that the model is interpretable and that prediction is easy.</p>
<hr>
<h2> <span>The intuition behind Linear Discriminant Analysis</span></h2>
<p>Linear Discriminant Analysis takes a data set of <em>cases</em> (also known as <em>observations</em>) as input. For each case, you need to have a <em>categorical variable</em> to define the <em>class</em> and several <em>predictor variables </em>(which are numeric). We often visualize this input data as a <em>matrix, </em>such as shown below, with each case being a row and each variable a column. In this example, the categorical variable is called “class” and the predictive variables (which are numeric) are the other columns.</p>
<p> <iframe width="450" src="https://embedded.azureedge.net/75668/233184/b198d1a5-0834-44fc-8b21-b5545c5cdc2a.html?v=29307-9149945026-423807299"></iframe></p>
<hr>
<p>Think of each case as a point in N-dimensional space, where N is the number of predictor variables. Every point is labeled by its category. (Although it focuses on <a rel="nofollow" href="https://www.displayr.com/using-t-sne-to-visualize-data-before-prediction/" target="_blank">t-SNE</a>, this <a rel="nofollow" href="https://experiments.withgoogle.com/ai/visualizing-high-dimensional-space" target="_blank">video</a> neatly illustrates what we mean by <em>dimensional space</em>).</p>
<p>The LDA algorithm uses this data to divide the space of predictor variables into <em>regions</em>. The regions are labeled by categories and have linear boundaries, hence the “L” in LDA. The model predicts the category of a new unseen case according to which region it lies in. The model predicts that all cases within a region belong to the same category.</p>
<p>The linear boundaries are a consequence of assuming that the predictor variables for each category have the same <em>multivariate Gaussian distribution</em>. Although in practice this assumption may not be 100% true, if it is approximately valid then LDA can still perform well.</p>
<p>Mathematically, LDA uses the input data to derive the <em>coefficients</em> of a <em>scoring function</em> for each category. Each function takes as arguments the numeric predictor variables of a case. It then scales each variable according to its category-specific coefficients and outputs a score. The LDA model looks at the score from each function and uses the highest score to allocate a case to a category (prediction). We call these scoring functions the <em>discriminant functions</em>.</p>
<p>I am going to stop with the model described here and go into some practical examples. If you would like more detail, I suggest one of my favorite reads, <a rel="nofollow" href="https://web.stanford.edu/~hastie/Papers/ESLII.pdf" target="_blank">Elements of Statistical Learning</a> (section 4.3).</p>
<hr>
<h2> Linear Discriminant Analysis Example</h2>
<h3>Predicting the type of vehicle</h3>
<p>Even though my eyesight is far from perfect, I can normally tell the difference between a car, a van, and a bus. I might not distinguish a Saab 9000 from an Opel Manta though. They are cars made around 30 years ago (I can’t remember!). Despite my unfamiliarity, I would hope to do a decent job if given a few examples of both.</p>
<p>I will demonstrate Linear Discriminant Analysis by predicting the type of vehicle in an image. The 4 vehicle categories are a double-decker bus, Chevrolet van, Saab 9000 and Opel Manta 400. The input features are not the raw image pixels but are 18 numerical features calculated from silhouettes of the vehicles. You can read more about the data behind this <a rel="nofollow" href="https://archive.ics.uci.edu/ml/datasets/Statlog+(Vehicle+Silhouettes)" target="_blank">LDA example here</a>.</p>
<p>To start, I load the 846 instances into a <em>data.frame</em> called <em>vehicles</em>. The columns are labeled by the variables, with the target outcome column called <em>class</em>. The earlier table shows this data.</p>
<hr>
<h2><span><em>flipMultivariates: </em>A new R package</span></h2>
<p>The package I am going to use is called <a rel="nofollow" href="https://github.com/Displayr/flipMultivariates" target="_blank"><em>flipMultivariates</em></a> (click on the link to get it). It is based on the <em>MASS</em> package, but extends it in the following ways:</p>
<ul>
<li>Handling of weighted data</li>
<li>Graphical outputs</li>
<li>Options for missing data</li>
<li>Ability to output discriminant functions</li>
</ul>
<p>The package is installed with the following R code.</p>
<pre>
library(devtools)
install_github(&quot;Displayr/flipStandardCharts&quot;)
</pre>
<p>Then the model is created with the following two lines of code.</p>
<pre>
library(flipMultivariates)
lda &lt;- LDA(class ~ ., data = vehicles)
</pre>
<hr>
<p>The output is shown below. The subtitle shows that the model identifies buses and vans well but struggles to tell the difference between the two car models. The first four columns show the means for each variable by category. High values are shaded in blue ad low values in red, with values significant at the 5% level in bold. The <em>R-Squared</em> column shows the proportion of variance within each row that is explained by the categories. On this measure, <em>ELONGATEDNESS</em> is the best discriminator.</p>
<p> <iframe width="450" src="https://embedded.azureedge.net/75668/233184/bb4f91c0-67da-40fe-8f52-8440112606cb.html?v=29307-9149945026353112978"></iframe>
</p>
<hr>
<h2> <span>Customizing the LDA model with alternative inputs in the code</span></h2>
<p>The <em>LDA</em> function in <em>flipMultivariates</em> has a lot more to offer than just the default. Consider the code below:</p>
<pre>
lda.2 &lt;- LDA(class ~ COMPACTNESS + CIRCULARITY + DISTANCE.CIRCULARITY + RADIUS.RATIO,
 data = vehicles,
 output = &quot;Scatterplot&quot;,
 prior = &quot;Equal&quot;,
 subset = vehicles$ELONGATEDNESS &lt; 50,
 weight = ifelse(vehicles$class == &quot;saab&quot;, 2, 1))
</pre>
<p>I’ve set a few new arguments, which include;</p>
<ul>
<li><span>output</span>
<ul>
<li>The default output is <span>Means</span><em>, </em>which is what you got in the very first output. In the code immediately above, I changed this to be <span>Scatterplot</span>.<em> </em>I explain how to interpret the <em>scatterplot</em> in the next section. Also available are <span>Prediction-Accuracy Table, Detail <span>and</span> Discriminant Functions.</span> The latter produces a table of the coefficients of the <em>discriminant functions</em> described earlier.</li>
</ul>
</li>
<li><span>prior</span>
<ul>
<li>This argument sets the prior probabilities of category membership. <span>Observed </span>is the default, which uses the frequencies of the input data. It is also possible to specify values for each category as a vector (which naturally sum to 1). <span>Equal </span>implies that vehicles are equally distributed across the categories.</li>
</ul>
</li>
<li><span>subset</span>
<ul>
<li>This<em> </em>is a vector of <span>TRUE/FALSE</span>, which in the code above limits the analysis to cases with lower <em>ELONGATEDNESS </em>(less than scores of 50 on that numeric predictor variable)</li>
</ul>
</li>
<li><span>weight</span>
<ul>
<li>This<em> </em>is a vector of values used to scale the cases. In this example, I overweight the <em>saab</em> cars.</li>
</ul>
</li>
</ul>
<p>It is also possible to control treatment of missing variables with the <span>missing </span>argument (not shown in the code example above). The options are <span><span>Exclude cases with missing</span></span><span><span> data </span>(default), </span><span><span>Error if missing data </span>and </span><span><span>Imputation (replace missing values with estimates)</span><em>. </em>Imputation allows the user to specify additional variables (which the model uses to estimate replacements for missing data points). </span></p>
<p>The R command <span>?LDA</span> gives more information on all of the arguments.</p>
<hr>
<h2><span>Interpreting the </span>Linear Discriminant Analysis <span>output</span></h2>
<p>The previous block of code above produces the following scatterplot. (Note: I am no longer using all the predictor variables in the example below, for the sake of clarity). I am going to talk about two aspects of interpreting the scatterplot: how each dimension separates the categories, and how the predictor variables correlate with the dimensions.</p>
<p> <iframe src="https://embedded.azureedge.net/75668/233184/b7d49027-1c1b-4448-93de-1450b535098c.html?v=29307-9149945026-1372884388" width="448.127" height="403.0317"></iframe></p>
<p>I said above that I would stop writing about the model. However, to explain the scatterplot I am going to have to mention a few more points about the algorithm. If you prefer to gloss over this, please skip ahead.</p>
<hr>
<p>An alternative view of linear discriminant analysis is that it projects the data into a space of (number of categories – 1) dimensions. In this example that space has 3 dimensions (4 vehicle categories minus one). While this aspect of dimension reduction has some similarity to <em>Principal Components Analysis</em> (PCA), there is a difference. The difference from PCA is that LDA chooses dimensions that maximally separate the categories (in the transformed space). The LDA model orders the dimensions in terms of how much separation each achieves (the first dimensions achieves the most separation, and so forth). Hence the scatterplot shows the means of each category plotted in the first two dimensions of this space. So in our example here, the first dimension (the horizontal axis) distinguishes the cars (right) from the <em>bus</em> and<em> van </em>categories (left)<em>. </em>However, the same dimension does not separate the cars well.</p>
<p>Also shown are the correlations between the predictor variables and these new dimensions. Because DISTANCE.CIRCULARITY has a high value along the first linear discriminant it positively correlates with this first dimension. It has a value of almost zero along the second linear discriminant, hence is virtually uncorrelated with the second dimension. Note the scatterplot scales the correlations to appear on the same scale as the means. So you can’t just read their values from the axis. In other words, the means are the primary data, whereas the scatterplot adjusts the correlations to “fit” on the chart.</p>
<hr>
<h2> <span>The Prediction-Accuracy Table</span></h2>
<p>Finally, I will leave you with this chart to consider the model’s <em>accuracy</em>. Changing the <span>output </span>argument in the code above to<span> <em>Prediction-Accuracy Table</em></span> produces the following:</p>
<p><iframe width="450" src="https://embedded.azureedge.net/75668/233184/b2fdbf15-44e9-4480-9a33-592f545622b5.html?v=29307-91499450262104602962"></iframe>
</p>
<p>So from this, you can see what the model gets right and wrong (in terms of correctly predicting the class of vehicle). The ideal is for all the cases to lie on the diagonal of this matrix (and so the diagonal is a deep color in terms of shading). But here we are getting some misallocations (no model is ever perfect). For instance, 19 cases that the model predicted as <em>Opel</em> are actually in the <em>bus</em> category (observed). Given the shades of red and the numbers that lie outside this diagonal (particularly with respect to the confusion between <em>Opel</em> and <em>saab</em>) this LDA model is far from perfect.</p>
<hr>
<h2></h2>
<h2><span>Try it yourself</span></h2>
<p>I created the analyses in this post with R in Displayr. You can review the underlying data and code or <a rel="nofollow" href="https://app.displayr.com/Try/Linear%20Discriminant%20Analysis" target="_blank">run your own LDA analyses here</a> (just sign into Displayr first). I used the <span>flipMultivariates<span> package (<a rel="nofollow" href="https://github.com/Displayr/flipDimensionReduction" target="_blank">available on GitHub</a>).</span></span></p>
<p>Displayr also makes Linear Discriminant Analysis and other machine learning tools available through menus, alleviating the need to write code.</p>
<p>This dataset originates from the Turing Institute, Glasgow, Scotland, which closed in 1994 so I doubt they care, but I’m crediting the source anyway.</p>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://www.displayr.com/linear-discriminant-analysis-in-r-an-introduction/?utm_medium=Feed&utm_source=Syndication"> R – Displayr</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/4PYdNeurKTk" height="1"></a></div>