<?xml version="1.0" encoding="UTF-8" ?>
<!-- RSS generated by PHPBoost on Sun, 26 Apr 2026 01:34:59 +0200 -->

<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
	<channel>
		<title><![CDATA[Last articles - STHDA : Classification Methods Essentials]]></title>
		<atom:link href="https://www.sthda.com/english/syndication/rss/articles/36" rel="self" type="application/rss+xml"/>
		<link>https://www.sthda.com</link>
		<description><![CDATA[Last articles - STHDA : Classification Methods Essentials]]></description>
		<copyright>(C) 2005-2026 PHPBoost</copyright>
		<language>en</language>
		<generator>PHPBoost</generator>
		
		
		<item>
			<title><![CDATA[Logistic Regression Essentials in R]]></title>
			<link>https://www.sthda.com/english/articles/36-classification-methods-essentials/151-logistic-regression-essentials-in-r/</link>
			<guid>https://www.sthda.com/english/articles/36-classification-methods-essentials/151-logistic-regression-essentials-in-r/</guid>
			<description><![CDATA[<!-- START HTML -->

  <div id="rdoc">





<p><strong>Logistic regression</strong> is used to predict the class (or category) of individuals based on one or multiple predictor variables (x). It is used to model a binary outcome, that is a variable, which can have only two possible values: 0 or 1, yes or no, diseased or non-diseased.</p>
<p>Logistic regression belongs to a family, named <em>Generalized Linear Model</em> (<em>GLM</em>), developed for extending the linear regression model (Chapter @ref(linear-regression)) to other situations. Other synonyms are <em>binary logistic regression</em>, <em>binomial logistic regression</em> and <em>logit model</em>.</p>
<p>Logistic regression does not return directly the class of observations. It allows us to estimate the probability (p) of class membership. The probability will range between 0 and 1. You need to decide the threshold probability at which the category flips from one to the other. By default, this is set to <code>p = 0.5</code>, but in reality it should be settled based on the analysis purpose.</p>
<p>In this chapter you’ll learn how to:</p>
<ul>
<li>Define the logistic regression equation and key terms such as log-odds and logit</li>
<li>Perform logistic regression in <strong>R</strong> and interpret the results</li>
<li>Make predictions on new test data and evaluate the model accuracy</li>
</ul>
<p>Contents:</p>
<div id="TOC">
<ul>
<li><a href="#logistic-function">Logistic function</a></li>
<li><a href="#loading-required-r-packages">Loading required R packages</a></li>
<li><a href="#preparing-the-data">Preparing the data</a></li>
<li><a href="#computing-logistic-regression">Computing logistic regression</a><ul>
<li><a href="#quick-start-r-code">Quick start R code</a></li>
<li><a href="#simple-logistic-regression">Simple logistic regression</a></li>
<li><a href="#multiple-logistic-regression">Multiple logistic regression</a></li>
</ul></li>
<li><a href="#interpretation">Interpretation</a></li>
<li><a href="#making-predictions">Making predictions</a></li>
<li><a href="#assessing-model-accuracy">Assessing model accuracy</a></li>
<li><a href="#discussion">Discussion</a></li>
<li><a href="#references">References</a></li>
</ul>
</div>
<br/>
<div class = "small-block content-privileged-friends navr-book">
  <p>The Book:</p>
        <a href = "https://www.sthda.com/english/web/5-bookadvisor/54-machine-learning-essentials/">
          <img src = "https://www.sthda.com/english/upload/machine-learning-essentials-frontcover-200px.png" /><br/>
     Machine Learning Essentials: Practical Guide in R
      </a>
</div>
<div class="spacer"></div>


<div id="logistic-function" class="section level2">
<h2>Logistic function</h2>
<p>The standard logistic regression function, for predicting the outcome of an observation given a predictor variable (x), is an s-shaped curve defined as <code>p = exp(y) / [1 + exp(y)]</code> <span class="citation">(James et al. 2014)</span>. This can be also simply written as <code>p = 1/[1 + exp(-y)]</code>, where:</p>
<ul>
<li><code>y = b0 + b1*x</code>,</li>
<li><code>exp()</code> is the exponential and</li>
<li><code>p</code> is the probability of event to occur (1) given <code>x</code>. Mathematically, this is written as <code>p(event=1|x) and abbreviated as</code>p(x)<code>, so</code>px = 1/[1 + exp(-(b0 + b1*x))]`</li>
</ul>
<p>By a bit of manipulation, it can be demonstrated that <code>p/(1-p) = exp(b0 + b1*x)</code>. By taking the logarithm of both sides, the formula becomes a linear combination of predictors: <code>log[p/(1-p)] = b0 + b1*x</code>.</p>
<p>When you have multiple predictor variables, the logistic function looks like: <code>log[p/(1-p)] = b0 + b1*x1 + b2*x2 + ... + bn*xn</code></p>
<p><code>b0</code> and <code>b1</code> are the regression beta coefficients. A positive <code>b1</code> indicates that increasing <code>x</code> will be associated with increasing <code>p</code>. Conversely, a negative <code>b1</code> indicates that increasing <code>x</code> will be associated with decreasing <code>p</code>.</p>
<p>The quantity <code>log[p/(1-p)]</code> is called the logarithm of the odd, also known as <strong>log-odd</strong> or <strong>logit</strong>.</p>
<p>The <strong>odds</strong> reflect the likelihood that the event will occur. It can be seen as the ratio of “successes” to “non-successes”. Technically, odds are the probability of an event divided by the probability that the event will not take place <span class="citation">(P. Bruce and Bruce 2017)</span>. For example, if the probability of being diabetes-positive is 0.5, the probability of “won’t be” is 1-0.5 = 0.5, and the odds are 1.0.</p>
<p>Note that, the probability can be calculated from the odds as <code>p = Odds/(1 + Odds)</code>.</p>
</div>
<div id="loading-required-r-packages" class="section level2">
<h2>Loading required R packages</h2>
<ul>
<li><code>tidyverse</code> for easy data manipulation and visualization</li>
<li><code>caret</code> for easy machine learning workflow</li>
</ul>
<pre class="r"><code>library(tidyverse)
library(caret)
theme_set(theme_bw())</code></pre>
</div>
<div id="preparing-the-data" class="section level2">
<h2>Preparing the data</h2>
<p>Logistic regression works for a data that contain continuous and/or categorical predictor variables.</p>
<p>Performing the following steps might improve the accuracy of your model</p>
<ul>
<li>Remove potential outliers</li>
<li>Make sure that the predictor variables are normally distributed. If not, you can use log, root, Box-Cox transformation.</li>
<li>Remove highly correlated predictors to minimize overfitting. The presence of highly correlated predictors might lead to an unstable model solution.</li>
</ul>
<p>Here, we’ll use the <code>PimaIndiansDiabetes2</code> [in <code>mlbench</code> package], introduced in Chapter @ref(classification-in-r), for predicting the probability of being diabetes positive based on multiple clinical variables.</p>
<p>We’ll randomly split the data into training set (80% for building a predictive model) and test set (20% for evaluating the model). Make sure to set seed for reproducibility.</p>
<pre class="r"><code># Load the data and remove NAs
data("PimaIndiansDiabetes2", package = "mlbench")
PimaIndiansDiabetes2 <- na.omit(PimaIndiansDiabetes2)
# Inspect the data
sample_n(PimaIndiansDiabetes2, 3)
# Split the data into training and test set
set.seed(123)
training.samples <- PimaIndiansDiabetes2$diabetes %>% 
  createDataPartition(p = 0.8, list = FALSE)
train.data  <- PimaIndiansDiabetes2[training.samples, ]
test.data <- PimaIndiansDiabetes2[-training.samples, ]</code></pre>
</div>
<div id="computing-logistic-regression" class="section level2">
<h2>Computing logistic regression</h2>
<p>The R function <code>glm()</code>, for generalized linear model, can be used to compute logistic regression. You need to specify the option <code>family = binomial</code>, which tells to R that we want to fit logistic regression.</p>
<div id="quick-start-r-code" class="section level3">
<h3>Quick start R code</h3>
<pre class="r"><code># Fit the model
model <- glm( diabetes ~., data = train.data, family = binomial)
# Summarize the model
summary(model)
# Make predictions
probabilities <- model %>% predict(test.data, type = "response")
predicted.classes <- ifelse(probabilities > 0.5, "pos", "neg")
# Model accuracy
mean(predicted.classes == test.data$diabetes)</code></pre>
</div>
<div id="simple-logistic-regression" class="section level3">
<h3>Simple logistic regression</h3>
<p>The simple logistic regression is used to predict the probability of class membership based on one single predictor variable.</p>
<p>The following R code builds a model to predict the probability of being diabetes-positive based on the plasma glucose concentration:</p>
<pre class="r"><code>model <- glm( diabetes ~ glucose, data = train.data, family = binomial)
summary(model)$coef</code></pre>
<pre><code>##             Estimate Std. Error z value Pr(>|z|)
## (Intercept)  -6.3267     0.7241   -8.74 2.39e-18
## glucose       0.0437     0.0054    8.09 6.01e-16</code></pre>
<p>The output above shows the estimate of the regression beta coefficients and their significance levels. The intercept (<code>b0</code>) is -6.32 and the coefficient of glucose variable is 0.043.</p>
<p>The logistic equation can be written as <code>p = exp(-6.32 + 0.043*glucose)/ [1 + exp(-6.32 + 0.043*glucose)]</code>. Using this formula, for each new glucose plasma concentration value, you can predict the probability of the individuals in being diabetes positive.</p>
<p>Predictions can be easily made using the function <code>predict()</code>. Use the option type = “response” to directly obtain the probabilities</p>
<pre class="r"><code>newdata <- data.frame(glucose = c(20,  180))
probabilities <- model %>% predict(newdata, type = "response")
predicted.classes <- ifelse(probabilities > 0.5, "pos", "neg")
predicted.classes</code></pre>
<p>The logistic function gives an s-shaped probability curve illustrated as follow:</p>
<pre class="r"><code>train.data %>%
  mutate(prob = ifelse(diabetes == "pos", 1, 0)) %>%
  ggplot(aes(glucose, prob)) +
  geom_point(alpha = 0.2) +
  geom_smooth(method = "glm", method.args = list(family = "binomial")) +
  labs(
    title = "Logistic Regression Model", 
    x = "Plasma Glucose Concentration",
    y = "Probability of being diabete-pos"
    )</code></pre>
<p><img src="https://www.sthda.com/english/sthda-upload/figures/machine-learning-essentials/027-logistic-regression-probabilities-curve-1.png" width="384" /></p>
</div>
<div id="multiple-logistic-regression" class="section level3">
<h3>Multiple logistic regression</h3>
<p>The multiple logistic regression is used to predict the probability of class membership based on multiple predictor variables, as follow:</p>
<pre class="r"><code>model <- glm( diabetes ~ glucose + mass + pregnant, 
                data = train.data, family = binomial)
summary(model)$coef</code></pre>
<p>Here, we want to include all the predictor variables available in the data set. This is done using <code>~.</code>:</p>
<pre class="r"><code>model <- glm( diabetes ~., data = train.data, family = binomial)
summary(model)$coef</code></pre>
<pre><code>##             Estimate Std. Error z value Pr(>|z|)
## (Intercept) -9.50372    1.31719  -7.215 5.39e-13
## pregnant     0.04571    0.06218   0.735 4.62e-01
## glucose      0.04230    0.00657   6.439 1.20e-10
## pressure    -0.00700    0.01291  -0.542 5.87e-01
## triceps      0.01858    0.01861   0.998 3.18e-01
## insulin     -0.00159    0.00139  -1.144 2.52e-01
## mass         0.04502    0.02887   1.559 1.19e-01
## pedigree     0.96845    0.46020   2.104 3.53e-02
## age          0.04256    0.02158   1.972 4.86e-02</code></pre>
<p>From the output above, the coefficients table shows the beta coefficient estimates and their significance levels. Columns are:</p>
<ul>
<li><code>Estimate</code>: the intercept (b0) and the beta coefficient estimates associated to each predictor variable</li>
<li><code>Std.Error</code>: the standard error of the coefficient estimates. This represents the accuracy of the coefficients. The larger the standard error, the less confident we are about the estimate.</li>
<li><code>z value</code>: the z-statistic, which is the coefficient estimate (column 2) divided by the standard error of the estimate (column 3)</li>
<li><code>Pr(>|z|)</code>: The p-value corresponding to the z-statistic. The smaller the p-value, the more significant the estimate is.</li>
</ul>
<p>Note that, the functions <code>coef()</code> and <code>summary()</code> can be used to extract only the coefficients, as follow:</p>
<pre class="r"><code>coef(model)
summary(model )$coef</code></pre>
</div>
</div>
<div id="interpretation" class="section level2">
<h2>Interpretation</h2>
<p>It can be seen that only 5 out of the 8 predictors are significantly associated to the outcome. These include: pregnant, glucose, pressure, mass and pedigree.</p>
<p>The coefficient estimate of the variable <code>glucose</code> is b = 0.045, which is positive. This means that an increase in glucose is associated with increase in the probability of being diabetes-positive. However the coefficient for the variable <code>pressure</code> is b = -0.007, which is negative. This means that an increase in blood pressure will be associated with a decreased probability of being diabetes-positive.</p>
<p>An important concept to understand, for interpreting the logistic beta coefficients, is the <strong>odds ratio</strong>. An odds ratio measures the association between a predictor variable (x) and the outcome variable (y). It represents the ratio of the odds that an event will occur (<code>event = 1</code>) given the presence of the predictor x (<code>x = 1</code>), compared to the odds of the event occurring in the absence of that predictor (<code>x = 0</code>).</p>
<p>For a given predictor (say x1), the associated beta coefficient (b1) in the logistic regression function corresponds to the log of the odds ratio for that predictor.</p>
<p>If the odds ratio is 2, then the odds that the event occurs (<code>event = 1</code>) are two times higher when the predictor x is present (<code>x = 1</code>) versus x is absent (<code>x = 0</code>).</p>
<p>For example, the regression coefficient for glucose is 0.042. This indicate that one unit increase in the glucose concentration will increase the odds of being diabetes-positive by exp(0.042) 1.04 times.</p>
<p>From the logistic regression results, it can be noticed that some variables - triceps, insulin and age - are not statistically significant. Keeping them in the model may contribute to overfitting. Therefore, they should be eliminated. This can be done automatically using statistical techniques, including <strong>stepwise regression</strong> and <strong>penalized regression</strong> methods. This methods are described in the next section. Briefly, they consist of selecting an optimal model with a reduced set of variables, without compromising the model curacy.</p>
<p>Here, as we have a small number of predictors (n = 9), we can select manually the most significant:</p>
<pre class="r"><code>model <- glm( diabetes ~ pregnant + glucose + pressure + mass + pedigree, 
                data = train.data, family = binomial)</code></pre>
</div>
<div id="making-predictions" class="section level2">
<h2>Making predictions</h2>
<p>We’ll make predictions using the test data in order to evaluate the performance of our logistic regression model.</p>
<p>The procedure is as follow:</p>
<ol style="list-style-type: decimal">
<li>Predict the class membership probabilities of observations based on predictor variables</li>
<li>Assign the observations to the class with highest probability score (i.e above 0.5)</li>
</ol>
<p>The R function <code>predict()</code> can be used to predict the probability of being diabetes-positive, given the predictor values.</p>
<p><strong>Predict the probabilities</strong> of being diabetes-positive:</p>
<pre class="r"><code>probabilities <- model %>% predict(test.data, type = "response")
head(probabilities)</code></pre>
<pre><code>##     21     25     28     29     32     36 
## 0.3914 0.6706 0.0501 0.5735 0.6444 0.1494</code></pre>
<p>Which classes do these probabilities refer to? In our example, the output is the probability that the diabetes test will be positive. We know that these values correspond to the probability of the test to be positive, rather than negative, because the <code>contrasts()</code> function indicates that R has created a dummy variable with a 1 for “pos” and “0” for neg. The probabilities always refer to the class dummy-coded as “1”.</p>
<p>Check the dummy coding:</p>
<pre class="r"><code>contrasts(test.data$diabetes)</code></pre>
<pre><code>##     pos
## neg   0
## pos   1</code></pre>
<p><strong>Predict the class of individuals</strong>:</p>
<p>The following R code categorizes individuals into two groups based on their predicted probabilities (p) of being diabetes-positive. Individuals, with p above 0.5 (random guessing), are considered as diabetes-positive.</p>
<pre class="r"><code>predicted.classes <- ifelse(probabilities > 0.5, "pos", "neg")
head(predicted.classes)</code></pre>
<pre><code>##    21    25    28    29    32    36 
## "neg" "pos" "neg" "pos" "pos" "neg"</code></pre>
</div>
<div id="assessing-model-accuracy" class="section level2">
<h2>Assessing model accuracy</h2>
<p>The model accuracy is measured as the proportion of observations that have been correctly classified. Inversely, the classification error is defined as the proportion of observations that have been misclassified.</p>
<p>Proportion of correctly classified observations:</p>
<pre class="r"><code>mean(predicted.classes == test.data$diabetes)</code></pre>
<pre><code>## [1] 0.756</code></pre>
<div class="success">
<p>
The classification prediction accuracy is about 76%, which is good. The misclassification error rate is 24%.
</p>
</div>
<p>Note that, there are several metrics for evaluating the performance of a classification model (Chapter @ref(classification-model-evaluation)).</p>
</div>
<div id="discussion" class="section level2">
<h2>Discussion</h2>
<p>In this chapter, we have described how logistic regression works and we have provided R codes to compute logistic regression. Additionally, we demonstrated how to make predictions and to assess the model accuracy. Logistic regression model output is very easy to interpret compared to other classification methods. Additionally, because of its simplicity it is less prone to overfitting than flexible methods such as decision trees.</p>
<p>Note that, many concepts for linear regression hold true for the logistic regression modeling. For example, you need to perform some diagnostics (Chapter @ref(logistic-regression-assumptions-and-diagnostics)) to make sure that the assumptions made by the model are met for your data.</p>
<p>Furthermore, you need to measure how good the model is in predicting the outcome of new test data observations. Here, we described how to compute the raw classification accuracy, but not that other important performance metric exists (Chapter @ref(classification-model-evaluation))</p>
<p>In a situation, where you have many predictors you can select, without compromising the prediction accuracy, a minimal list of predictor variables that contribute the most to the model using stepwise regression (Chapter @ref(stepwise-logistic-regression)) and lasso regression techniques (Chapter @ref(penalized-logistic-regression)).</p>
<p>Additionally, you can add interaction terms in the model, or include spline terms.</p>
<p>The same problems concerning confounding and correlated variables apply to logistic regression (see Chapter @ref(confounding-variables) and @ref(multicollinearity)).</p>
<p>You can also fit <em>generalized additive models</em> (Chapter @ref(polynomial-and-spline-regression)), when linearity of the predictor cannot be assumed. This can be done using the <code>mgcv</code> package:</p>
<pre class="r"><code>library("mgcv")
# Fit the model
gam.model <- gam(diabetes ~ s(glucose) + mass + pregnant,
                 data = train.data, family = "binomial")
# Summarize model
summary(gam.model )
# Make predictions
probabilities <- gam.model %>% predict(test.data, type = "response")
predicted.classes <- ifelse(probabilities> 0.5, "pos", "neg")
# Model Accuracy
mean(predicted.classes == test.data$diabetes)</code></pre>
<p>Logistic regression is limited to only two-class classification problems. There is an extension, called <em>multinomial logistic regression</em>, for multiclass classification problem (Chapter @ref(multinomial-logistic-regression)).</p>
<p>Note that, the most popular method, for multiclass tasks, is the <em>Linear Discriminant Analysis</em> (Chapter @ref(discriminant-analysis)).</p>
</div>
<div id="references" class="section level2 unnumbered">
<h2>References</h2>
<div id="refs" class="references">
<div id="ref-bruce2017">
<p>Bruce, Peter, and Andrew Bruce. 2017. <em>Practical Statistics for Data Scientists</em>. O’Reilly Media.</p>
</div>
<div id="ref-james2014">
<p>James, Gareth, Daniela Witten, Trevor Hastie, and Robert Tibshirani. 2014. <em>An Introduction to Statistical Learning: With Applications in R</em>. Springer Publishing Company, Incorporated.</p>
</div>
</div>
</div>


</div><!--end rdoc-->


<!-- END HTML -->]]></description>
			<pubDate>Sun, 11 Mar 2018 09:07:00 +0100</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[Stepwise Logistic Regression Essentials in R]]></title>
			<link>https://www.sthda.com/english/articles/36-classification-methods-essentials/150-stepwise-logistic-regression-essentials-in-r/</link>
			<guid>https://www.sthda.com/english/articles/36-classification-methods-essentials/150-stepwise-logistic-regression-essentials-in-r/</guid>
			<description><![CDATA[<!-- START HTML -->

  <div id="rdoc">





<p><strong>Stepwise logistic regression</strong> consists of automatically selecting a reduced number of predictor variables for building the best performing logistic regression model. Read more at Chapter @ref(stepwise-regression).</p>
<p>This chapter describes how to compute the stepwise logistic regression in <strong>R</strong>.</p>
<p>Contents:</p>
<div id="TOC">
<ul>
<li><a href="#loading-required-r-packages">Loading required R packages</a></li>
<li><a href="#preparing-the-data">Preparing the data</a></li>
<li><a href="#computing-stepwise-logistique-regression">Computing stepwise logistique regression</a><ul>
<li><a href="#quick-start-r-code">Quick start R code</a></li>
<li><a href="#full-logistic-regression-model">Full logistic regression model</a></li>
<li><a href="#perform-stepwise-variable-selection">Perform stepwise variable selection</a></li>
<li><a href="#compare-the-full-and-the-stepwise-models">Compare the full and the stepwise models</a></li>
</ul></li>
<li><a href="#discussion">Discussion</a></li>
</ul>
</div>
<br/>
<div class = "small-block content-privileged-friends navr-book">
  <p>The Book:</p>
        <a href = "https://www.sthda.com/english/web/5-bookadvisor/54-machine-learning-essentials/">
          <img src = "https://www.sthda.com/english/upload/machine-learning-essentials-frontcover-200px.png" /><br/>
     Machine Learning Essentials: Practical Guide in R
      </a>
</div>
<div class="spacer"></div>


<div id="loading-required-r-packages" class="section level2">
<h2>Loading required R packages</h2>
<ul>
<li><code>tidyverse</code> for easy data manipulation and visualization</li>
<li><code>caret</code> for easy machine learning workflow</li>
</ul>
<pre class="r"><code>library(tidyverse)
library(caret)</code></pre>
</div>
<div id="preparing-the-data" class="section level2">
<h2>Preparing the data</h2>
<p>Data set: <code>PimaIndiansDiabetes2</code> [in <code>mlbench</code> package], introduced in Chapter @ref(classification-in-r), for predicting the probability of being diabetes positive based on multiple clinical variables.</p>
<p>We’ll randomly split the data into training set (80% for building a predictive model) and test set (20% for evaluating the model). Make sure to set seed for reproductibility.</p>
<pre class="r"><code># Load the data and remove NAs
data("PimaIndiansDiabetes2", package = "mlbench")
PimaIndiansDiabetes2 <- na.omit(PimaIndiansDiabetes2)
# Inspect the data
sample_n(PimaIndiansDiabetes2, 3)
# Split the data into training and test set
set.seed(123)
training.samples <- PimaIndiansDiabetes2$diabetes %>% 
  createDataPartition(p = 0.8, list = FALSE)
train.data  <- PimaIndiansDiabetes2[training.samples, ]
test.data <- PimaIndiansDiabetes2[-training.samples, ]</code></pre>
</div>
<div id="computing-stepwise-logistique-regression" class="section level2">
<h2>Computing stepwise logistique regression</h2>
<p>The stepwise logistic regression can be easily computed using the R function <code>stepAIC()</code> available in the MASS package. It performs model selection by AIC. It has an option called <code>direction</code>, which can have the following values: “both”, “forward”, “backward” (see Chapter @ref(stepwise-regression)).</p>
<div id="quick-start-r-code" class="section level3">
<h3>Quick start R code</h3>
<pre class="r"><code>library(MASS)
# Fit the model
model <- glm(diabetes ~., data = train.data, family = binomial) %>%
  stepAIC(trace = FALSE)
# Summarize the final selected model
summary(model)
# Make predictions
probabilities <- model %>% predict(test.data, type = "response")
predicted.classes <- ifelse(probabilities > 0.5, "pos", "neg")
# Model accuracy
mean(predicted.classes==test.data$diabetes)</code></pre>
</div>
<div id="full-logistic-regression-model" class="section level3">
<h3>Full logistic regression model</h3>
<p>Full model incorporating all predictors:</p>
<pre class="r"><code>full.model <- glm(diabetes ~., data = train.data, family = binomial)
coef(full.model)</code></pre>
<pre><code>## (Intercept)    pregnant     glucose    pressure     triceps     insulin 
##    -9.50372     0.04571     0.04230    -0.00700     0.01858    -0.00159 
##        mass    pedigree         age 
##     0.04502     0.96845     0.04256</code></pre>
</div>
<div id="perform-stepwise-variable-selection" class="section level3">
<h3>Perform stepwise variable selection</h3>
<p>Select the most contributive variables:</p>
<pre class="r"><code>library(MASS)
step.model <- full.model %>% stepAIC(trace = FALSE)
coef(step.model)</code></pre>
<pre><code>## (Intercept)     glucose        mass    pedigree         age 
##     -9.5612      0.0379      0.0523      0.9697      0.0529</code></pre>
<div class="success">
<p>
The function chose a final model in which one variable has been removed from the original full model. Dropped predictor is: <code>triceps</code>.
</p>
</div>
</div>
<div id="compare-the-full-and-the-stepwise-models" class="section level3">
<h3>Compare the full and the stepwise models</h3>
<p>Here, we’ll compare the performance of the full and the stepwise logistic models. The best model is defined as the model that has the lowest classification error rate in predicting the class of new test data:</p>
<p>Prediction accuracy of the full logistic regression model:</p>
<pre class="r"><code># Make predictions
probabilities <- full.model %>% predict(test.data, type = "response")
predicted.classes <- ifelse(probabilities > 0.5, "pos", "neg")
# Prediction accuracy
observed.classes <- test.data$diabetes
mean(predicted.classes == observed.classes)</code></pre>
<pre><code>## [1] 0.808</code></pre>
<p>Prediction accuracy of the stepwise logistic regression model:</p>
<pre class="r"><code># Make predictions
probabilities <- predict(step.model, test.data, type = "response")
predicted.classes <- ifelse(probabilities > 0.5, "pos", "neg")
# Prediction accuracy
observed.classes <- test.data$diabetes
mean(predicted.classes == observed.classes)</code></pre>
<pre><code>## [1] 0.795</code></pre>
</div>
</div>
<div id="discussion" class="section level2">
<h2>Discussion</h2>
<p>This chapter describes how to perform stepwise logistic regression in R. In our example, the stepwise regression have selected a reduced number of predictor variables resulting to a final model, which performance was similar to the one of the full model.</p>
<p>So, the stepwise selection reduced the complexity of the model without compromising its accuracy. Note that, all things equal, we should always choose the simpler model, here the final model returned by the stepwise regression.</p>
<p>Another alternative to the stepwise method, for model selection, is the penalized regression approach (Chapter @ref(penalized-logistic-regression)), which penalizes the model for having two many variables.</p>
</div>


</div><!--end rdoc-->


<!-- END HTML -->]]></description>
			<pubDate>Sun, 11 Mar 2018 09:03:00 +0100</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[Penalized Logistic Regression Essentials in R: Ridge, Lasso and Elastic Net]]></title>
			<link>https://www.sthda.com/english/articles/36-classification-methods-essentials/149-penalized-logistic-regression-essentials-in-r-ridge-lasso-and-elastic-net/</link>
			<guid>https://www.sthda.com/english/articles/36-classification-methods-essentials/149-penalized-logistic-regression-essentials-in-r-ridge-lasso-and-elastic-net/</guid>
			<description><![CDATA[<!-- START HTML -->

  <div id="rdoc">





<p>When you have multiple variables in your logistic regression model, it might be useful to find a reduced set of variables resulting to an optimal performing model (see Chapter @ref(penalized-regression)).</p>
<p><strong>Penalized logistic regression</strong> imposes a penalty to the logistic model for having too many variables. This results in shrinking the coefficients of the less contributive variables toward zero. This is also known as <strong>regularization</strong>.</p>
<p>The most commonly used penalized regression include:</p>
<ul>
<li><strong>ridge regression</strong>: variables with minor contribution have their coefficients close to zero. However, all the variables are incorporated in the model. This is useful when all variables need to be incorporated in the model according to domain knowledge.</li>
<li><strong>lasso regression</strong>: the coefficients of some less contributive variables are forced to be exactly zero. Only the most significant variables are kept in the final model.</li>
<li><strong>elastic net regression</strong>: the combination of ridge and lasso regression. It shrinks some coefficients toward zero (like ridge regression) and set some coefficients to exactly zero (like lasso regression)</li>
</ul>
<p>This chapter describes how to compute penalized logistic regression, such as lasso regression, for automatically selecting an optimal model containing the most contributive predictor variables.</p>
<p>Contents:</p>
<div id="TOC">
<ul>
<li><a href="#loading-required-r-packages">Loading required R packages</a></li>
<li><a href="#preparing-the-data">Preparing the data</a></li>
<li><a href="#computing-penalized-logistic-regression">Computing penalized logistic regression</a><ul>
<li><a href="#additionnal-data-preparation">Additionnal data preparation</a></li>
<li><a href="#r-functions">R functions</a></li>
<li><a href="#quick-start-r-code">Quick start R code</a></li>
<li><a href="#compute-lasso-regression">Compute lasso regression</a></li>
<li><a href="#compute-the-full-logistic-model">Compute the full logistic model</a></li>
</ul></li>
<li><a href="#discussion">Discussion</a></li>
</ul>
</div>
<br/>
<div class = "small-block content-privileged-friends navr-book">
  <p>The Book:</p>
        <a href = "https://www.sthda.com/english/web/5-bookadvisor/54-machine-learning-essentials/">
          <img src = "https://www.sthda.com/english/upload/machine-learning-essentials-frontcover-200px.png" /><br/>
     Machine Learning Essentials: Practical Guide in R
      </a>
</div>
<div class="spacer"></div>


<div id="loading-required-r-packages" class="section level2">
<h2>Loading required R packages</h2>
<ul>
<li><code>tidyverse</code> for easy data manipulation and visualization</li>
<li><code>caret</code> for easy machine learning workflow</li>
<li><code>glmnet</code>, for computing penalized regression</li>
</ul>
<pre class="r"><code>library(tidyverse)
library(caret)
library(glmnet)</code></pre>
</div>
<div id="preparing-the-data" class="section level2">
<h2>Preparing the data</h2>
<p>Data set: <code>PimaIndiansDiabetes2</code> [in <code>mlbench</code> package], introduced in Chapter @ref(classification-in-r), for predicting the probability of being diabetes positive based on multiple clinical variables.</p>
<p>We’ll randomly split the data into training set (80% for building a predictive model) and test set (20% for evaluating the model). Make sure to set seed for reproductibility.</p>
<pre class="r"><code># Load the data and remove NAs
data("PimaIndiansDiabetes2", package = "mlbench")
PimaIndiansDiabetes2 <- na.omit(PimaIndiansDiabetes2)
# Inspect the data
sample_n(PimaIndiansDiabetes2, 3)
# Split the data into training and test set
set.seed(123)
training.samples <- PimaIndiansDiabetes2$diabetes %>% 
  createDataPartition(p = 0.8, list = FALSE)
train.data  <- PimaIndiansDiabetes2[training.samples, ]
test.data <- PimaIndiansDiabetes2[-training.samples, ]</code></pre>
</div>
<div id="computing-penalized-logistic-regression" class="section level2">
<h2>Computing penalized logistic regression</h2>
<div id="additionnal-data-preparation" class="section level3">
<h3>Additionnal data preparation</h3>
<p>The R function <code>model.matrix()</code> helps to create the matrix of predictors and also automatically converts categorical predictors to appropriate dummy variables, which is required for the <code>glmnet()</code> function.</p>
<pre class="r"><code># Dumy code categorical predictor variables
x <- model.matrix(diabetes~., train.data)[,-1]
# Convert the outcome (class) to a numerical variable
y <- ifelse(train.data$diabetes == "pos", 1, 0)</code></pre>
</div>
<div id="r-functions" class="section level3">
<h3>R functions</h3>
<p>We’ll use the R function <code>glmnet()</code> [glmnet package] for computing penalized logistic regression.</p>
<p>The simplified format is as follow:</p>
<pre class="r"><code>glmnet(x, y, family = "binomial", alpha = 1, lambda = NULL)</code></pre>
<ul>
<li><code>x</code>: matrix of predictor variables</li>
<li><code>y</code>: the response or outcome variable, which is a binary variable.</li>
<li><code>family</code>: the response type. Use “binomial” for a binary outcome variable</li>
<li><code>alpha</code>: the elasticnet mixing parameter. Allowed values include:
<ul>
<li>“1”: for lasso regression</li>
<li>“0”: for ridge regression</li>
<li>a value between 0 and 1 (say 0.3) for elastic net regression.</li>
</ul></li>
<li><code>lamba</code>: a numeric value defining the amount of shrinkage. Should be specify by analyst.</li>
</ul>
<p>In penalized regression, you need to specify a constant <code>lambda</code> to adjust the amount of the coefficient shrinkage. The best <code>lambda</code> for your data, can be defined as the <code>lambda</code> that minimize the cross-validation prediction error rate. This can be determined automatically using the function <code>cv.glmnet()</code>.</p>
<div class="block">
<p>
In the following R code, we’ll show how to compute lasso regression by specifying the option <code>alpha = 1</code>. You can also try the ridge regression, using <code>alpha = 0</code>, to see which is better for your data.
</p>
</div>
</div>
<div id="quick-start-r-code" class="section level3">
<h3>Quick start R code</h3>
<p>Fit the lasso penalized regression model:</p>
<pre class="r"><code>library(glmnet)
# Find the best lambda using cross-validation
set.seed(123) 
cv.lasso <- cv.glmnet(x, y, alpha = 1, family = "binomial")
# Fit the final model on the training data
model <- glmnet(x, y, alpha = 1, family = "binomial",
                lambda = cv.lasso$lambda.min)
# Display regression coefficients
coef(model)
# Make predictions on the test data
x.test <- model.matrix(diabetes ~., test.data)[,-1]
probabilities <- model %>% predict(newx = x.test)
predicted.classes <- ifelse(probabilities > 0.5, "pos", "neg")
# Model accuracy
observed.classes <- test.data$diabetes
mean(predicted.classes == observed.classes)</code></pre>
</div>
<div id="compute-lasso-regression" class="section level3">
<h3>Compute lasso regression</h3>
<p><strong>Find the optimal value of lambda that minimizes the cross-validation error</strong>:</p>
<pre class="r"><code>library(glmnet)
set.seed(123)
cv.lasso <- cv.glmnet(x, y, alpha = 1, family = "binomial")
plot(cv.lasso)</code></pre>
<p><img src="https://www.sthda.com/english/sthda-upload/figures/machine-learning-essentials/029-penalized-logistic-regression-cross-validation-error-1.png" width="384" /></p>
<p>The plot displays the cross-validation error according to the log of lambda. The left dashed vertical line indicates that the log of the optimal value of lambda is approximately -5, which is the one that minimizes the prediction error. This lambda value will give the most accurate model. The exact value of <code>lambda</code> can be viewed as follow:</p>
<pre class="r"><code>cv.lasso$lambda.min</code></pre>
<pre><code>## [1] 0.00871</code></pre>
<p>Generally, the purpose of regularization is to balance accuracy and simplicity. This means, a model with the smallest number of predictors that also gives a good accuracy. To this end, the function <code>cv.glmnet()</code> finds also the value of <code>lambda</code> that gives the simplest model but also lies within one standard error of the optimal value of <code>lambda</code>. This value is called <code>lambda.1se</code>.</p>
<pre class="r"><code>cv.lasso$lambda.1se</code></pre>
<pre><code>## [1] 0.0674</code></pre>
<p>Using <code>lambda.min</code> as the best lambda, gives the following regression coefficients:</p>
<pre class="r"><code>coef(cv.lasso, cv.lasso$lambda.min)</code></pre>
<pre><code>## 9 x 1 sparse Matrix of class "dgCMatrix"
##                     1
## (Intercept) -8.615615
## pregnant     0.035076
## glucose      0.036916
## pressure     .       
## triceps      0.016484
## insulin     -0.000392
## mass         0.030485
## pedigree     0.785506
## age          0.036265</code></pre>
<div class="success">
<p>
From the output above, only the viable <code>triceps</code> has a coefficient exactly equal to zero.
</p>
</div>
<p>Using <code>lambda.1se</code> as the best lambda, gives the following regression coefficients:</p>
<pre class="r"><code>coef(cv.lasso, cv.lasso$lambda.1se)</code></pre>
<pre><code>## 9 x 1 sparse Matrix of class "dgCMatrix"
##                    1
## (Intercept) -4.65750
## pregnant     .      
## glucose      0.02628
## pressure     .      
## triceps      0.00191
## insulin      .      
## mass         .      
## pedigree     .      
## age          0.01734</code></pre>
<div class="success">
<p>
Using <code>lambda.1se</code>, only 5 variables have non-zero coefficients. The coefficients of all other variables have been set to zero by the lasso algorithm, reducing the complexity of the model.
</p>
<p>
Setting lambda = lambda.1se produces a simpler model compared to lambda.min, but the model might be a little bit less accurate than the one obtained with lambda.min.
</p>
</div>
<p>In the next sections, we’ll compute the final model using <code>lambda.min</code> and then assess the model accuracy against the test data. We’ll also discuss the results obtained by fitting the model using <code>lambda = lambda.1se</code>.</p>
<p><strong>Compute the final lasso model</strong>:</p>
<ul>
<li>Compute the final model using <code>lambda.min</code>:</li>
</ul>
<pre class="r"><code># Final model with lambda.min
lasso.model <- glmnet(x, y, alpha = 1, family = "binomial",
                      lambda = cv.lasso$lambda.min)
# Make prediction on test data
x.test <- model.matrix(diabetes ~., test.data)[,-1]
probabilities <- lasso.model %>% predict(newx = x.test)
predicted.classes <- ifelse(probabilities > 0.5, "pos", "neg")
# Model accuracy
observed.classes <- test.data$diabetes
mean(predicted.classes == observed.classes)</code></pre>
<pre><code>## [1] 0.769</code></pre>
<ul>
<li>Compute the final model using <code>lambda.1se</code>:</li>
</ul>
<pre class="r"><code># Final model with lambda.1se
lasso.model <- glmnet(x, y, alpha = 1, family = "binomial",
                      lambda = cv.lasso$lambda.1se)
# Make prediction on test data
x.test <- model.matrix(diabetes ~., test.data)[,-1]
probabilities <- lasso.model %>% predict(newx = x.test)
predicted.classes <- ifelse(probabilities > 0.5, "pos", "neg")
# Model accuracy rate
observed.classes <- test.data$diabetes
mean(predicted.classes == observed.classes)</code></pre>
<pre><code>## [1] 0.705</code></pre>
<p>In the next sections, we’ll compare the accuracy obtained with lasso regression against the one obtained using the full logistic regression model (including all predictors).</p>
</div>
<div id="compute-the-full-logistic-model" class="section level3">
<h3>Compute the full logistic model</h3>
<pre class="r"><code># Fit the model
full.model <- glm(diabetes ~., data = train.data, family = binomial)
# Make predictions
probabilities <- full.model %>% predict(test.data, type = "response")
predicted.classes <- ifelse(probabilities > 0.5, "pos", "neg")
# Model accuracy
observed.classes <- test.data$diabetes
mean(predicted.classes == observed.classes)</code></pre>
<pre><code>## [1] 0.808</code></pre>
</div>
</div>
<div id="discussion" class="section level2">
<h2>Discussion</h2>
<p>This chapter described how to compute penalized logistic regression model in R. Here, we focused on lasso model, but you can also fit the ridge regression by using <code>alpha = 0</code> in the <code>glmnet()</code> function. For elastic net regression, you need to choose a value of alpha somewhere between 0 and 1. This can be done automatically using the <code>caret</code> package. See Chapter @ref(penalized-regression).</p>
<p>Our analysis demonstrated that the lasso regression, using <code>lambda.min</code> as the best lambda, results to simpler model without compromising much the model performance on the test data when compared to the full logistic model.</p>
<p>The model accuracy that we have obtained with <code>lambda.1se</code> is a bit less than what we got with the more complex model using all predictor variables (n = 8) or using <code>lambda.min</code> in the lasso regression. Even with <code>lambda.1se</code>, the obtained accuracy remains good enough in addition to the resulting model simplicity.</p>
<p>This means that the simpler model obtained with lasso regression does at least as good a job fitting the information in the data as the more complicated one. According to the bias-variance trade-off, all things equal, simpler model should be always preferred because it is less likely to overfit the training data.</p>
<p>For variable selection, an alternative to the penalized logistic regression techniques is the stepwise logistic regression described in the Chapter @ref(stepwise-logistic-regression).</p>
</div>


</div><!--end rdoc-->


<!-- END HTML -->]]></description>
			<pubDate>Sun, 11 Mar 2018 08:57:00 +0100</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[Logistic Regression Assumptions and Diagnostics in R]]></title>
			<link>https://www.sthda.com/english/articles/36-classification-methods-essentials/148-logistic-regression-assumptions-and-diagnostics-in-r/</link>
			<guid>https://www.sthda.com/english/articles/36-classification-methods-essentials/148-logistic-regression-assumptions-and-diagnostics-in-r/</guid>
			<description><![CDATA[<!-- START HTML -->

  <div id="rdoc">





<p>The <strong>logistic regression</strong> model makes several <strong>assumptions</strong> about the data.</p>
<p>This chapter describes the major assumptions and provides practical guide, in R, to check whether these assumptions hold true for your data, which is essential to build a good model.</p>
<p>Make sure you have read the logistic regression essentials in Chapter @ref(logistic-regression).</p>
<p>Contents:</p>
<div id="TOC">
<ul>
<li><a href="#logistic-regression-assumptions">Logistic regression assumptions</a></li>
<li><a href="#loading-required-r-packages">Loading required R packages</a></li>
<li><a href="#building-a-logistic-regression-model">Building a logistic regression model</a></li>
<li><a href="#logistic-regression-diagnostics">Logistic regression diagnostics</a><ul>
<li><a href="#linearity-assumption">Linearity assumption</a></li>
<li><a href="#influential-values">Influential values</a></li>
<li><a href="#multicollinearity-logistic-regression">Multicollinearity</a></li>
</ul></li>
<li><a href="#discussion">Discussion</a></li>
</ul>
</div>
<br/>
<div class = "small-block content-privileged-friends navr-book">
  <p>The Book:</p>
        <a href = "https://www.sthda.com/english/web/5-bookadvisor/54-machine-learning-essentials/">
          <img src = "https://www.sthda.com/english/upload/machine-learning-essentials-frontcover-200px.png" /><br/>
     Machine Learning Essentials: Practical Guide in R
      </a>
</div>
<div class="spacer"></div>


<div id="logistic-regression-assumptions" class="section level2">
<h2>Logistic regression assumptions</h2>
<p>The logistic regression method assumes that:</p>
<ul>
<li>The outcome is a binary or dichotomous variable like yes vs no, positive vs negative, 1 vs 0.

</li>
<li>There is a linear relationship between the logit of the outcome and each predictor variables. Recall that the logit function is <code>logit(p) = log(p/(1-p))</code>, where p is the probabilities of the outcome (see Chapter @ref(logistic-regression)).</li>
<li>There is no influential values (extreme values or outliers) in the continuous predictors</li>
<li>There is no high intercorrelations (i.e. multicollinearity) among the predictors.</li>
</ul>
<p>To improve the accuracy of your model, you should make sure that these assumptions hold true for your data. In the following sections, we’ll describe how to diagnostic potential problems in the data.</p>
</div>
<div id="loading-required-r-packages" class="section level2">
<h2>Loading required R packages</h2>
<ul>
<li><code>tidyverse</code> for easy data manipulation and visualization</li>
<li><code>broom</code>: creates a tidy data frame from statistical test results</li>
</ul>
<pre class="r"><code>library(tidyverse)
library(broom)
theme_set(theme_classic())</code></pre>
</div>
<div id="building-a-logistic-regression-model" class="section level2">
<h2>Building a logistic regression model</h2>
<p>We start by computing an example of logistic regression model using the <code>PimaIndiansDiabetes2</code> [mlbench package], introduced in Chapter @ref(classification-in-r), for predicting the probability of diabetes test positivity based on clinical variables.</p>
<pre class="r"><code># Load the data
data("PimaIndiansDiabetes2", package = "mlbench")
PimaIndiansDiabetes2 <- na.omit(PimaIndiansDiabetes2)
# Fit the logistic regression model
model <- glm(diabetes ~., data = PimaIndiansDiabetes2, 
               family = binomial)
# Predict the probability (p) of diabete positivity
probabilities <- predict(model, type = "response")
predicted.classes <- ifelse(probabilities > 0.5, "pos", "neg")
head(predicted.classes)</code></pre>
<pre><code>##     4     5     7     9    14    15 
## "neg" "pos" "neg" "pos" "pos" "pos"</code></pre>
</div>
<div id="logistic-regression-diagnostics" class="section level2">
<h2>Logistic regression diagnostics</h2>
<div id="linearity-assumption" class="section level3">
<h3>Linearity assumption</h3>
<p>Here, we’ll check the linear relationship between continuous predictor variables and the logit of the outcome. This can be done by visually inspecting the scatter plot between each predictor and the logit values.</p>
<ol style="list-style-type: decimal">
<li>Remove qualitative variables from the original data frame and bind the logit values to the data:</li>
</ol>
<pre class="r"><code># Select only numeric predictors
mydata <- PimaIndiansDiabetes2 %>%
  dplyr::select_if(is.numeric) 
predictors <- colnames(mydata)
# Bind the logit and tidying the data for plot
mydata <- mydata %>%
  mutate(logit = log(probabilities/(1-probabilities))) %>%
  gather(key = "predictors", value = "predictor.value", -logit)</code></pre>
<ol start="2" style="list-style-type: decimal">
<li>Create the scatter plots:</li>
</ol>
<pre class="r"><code>ggplot(mydata, aes(logit, predictor.value))+
  geom_point(size = 0.5, alpha = 0.5) +
  geom_smooth(method = "loess") + 
  theme_bw() + 
  facet_wrap(~predictors, scales = "free_y")</code></pre>
<p><img src="https://www.sthda.com/english/sthda-upload/figures/machine-learning-essentials/030-logistic-regression-assumptions-and-diagnostics-linearity-assumptions-1.png" width="480" /></p>
<p>The smoothed scatter plots show that variables glucose, mass, pregnant, pressure and triceps are all quite linearly associated with the diabetes outcome in logit scale.</p>
<p>The variable age and pedigree is not linear and might need some transformations. If the scatter plot shows non-linearity, you need other methods to build the model such as including 2 or 3-power terms, fractional polynomials and spline function (Chapter @ref(polynomial-and-spline-regression)).</p>
</div>
<div id="influential-values" class="section level3">
<h3>Influential values</h3>
<p>Influential values are extreme individual data points that can alter the quality of the logistic regression model.</p>
<p>The most extreme values in the data can be examined by visualizing the Cook’s distance values. Here we label the top 3 largest values:</p>
<pre class="r"><code>plot(model, which = 4, id.n = 3)</code></pre>
<p><img src="https://www.sthda.com/english/sthda-upload/figures/machine-learning-essentials/030-logistic-regression-assumptions-and-diagnostics-cooks-distance-outliers-1.png" width="576" /></p>
<p>Note that, not all outliers are influential observations. To check whether the data contains potential influential observations, the standardized residual error can be inspected. Data points with an absolute standardized residuals above 3 represent possible outliers and may deserve closer attention.</p>
<p>The following R code computes the standardized residuals (<code>.std.resid</code>) and the Cook’s distance (<code>.cooksd</code>) using the R function <code>augment()</code> [broom package].</p>
<pre class="r"><code># Extract model results
model.data <- augment(model) %>% 
  mutate(index = 1:n()) </code></pre>
<p>The data for the top 3 largest values, according to the Cook’s distance, can be displayed as follow:</p>
<pre class="r"><code>model.data %>% top_n(3, .cooksd)</code></pre>
<p>Plot the standardized residuals:</p>
<pre class="r"><code>ggplot(model.data, aes(index, .std.resid)) + 
  geom_point(aes(color = diabetes), alpha = .5) +
  theme_bw()</code></pre>
<p><img src="https://www.sthda.com/english/sthda-upload/figures/machine-learning-essentials/030-logistic-regression-assumptions-and-diagnostics-influential-values-outliers-1.png" width="432" /></p>
<p>Filter potential influential data points with <code>abs(.std.res) > 3</code>:</p>
<pre class="r"><code>model.data %>% 
  filter(abs(.std.resid) > 3)</code></pre>
<div class="success">
<p>
There is no influential observations in our data.
</p>
</div>
<p>When you have outliers in a continuous predictor, potential solutions include:</p>
<ul>
<li>Removing the concerned records</li>
<li>Transform the data into log scale</li>
<li>Use non parametric methods</li>
</ul>
</div>
<div id="multicollinearity-logistic-regression" class="section level3">
<h3>Multicollinearity</h3>
<p>Multicollinearity corresponds to a situation where the data contain highly correlated predictor variables. Read more in Chapter @ref(multicollinearity).</p>
<p>Multicollinearity is an important issue in regression analysis and should be fixed by removing the concerned variables. It can be assessed using the R function <code>vif()</code> [car package], which computes the variance inflation factors:</p>
<pre class="r"><code>car::vif(model)</code></pre>
<pre><code>## pregnant  glucose pressure  triceps  insulin     mass pedigree      age 
##     1.89     1.38     1.19     1.64     1.38     1.83     1.03     1.97</code></pre>
<p>As a rule of thumb, a VIF value that exceeds 5 or 10 indicates a problematic amount of collinearity. In our example, there is no collinearity: all variables have a value of VIF well below 5.</p>
</div>
</div>
<div id="discussion" class="section level2">
<h2>Discussion</h2>
<p>This chapter describes the main assumptions of logistic regression model and provides examples of R code to diagnostic potential problems in the data, including non linearity between the predictor variables and the logit of the outcome, the presence of influential observations in the data and multicollinearity among predictors.</p>
<p>Fixing these potential problems might improve considerably the goodness of the model. See also, additional performance metrics to check the validity of your model are described in the Chapter @ref(classification-model-evaluation).</p>
</div>


</div><!--end rdoc-->


<!-- END HTML -->]]></description>
			<pubDate>Sun, 11 Mar 2018 08:51:00 +0100</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[Multinomial Logistic Regression Essentials in R]]></title>
			<link>https://www.sthda.com/english/articles/36-classification-methods-essentials/147-multinomial-logistic-regression-essentials-in-r/</link>
			<guid>https://www.sthda.com/english/articles/36-classification-methods-essentials/147-multinomial-logistic-regression-essentials-in-r/</guid>
			<description><![CDATA[<!-- START HTML -->

  <div id="rdoc">





<p>The <strong>multinomial logistic regression</strong> is an extension of the logistic regression (Chapter @ref(logistic-regression)) for multiclass classification tasks. It is used when the outcome involves more than two classes.</p>
<p>In this chapter, we’ll show you how to compute multinomial logistic regression in R.</p>
<p>Contents:</p>
<div id="TOC">
<ul>
<li><a href="#loading-required-r-packages">Loading required R packages</a></li>
<li><a href="#preparing-the-data">Preparing the data</a></li>
<li><a href="#computing-multinomial-logistic-regression">Computing multinomial logistic regression</a></li>
<li><a href="#discussion">Discussion</a></li>
</ul>
</div>
<br/>
<div class = "small-block content-privileged-friends navr-book">
  <p>The Book:</p>
        <a href = "https://www.sthda.com/english/web/5-bookadvisor/54-machine-learning-essentials/">
          <img src = "https://www.sthda.com/english/upload/machine-learning-essentials-frontcover-200px.png" /><br/>
     Machine Learning Essentials: Practical Guide in R
      </a>
</div>
<div class="spacer"></div>


<div id="loading-required-r-packages" class="section level2">
<h2>Loading required R packages</h2>
<ul>
<li><code>tidyverse</code> for easy data manipulation</li>
<li><code>caret</code> for easy predictive modeling</li>
<li><code>nnet</code> for computing multinomial logistic regression</li>
</ul>
<pre class="r"><code>library(tidyverse)
library(caret)
library(nnet)</code></pre>
</div>
<div id="preparing-the-data" class="section level2">
<h2>Preparing the data</h2>
<p>We’ll use the <code>iris</code> data set, introduced in Chapter @ref(classification-in-r), for predicting iris species based on the predictor variables Sepal.Length, Sepal.Width, Petal.Length, Petal.Width.</p>
<p>We start by randomly splitting the data into training set (80% for building a predictive model) and test set (20% for evaluating the model). Make sure to set seed for reproducibility.</p>
<pre class="r"><code># Load the data
data("iris")
# Inspect the data
sample_n(iris, 3)
# Split the data into training and test set
set.seed(123)
training.samples <- iris$Species %>% 
  createDataPartition(p = 0.8, list = FALSE)
train.data  <- iris[training.samples, ]
test.data <- iris[-training.samples, ]</code></pre>
</div>
<div id="computing-multinomial-logistic-regression" class="section level2">
<h2>Computing multinomial logistic regression</h2>
<pre class="r"><code># Fit the model
model <- nnet::multinom(Species ~., data = train.data)
# Summarize the model
summary(model)
# Make predictions
predicted.classes <- model %>% predict(test.data)
head(predicted.classes)
# Model accuracy
mean(predicted.classes == test.data$Species)</code></pre>
<p>Model accuracy:</p>
<pre class="r"><code>mean(predicted.classes == test.data$Species)</code></pre>
<pre><code>## [1] 0.967</code></pre>
<div class="success">
<p>
Our model is very good in predicting the different categories with an accuracy of 97%.
</p>
</div>
</div>
<div id="discussion" class="section level2">
<h2>Discussion</h2>
<p>This chapter describes how to compute multinomial logistic regression in R. This method is used for multiclass problems. In practice, it is not used very often. Discriminant analysis (Chapter @ref(discriminant-analysis)) is more popular for multiple-class classification.</p>
</div>


</div><!--end rdoc-->


<!-- END HTML -->]]></description>
			<pubDate>Sun, 11 Mar 2018 08:47:00 +0100</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[Discriminant Analysis Essentials in R]]></title>
			<link>https://www.sthda.com/english/articles/36-classification-methods-essentials/146-discriminant-analysis-essentials-in-r/</link>
			<guid>https://www.sthda.com/english/articles/36-classification-methods-essentials/146-discriminant-analysis-essentials-in-r/</guid>
			<description><![CDATA[<!-- START HTML -->

  <div id="rdoc">





<p><strong>Discriminant analysis</strong> is used to predict the probability of belonging to a given class (or category) based on one or multiple predictor variables. It works with continuous and/or categorical predictor variables.</p>
<p>Previously, we have described the logistic regression for two-class classification problems, that is when the outcome variable has two possible values (0/1, no/yes, negative/positive).</p>
<p>Compared to logistic regression, the discriminant analysis is more suitable for predicting the category of an observation in the situation where the outcome variable contains more than two classes. Additionally, it’s more stable than the logistic regression for multi-class classification problems.</p>
<p>Note that, both logistic regression and discriminant analysis can be used for binary classification tasks.</p>
<p>In this chapter, you’ll learn the most widely used discriminant analysis techniques and extensions. Additionally, we’ll provide R code to perform the different types of analysis.</p>
<p>The following discriminant analysis methods will be described:</p>
<ul>
<li><p><strong>Linear discriminant analysis</strong> (<strong>LDA</strong>): Uses linear combinations of predictors to predict the class of a given observation. Assumes that the predictor variables (p) are normally distributed and the classes have identical variances (for univariate analysis, p = 1) or identical covariance matrices (for multivariate analysis, p > 1).</p></li>
<li><p><strong>Quadratic discriminant analysis</strong> (<strong>QDA</strong>): More flexible than LDA. Here, there is no assumption that the covariance matrix of classes is the same. </p></li>
<li><p><strong>Mixture discriminant analysis</strong> (<strong>MDA</strong>): Each class is assumed to be a Gaussian mixture of subclasses.</p></li>
<li><p><strong>Flexible Discriminant Analysis</strong> (<strong>FDA</strong>): Non-linear combinations of predictors is used such as splines.</p></li>
<li><p><strong>Regularized discriminant anlysis</strong> (<strong>RDA</strong>): Regularization (or shrinkage) improves the estimate of the covariance matrices in situations where the number of predictors is larger than the number of samples in the training data. This leads to an improvement of the discriminant analysis.</p></li>
</ul>
<p>Contents:</p>
<div id="TOC">
<ul>
<li><a href="#loading-required-r-packages">Loading required R packages</a></li>
<li><a href="#preparing-the-data">Preparing the data</a></li>
<li><a href="#linear-discriminant-analysis---lda">Linear discriminant analysis - LDA</a></li>
<li><a href="#quadratic-discriminant-analysis---qda">Quadratic discriminant analysis - QDA</a></li>
<li><a href="#mixture-discriminant-analysis---mda">Mixture discriminant analysis - MDA</a></li>
<li><a href="#flexible-discriminant-analysis---fda">Flexible discriminant analysis - FDA</a></li>
<li><a href="#regularized-discriminant-analysis">Regularized discriminant analysis</a></li>
<li><a href="#discussion">Discussion</a></li>
<li><a href="#references">References</a></li>
</ul>
</div>
<br/>
<div class = "small-block content-privileged-friends navr-book">
  <p>The Book:</p>
        <a href = "https://www.sthda.com/english/web/5-bookadvisor/54-machine-learning-essentials/">
          <img src = "https://www.sthda.com/english/upload/machine-learning-essentials-frontcover-200px.png" /><br/>
     Machine Learning Essentials: Practical Guide in R
      </a>
</div>
<div class="spacer"></div>


<div id="loading-required-r-packages" class="section level2">
<h2>Loading required R packages</h2>
<ul>
<li><code>tidyverse</code> for easy data manipulation and visualization</li>
<li><code>caret</code> for easy machine learning workflow</li>
</ul>
<pre class="r"><code>library(tidyverse)
library(caret)
theme_set(theme_classic())</code></pre>
</div>
<div id="preparing-the-data" class="section level2">
<h2>Preparing the data</h2>
<p>We’ll use the <code>iris</code> data set, introduced in Chapter @ref(classification-in-r), for predicting iris species based on the predictor variables Sepal.Length, Sepal.Width, Petal.Length, Petal.Width.</p>
<p>Discriminant analysis can be affected by the scale/unit in which predictor variables are measured. It’s generally recommended to standardize/normalize continuous predictor before the analysis.</p>
<ol style="list-style-type: decimal">
<li>Split the data into training and test set:</li>
</ol>
<pre class="r"><code># Load the data
data("iris")
# Split the data into training (80%) and test set (20%)
set.seed(123)
training.samples <- iris$Species %>%
  createDataPartition(p = 0.8, list = FALSE)
train.data <- iris[training.samples, ]
test.data <- iris[-training.samples, ]</code></pre>
<ol start="2" style="list-style-type: decimal">
<li>Normalize the data. Categorical variables are automatically ignored.</li>
</ol>
<pre class="r"><code># Estimate preprocessing parameters
preproc.param <- train.data %>% 
  preProcess(method = c("center", "scale"))
# Transform the data using the estimated parameters
train.transformed <- preproc.param %>% predict(train.data)
test.transformed <- preproc.param %>% predict(test.data)</code></pre>
</div>
<div id="linear-discriminant-analysis---lda" class="section level2">
<h2>Linear discriminant analysis - LDA</h2>
<p>The LDA algorithm starts by finding directions that maximize the separation between classes, then use these directions to predict the class of individuals. These directions, called linear discriminants, are a linear combinations of predictor variables.</p>
<p>LDA assumes that predictors are normally distributed (Gaussian distribution) and that the different classes have class-specific means and equal variance/covariance.</p>
<p>Before performing LDA, consider:</p>
<ul>
<li>Inspecting the univariate distributions of each variable and make sure that they are normally distribute. If not, you can transform them using log and root for exponential distributions and Box-Cox for skewed distributions.</li>
<li>removing outliers from your data and standardize the variables to make their scale comparable.</li>
</ul>
<p>The linear discriminant analysis can be easily computed using the function <code>lda()</code> [MASS package].</p>
<p><strong>Quick start R code</strong>:</p>
<pre class="r"><code>library(MASS)
# Fit the model
model <- lda(Species~., data = train.transformed)
# Make predictions
predictions <- model %>% predict(test.transformed)
# Model accuracy
mean(predictions$class==test.transformed$Species)</code></pre>
<p><strong>Compute LDA</strong>:</p>
<pre class="r"><code>library(MASS)
model <- lda(Species~., data = train.transformed)
model</code></pre>
<pre><code>## Call:
## lda(Species ~ ., data = train.transformed)
## 
## Prior probabilities of groups:
##     setosa versicolor  virginica 
##      0.333      0.333      0.333 
## 
## Group means:
##            Sepal.Length Sepal.Width Petal.Length Petal.Width
## setosa           -1.012       0.787       -1.293      -1.250
## versicolor        0.117      -0.648        0.272       0.154
## virginica         0.895      -0.139        1.020       1.095
## 
## Coefficients of linear discriminants:
##                 LD1     LD2
## Sepal.Length  0.911  0.0318
## Sepal.Width   0.648  0.8985
## Petal.Length -4.082 -2.2272
## Petal.Width  -2.313  2.6544
## 
## Proportion of trace:
##    LD1    LD2 
## 0.9905 0.0095</code></pre>
<p>LDA determines group means and computes, for each individual, the probability of belonging to the different groups. The individual is then affected to the group with the highest probability score.</p>
<p>The <code>lda()</code> outputs contain the following elements:</p>
<ul>
<li><em>Prior probabilities of groups</em>: the proportion of training observations in each group. For example, there are 31% of the training observations in the setosa group</li>
<li><em>Group means</em>: group center of gravity. Shows the mean of each variable in each group.</li>
<li><em>Coefficients of linear discriminants</em>: Shows the linear combination of predictor variables that are used to form the LDA decision rule. for example, <code>LD1 = 0.91*Sepal.Length + 0.64*Sepal.Width - 4.08*Petal.Length - 2.3*Petal.Width</code>. Similarly, <code>LD2 = 0.03*Sepal.Length + 0.89*Sepal.Width - 2.2*Petal.Length - 2.6*Petal.Width</code>.</li>
</ul>
<p>Using the function <code>plot()</code> produces plots of the linear discriminants, obtained by computing LD1 and LD2 for each of the training observations.</p>
<pre class="r"><code>plot(model)</code></pre>
<p><strong>Make predictions</strong>:</p>
<pre class="r"><code>predictions <- model %>% predict(test.transformed)
names(predictions)</code></pre>
<pre><code>## [1] "class"     "posterior" "x"</code></pre>
<p>The <code>predict()</code> function returns the following elements:</p>
<ul>
<li><em>class</em>: predicted classes of observations.</li>
<li><em>posterior</em>: is a matrix whose columns are the groups, rows are the individuals and values are the posterior probability that the corresponding observation belongs to the groups.</li>
<li><em>x</em>: contains the linear discriminants, described above</li>
</ul>
<p>Inspect the results:</p>
<pre class="r"><code># Predicted classes
head(predictions$class, 6)
# Predicted probabilities of class memebership.
head(predictions$posterior, 6) 
# Linear discriminants
head(predictions$x, 3) </code></pre>
<p>Note that, you can create the LDA plot using ggplot2 as follow:</p>
<pre class="r"><code>lda.data <- cbind(train.transformed, predict(model)$x)
ggplot(lda.data, aes(LD1, LD2)) +
  geom_point(aes(color = Species))</code></pre>
<p><img src="https://www.sthda.com/english/sthda-upload/figures/machine-learning-essentials/032-discriminant-analysis-ggplot-lda-1.png" width="384" /></p>
<p><strong>Model accuracy</strong>:</p>
<p>You can compute the model accuracy as follow:</p>
<pre class="r"><code>mean(predictions$class==test.transformed$Species)</code></pre>
<pre><code>## [1] 1</code></pre>
<div class="success">
<p>
It can be seen that, our model correctly classified 100% of observations, which is excellent.
</p>
</div>
<p>Note that, by default, the probability cutoff used to decide group-membership is 0.5 (random guessing). For example, the number of observations in the setosa group can be re-calculated using:</p>
<pre class="r"><code>sum(predictions$posterior[ ,1] >=.5)</code></pre>
<pre><code>## [1] 10</code></pre>
<p>In some situations, you might want to increase the precision of the model. In this case you can fine-tune the model by adjusting the posterior probability cutoff. For example, you can increase or lower the cutoff.</p>
<p><strong>Variable selection</strong>:</p>
<p>Note that, if the predictor variables are standardized before computing LDA, the discriminator weights can be used as measures of variable importance for feature selection.</p>
</div>
<div id="quadratic-discriminant-analysis---qda" class="section level2">
<h2>Quadratic discriminant analysis - QDA</h2>
<p>QDA is little bit more flexible than LDA, in the sense that it does not assumes the equality of variance/covariance. In other words, for QDA the covariance matrix can be different for each class.</p>
<p>LDA tends to be a better than QDA when you have a small training set.</p>
<p>In contrast, QDA is recommended if the training set is very large, so that the variance of the classifier is not a major issue, or if the assumption of a common covariance matrix for the K classes is clearly untenable <span class="citation">(James et al. 2014)</span>.</p>
<p>QDA can be computed using the R function <code>qda()</code> [MASS package]</p>
<pre class="r"><code>library(MASS)
# Fit the model
model <- qda(Species~., data = train.transformed)
model
# Make predictions
predictions <- model %>% predict(test.transformed)
# Model accuracy
mean(predictions$class == test.transformed$Species)</code></pre>
</div>
<div id="mixture-discriminant-analysis---mda" class="section level2">
<h2>Mixture discriminant analysis - MDA</h2>
<p>The LDA classifier assumes that each class comes from a single normal (or Gaussian) distribution. This is too restrictive.</p>
<p>For MDA, there are classes, and each class is assumed to be a Gaussian mixture of subclasses, where each data point has a probability of belonging to each class. Equality of covariance matrix, among classes, is still assumed.</p>
<pre class="r"><code>library(mda)
# Fit the model
model <- mda(Species~., data = train.transformed)
model
# Make predictions
predicted.classes <- model %>% predict(test.transformed)
# Model accuracy
mean(predicted.classes == test.transformed$Species)</code></pre>
<p>MDA might outperform LDA and QDA is some situations, as illustrated below. In this example data, we have 3 main groups of individuals, each having 3 no adjacent subgroups. The solid black lines on the plot represent the decision boundaries of LDA, QDA and MDA. It can be seen that the MDA classifier have identified correctly the subclasses compared to LDA and QDA, which were not good at all in modeling this data.</p>
<p><img src="https://www.sthda.com/english/sthda-upload/figures/machine-learning-essentials/032-discriminant-analysis-comparing-lda-qda-and-mda-1.png" width="672" /></p>
<p>The code for generating the above plots is from <a href="https://www.r-bloggers.com/a-brief-look-at-mixture-discriminant-analysis/">John Ramey</a></p>
</div>
<div id="flexible-discriminant-analysis---fda" class="section level2">
<h2>Flexible discriminant analysis - FDA</h2>
<p>FDA is a flexible extension of LDA that uses non-linear combinations of predictors such as splines. FDA is useful to model multivariate non-normality or non-linear relationships among variables within each group, allowing for a more accurate classification.</p>
<pre class="r"><code>library(mda)
# Fit the model
model <- fda(Species~., data = train.transformed)
# Make predictions
predicted.classes <- model %>% predict(test.transformed)
# Model accuracy
mean(predicted.classes == test.transformed$Species)</code></pre>
</div>
<div id="regularized-discriminant-analysis" class="section level2">
<h2>Regularized discriminant analysis</h2>
<p>RDA builds a classification rule by regularizing the group covariance matrices <span class="citation">(Friedman 1989)</span> allowing a more robust model against multicollinearity in the data. This might be very useful for a large multivariate data set containing highly correlated predictors.</p>
<p>Regularized discriminant analysis is a kind of a trade-off between LDA and QDA. Recall that, in LDA we assume equality of covariance matrix for all of the classes. QDA assumes different covariance matrices for all the classes. Regularized discriminant analysis is an intermediate between LDA and QDA.</p>
<p>RDA shrinks the separate covariances of QDA toward a common covariance as in LDA. This improves the estimate of the covariance matrices in situations where the number of predictors is larger than the number of samples in the training data, potentially leading to an improvement of the model accuracy.</p>
<pre class="r"><code>library(klaR)
# Fit the model
model <- rda(Species~., data = train.transformed)
# Make predictions
predictions <- model %>% predict(test.transformed)
# Model accuracy
mean(predictions$class == test.transformed$Species)</code></pre>
</div>
<div id="discussion" class="section level2">
<h2>Discussion</h2>
<p>We have described linear discriminant analysis (LDA) and extensions for predicting the class of an observations based on multiple predictor variables. Discriminant analysis is more suitable to multiclass classification problems compared to the logistic regression (Chapter @ref(logistic-regression)).</p>
<p>LDA assumes that the different classes has the same variance or covariance matrix. We have described many extensions of LDA in this chapter. The most popular extension of LDA is the quadratic discriminant analysis (QDA), which is more flexible than LDA in the sens that it does not assume the equality of group covariance matrices.</p>
<p>LDA tends to be better than QDA for small data set. QDA is recommended for large training data set.</p>
</div>
<div id="references" class="section level2 unnumbered">
<h2>References</h2>
<div id="refs" class="references">
<div id="ref-friedman1989">
<p>Friedman, Jerome H. 1989. “Regularized Discriminant Analysis.” <em>Journal of the American Statistical Association</em> 84 (405). Taylor &amp; Francis: 165–75. doi:<a href="https://doi.org/10.1080/01621459.1989.10478752">10.1080/01621459.1989.10478752</a>.</p>
</div>
<div id="ref-james2014">
<p>James, Gareth, Daniela Witten, Trevor Hastie, and Robert Tibshirani. 2014. <em>An Introduction to Statistical Learning: With Applications in R</em>. Springer Publishing Company, Incorporated.</p>
</div>
</div>
</div>


</div><!--end rdoc-->


<!-- END HTML -->]]></description>
			<pubDate>Sun, 11 Mar 2018 08:42:00 +0100</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[Naive Bayes Classifier Essentials]]></title>
			<link>https://www.sthda.com/english/articles/36-classification-methods-essentials/145-naive-bayes-classifier-essentials/</link>
			<guid>https://www.sthda.com/english/articles/36-classification-methods-essentials/145-naive-bayes-classifier-essentials/</guid>
			<description><![CDATA[<!-- START HTML -->

  <div id="rdoc">





<p>The <strong>Naive Bayes classifier</strong> is a simple and powerful method that can be used for binary and multiclass classification problems.</p>
<p>Naive Bayes classifier predicts the class membership probability of observations using Bayes theorem, which is based on conditional probability, that is the probability of something to happen, given that something else has already occurred.</p>
<p>Observations are assigned to the class with the largest probability score.</p>
<p>In this chapter, you’ll learn how to perform naive Bayes classification in R using the <code>klaR</code> and <code>caret</code> package.</p>
<p>Contents:</p>
<div id="TOC">
<ul>
<li><a href="#loading-required-r-packages">Loading required R packages</a></li>
<li><a href="#preparing-the-data">Preparing the data</a></li>
<li><a href="#computing-naive-bayes">Computing Naive Bayes</a></li>
<li><a href="#using-caret-r-package">Using caret R package</a></li>
<li><a href="#discussion">Discussion</a></li>
</ul>
</div>
<br/>
<div class = "small-block content-privileged-friends navr-book">
  <p>The Book:</p>
        <a href = "https://www.sthda.com/english/web/5-bookadvisor/54-machine-learning-essentials/">
          <img src = "https://www.sthda.com/english/upload/machine-learning-essentials-frontcover-200px.png" /><br/>
     Machine Learning Essentials: Practical Guide in R
      </a>
</div>
<div class="spacer"></div>


<div id="loading-required-r-packages" class="section level2">
<h2>Loading required R packages</h2>
<ul>
<li><code>tidyverse</code> for easy data manipulation and visualization</li>
<li><code>caret</code> for easy machine learning workflow</li>
</ul>
<pre class="r"><code>library(tidyverse)
library(caret)</code></pre>
</div>
<div id="preparing-the-data" class="section level2">
<h2>Preparing the data</h2>
<p>The input predictor variables can be categorical and/or numeric variables.</p>
<p>Here, we’ll use the <code>PimaIndiansDiabetes2</code> [in <code>mlbench</code> package], introduced in Chapter @ref(classification-in-r), for predicting the probability of being diabetes positive based on multiple clinical variables.</p>
<p>We’ll randomly split the data into training set (80% for building a predictive model) and test set (20% for evaluating the model). Make sure to set seed for reproducibility.</p>
<pre class="r"><code># Load the data and remove NAs
data("PimaIndiansDiabetes2", package = "mlbench")
PimaIndiansDiabetes2 <- na.omit(PimaIndiansDiabetes2)
# Inspect the data
sample_n(PimaIndiansDiabetes2, 3)
# Split the data into training and test set
set.seed(123)
training.samples <- PimaIndiansDiabetes2$diabetes %>% 
  createDataPartition(p = 0.8, list = FALSE)
train.data  <- PimaIndiansDiabetes2[training.samples, ]
test.data <- PimaIndiansDiabetes2[-training.samples, ]</code></pre>
</div>
<div id="computing-naive-bayes" class="section level2">
<h2>Computing Naive Bayes</h2>
<pre class="r"><code>library("klaR")
# Fit the model
model <- NaiveBayes(diabetes ~., data = train.data)
# Make predictions
predictions <- model %>% predict(test.data)
# Model accuracy
mean(predictions$class == test.data$diabetes)</code></pre>
<pre><code>## [1] 0.821</code></pre>
</div>
<div id="using-caret-r-package" class="section level2">
<h2>Using caret R package</h2>
<p>The <code>caret</code> R package can automatically train the model and assess the model accuracy using k-fold cross-validation Chapter @ref(cross-validation).</p>
<pre class="r"><code>library(klaR)
# Build the model
set.seed(123)
model <- train(diabetes ~., data = train.data, method = "nb", 
               trControl = trainControl("cv", number = 10))
# Make predictions
predicted.classes <- model %>% predict(test.data)
# Model n accuracy
mean(predicted.classes == test.data$diabetes)</code></pre>
</div>
<div id="discussion" class="section level2">
<h2>Discussion</h2>
<p>This chapter introduces the basics of Naive Bayes classification and provides practical examples in R using the <code>klaR</code> and <code>caret</code> package.</p>
</div>


</div><!--end rdoc-->


<!-- END HTML -->]]></description>
			<pubDate>Sun, 11 Mar 2018 08:36:00 +0100</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[SVM Model: Support Vector Machine Essentials]]></title>
			<link>https://www.sthda.com/english/articles/36-classification-methods-essentials/144-svm-model-support-vector-machine-essentials/</link>
			<guid>https://www.sthda.com/english/articles/36-classification-methods-essentials/144-svm-model-support-vector-machine-essentials/</guid>
			<description><![CDATA[<!-- START HTML -->

  <div id="rdoc">





<p><strong>Support Vector Machine</strong> (or <strong>SVM</strong>) is a machine learning technique used for <em>classification</em> tasks. Briefly, SVM works by identifying the optimal decision boundary that separates data points from different groups (or classes), and then predicts the class of new observations based on this separation boundary.</p>
<p>Depending on the situations, the different groups might be separable by a linear straight line or by a non-linear boundary line.</p>
<p>Support vector machine methods can handle both linear and non-linear class boundaries. It can be used for both two-class and multi-class classification problems.</p>
<p>In real life data, the separation boundary is generally nonlinear. Technically, the SVM algorithm perform a non-linear classification using what is called the <a href="https://en.wikipedia.org/wiki/Support_vector_machine">kernel trick</a>. The most commonly used kernel transformations are <em>polynomial kernel</em> and <em>radial kernel</em>.</p>
<p>Note that, there is also an extension of the SVM for regression, called support vector regression.</p>
<p>In this chapter, we’ll describe how to build SVM classifier using the <em>caret</em> R package.</p>
<p>Contents:</p>
<div id="TOC">
<ul>
<li><a href="#loading-required-r-packages">Loading required R packages</a></li>
<li><a href="#example-of-data-set">Example of data set</a></li>
<li><a href="#svm-linear-classifier">SVM linear classifier</a></li>
<li><a href="#svm-classifier-using-non-linear-kernel">SVM classifier using Non-Linear Kernel</a></li>
<li><a href="#discussion">Discussion</a></li>
</ul>
</div>
<br/>
<div class = "small-block content-privileged-friends navr-book">
  <p>The Book:</p>
        <a href = "https://www.sthda.com/english/web/5-bookadvisor/54-machine-learning-essentials/">
          <img src = "https://www.sthda.com/english/upload/machine-learning-essentials-frontcover-200px.png" /><br/>
     Machine Learning Essentials: Practical Guide in R
      </a>
</div>
<div class="spacer"></div>


<div id="loading-required-r-packages" class="section level2">
<h2>Loading required R packages</h2>
<ul>
<li><code>tidyverse</code> for easy data manipulation and visualization</li>
<li><code>caret</code> for easy machine learning workflow</li>
</ul>
<pre class="r"><code>library(tidyverse)
library(caret)</code></pre>
</div>
<div id="example-of-data-set" class="section level2">
<h2>Example of data set</h2>
<p>Data set: <code>PimaIndiansDiabetes2</code> [in <code>mlbench</code> package], introduced in Chapter @ref(classification-in-r), for predicting the probability of being diabetes positive based on multiple clinical variables.</p>
<p>We’ll randomly split the data into training set (80% for building a predictive model) and test set (20% for evaluating the model). Make sure to set seed for reproducibility.</p>
<pre class="r"><code># Load the data
data("PimaIndiansDiabetes2", package = "mlbench")
pima.data <- na.omit(PimaIndiansDiabetes2)
# Inspect the data
sample_n(pima.data, 3)
# Split the data into training and test set
set.seed(123)
training.samples <- pima.data$diabetes %>%
  createDataPartition(p = 0.8, list = FALSE)
train.data  <- pima.data[training.samples, ]
test.data <- pima.data[-training.samples, ]</code></pre>
</div>
<div id="svm-linear-classifier" class="section level2">
<h2>SVM linear classifier</h2>
<p>In the following example variables are normalized to make their scale comparable. This is automatically done before building the SVM classifier by setting the option <code>preProcess = c("center","scale")</code>.</p>
<pre class="r"><code># Fit the model on the training set
set.seed(123)
model <- train(
  diabetes ~., data = train.data, method = "svmLinear",
  trControl = trainControl("cv", number = 10),
  preProcess = c("center","scale")
  )
# Make predictions on the test data
predicted.classes <- model %>% predict(test.data)
head(predicted.classes)</code></pre>
<pre><code>## [1] neg pos neg pos pos neg
## Levels: neg pos</code></pre>
<pre class="r"><code># Compute model accuracy rate
mean(predicted.classes == test.data$diabetes)</code></pre>
<pre><code>## [1] 0.782</code></pre>
<p>Note that, there is a tuning parameter <code>C</code>, also known as <em>Cost</em>, that determines the possible misclassifications. It essentially imposes a penalty to the model for making an error: the higher the value of C, the less likely it is that the SVM algorithm will misclassify a point.</p>
<p>By default <code>caret</code> builds the SVM linear classifier using <code>C = 1</code>. You can check this by typing <code>model</code> in R console.</p>
<p>It’s possible to automatically compute SVM for different values of `C and to choose the optimal one that maximize the model cross-validation accuracy.</p>
<p>The following R code compute SVM for a grid values of <code>C</code> and choose automatically the final model for predictions:</p>
<pre class="r"><code># Fit the model on the training set
set.seed(123)
model <- train(
  diabetes ~., data = train.data, method = "svmLinear",
  trControl = trainControl("cv", number = 10),
  tuneGrid = expand.grid(C = seq(0, 2, length = 20)),
  preProcess = c("center","scale")
  )
# Plot model accuracy vs different values of Cost
plot(model)</code></pre>
<p><img src="https://www.sthda.com/english/sthda-upload/figures/machine-learning-essentials/034-support-vector-machine-svm-linear-classifier-cost-1.png" width="384" /></p>
<pre class="r"><code># Print the best tuning parameter C that
# maximizes model accuracy
model$bestTune</code></pre>
<pre><code>##       C
## 12 1.16</code></pre>
<pre class="r"><code># Make predictions on the test data
predicted.classes <- model %>% predict(test.data)
# Compute model accuracy rate
mean(predicted.classes == test.data$diabetes)</code></pre>
<pre><code>## [1] 0.782</code></pre>
</div>
<div id="svm-classifier-using-non-linear-kernel" class="section level2">
<h2>SVM classifier using Non-Linear Kernel</h2>
<p>To build a non-linear SVM classifier, we can use either polynomial kernel or radial kernel function. Again, the <code>caret</code> package can be used to easily computes the polynomial and the radial SVM non-linear models.</p>
<p>The package automatically choose the optimal values for the model tuning parameters, where optimal is defined as values that maximize the model accuracy.</p>
<ul>
<li><strong>Computing SVM using radial basis kernel</strong>:</li>
</ul>
<pre class="r"><code># Fit the model on the training set
set.seed(123)
model <- train(
  diabetes ~., data = train.data, method = "svmRadial",
  trControl = trainControl("cv", number = 10),
  preProcess = c("center","scale"),
  tuneLength = 10
  )
# Print the best tuning parameter sigma and C that
# maximizes model accuracy
model$bestTune</code></pre>
<pre><code>##   sigma    C
## 1 0.136 0.25</code></pre>
<pre class="r"><code># Make predictions on the test data
predicted.classes <- model %>% predict(test.data)
# Compute model accuracy rate
mean(predicted.classes == test.data$diabetes)</code></pre>
<pre><code>## [1] 0.795</code></pre>
<ul>
<li><strong>Computing SVM using polynomial basis kernel</strong>:</li>
</ul>
<pre class="r"><code># Fit the model on the training set
set.seed(123)
model <- train(
  diabetes ~., data = train.data, method = "svmPoly",
  trControl = trainControl("cv", number = 10),
  preProcess = c("center","scale"),
  tuneLength = 4
  )
# Print the best tuning parameter sigma and C that
# maximizes model accuracy
model$bestTune</code></pre>
<pre><code>##   degree scale C
## 8      1  0.01 2</code></pre>
<pre class="r"><code># Make predictions on the test data
predicted.classes <- model %>% predict(test.data)
# Compute model accuracy rate
mean(predicted.classes == test.data$diabetes)</code></pre>
<pre><code>## [1] 0.795</code></pre>
<div class="success">
<p>
In our examples, it can be seen that the SVM classifier using non-linear kernel gives a better result compared to the linear model.
</p>
</div>
</div>
<div id="discussion" class="section level2">
<h2>Discussion</h2>
<p>This chapter describes how to use support vector machine for classification tasks. Other alternatives exist, such as logistic regression (Chapter @ref(logistic-regression)).</p>
<p>You need to assess the performance of different methods on your data in order to choose the best one.</p>
</div>


</div><!--end rdoc-->


<!-- END HTML -->]]></description>
			<pubDate>Sun, 11 Mar 2018 08:28:00 +0100</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[Evaluation of Classification Model Accuracy: Essentials]]></title>
			<link>https://www.sthda.com/english/articles/36-classification-methods-essentials/143-evaluation-of-classification-model-accuracy-essentials/</link>
			<guid>https://www.sthda.com/english/articles/36-classification-methods-essentials/143-evaluation-of-classification-model-accuracy-essentials/</guid>
			<description><![CDATA[<!-- START HTML -->

  <div id="rdoc">





<p>After building a predictive classification model, you need to <strong>evaluate the performance of the model</strong>, that is how good the model is in predicting the outcome of new observations test data that have been not used to train the model.</p>
<p>In other words you need to estimate the model prediction <em>accuracy</em> and prediction errors using a new test data set. Because we know the actual outcome of observations in the test data set, the performance of the predictive model can be assessed by comparing the predicted outcome values against the known outcome values.</p>
<p>This chapter describes the commonly used metrics and methods for assessing the performance of predictive classification models, including:</p>
<ul>
<li><strong>Average classification accuracy</strong>, representing the proportion of correctly classified observations.</li>
<li><strong>Confusion matrix</strong>, which is 2x2 table showing four parameters, including the number of true positives, true negatives, false negatives and false positives.</li>
<li><strong>Precision, Recall and Specificity</strong>, which are three major performance metrics describing a predictive classification model</li>
<li><strong>ROC curve</strong>, which is a graphical summary of the overall performance of the model, showing the proportion of true positives and false positives at all possible values of probability cutoff. The <strong>Area Under the Curve</strong> (<strong>AUC</strong>) summarizes the overall performance of the classifier.</li>
</ul>
<p>We’ll provide practical examples in R to compute these above metrics, as well as, to create the ROC plot.</p>
<p>Contents:</p>
<div id="TOC">
<ul>
<li><a href="#loading-required-r-packages">Loading required R packages</a></li>
<li><a href="#building-a-classification-model">Building a classification model</a></li>
<li><a href="#overall-classification-accuracy">Overall classification accuracy</a></li>
<li><a href="#confusion-matrix">Confusion matrix</a></li>
<li><a href="#precision-recall-and-specificity">Precision, Recall and Specificity</a></li>
<li><a href="#roc">ROC curve</a><ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#computing-and-plotting-roc-curve">Computing and plotting ROC curve</a></li>
<li><a href="#multiple-roc-curves">Multiple ROC curves</a></li>
</ul></li>
<li><a href="#multiclass-settings">Multiclass settings</a></li>
<li><a href="#discussion">Discussion</a></li>
</ul>
</div>
<br/>
<div class = "small-block content-privileged-friends navr-book">
  <p>The Book:</p>
        <a href = "https://www.sthda.com/english/web/5-bookadvisor/54-machine-learning-essentials/">
          <img src = "https://www.sthda.com/english/upload/machine-learning-essentials-frontcover-200px.png" /><br/>
     Machine Learning Essentials: Practical Guide in R
      </a>
</div>
<div class="spacer"></div>


<div id="loading-required-r-packages" class="section level2">
<h2>Loading required R packages</h2>
<ul>
<li><code>tidyverse</code> for easy data manipulation and visualization</li>
<li><code>caret</code> for easy machine learning workflow</li>
</ul>
<pre class="r"><code>library(tidyverse)
library(caret)</code></pre>
</div>
<div id="building-a-classification-model" class="section level2">
<h2>Building a classification model</h2>
<p>To keep things simple, we’ll perform a binary classification, where the outcome variable can have only two possible values: negative vs positive.</p>
<p>We’ll compute an example of linear discriminant analysis model using the <code>PimaIndiansDiabetes2</code> [mlbench package], introduced in Chapter @ref(classification-in-r), for predicting the probability of diabetes test positivity based on clinical variables.</p>
<ol style="list-style-type: decimal">
<li>Split the data into training (80%, used to build the model) and test set (20%, used to evaluate the model performance):</li>
</ol>
<pre class="r"><code># Load the data
data("PimaIndiansDiabetes2", package = "mlbench")
pima.data <- na.omit(PimaIndiansDiabetes2)
# Inspect the data
sample_n(pima.data, 3)
# Split the data into training and test set
set.seed(123)
training.samples <- pima.data$diabetes %>%
  createDataPartition(p = 0.8, list = FALSE)

train.data  <- pima.data[training.samples, ]
test.data <- pima.data[-training.samples, ]</code></pre>
<ol start="2" style="list-style-type: decimal">
<li>Fit the LDA model on the training set and make predictions on the test data:</li>
</ol>
<pre class="r"><code>library(MASS)
# Fit LDA
fit <- lda(diabetes ~., data = train.data)
# Make predictions on the test data
predictions <- predict(fit, test.data)
prediction.probabilities <- predictions$posterior[,2]

predicted.classes <- predictions$class 
observed.classes <- test.data$diabetes</code></pre>
</div>
<div id="overall-classification-accuracy" class="section level2">
<h2>Overall classification accuracy</h2>
<p>The overall <strong>classification accuracy</strong> rate corresponds to the proportion of observations that have been correctly classified. Determining the raw classification accuracy is the first step in assessing the performance of a model. </p>
<p>Inversely, the <strong>classification error rate</strong> is defined as the proportion of observations that have been misclassified. <code>Error rate = 1 - accuracy</code></p>
<p>The raw classification accuracy and error can be easily computed by comparing the observed classes in the test data against the predicted classes by the model:</p>
<pre class="r"><code>accuracy <- mean(observed.classes == predicted.classes)
accuracy</code></pre>
<pre><code>## [1] 0.808</code></pre>
<pre class="r"><code>error <- mean(observed.classes != predicted.classes)
error</code></pre>
<pre><code>## [1] 0.192</code></pre>
<div class="success">
<p>
From the output above, the linear discriminant analysis correctly predicted the individual outcome in 81% of the cases. This is by far better than random guessing. The misclassification error rate can be calculated as 100 - 81% = 19%.
</p>
</div>
<p>In our example, a binary classifier can make two types of errors:</p>
<ul>
<li>it can incorrectly assign an individual who is diabetes-positive to the diabetes-negative category</li>
<li>it can incorrectly assign an individual who is diabetes-negative to the diabetes-positive category.</li>
</ul>
<p>The proportion of theses two types of errors can be determined by creating a <strong>confusion matrix</strong>, which compare the predicted outcome values against the known outcome values.</p>
</div>
<div id="confusion-matrix" class="section level2">
<h2>Confusion matrix</h2>
<p>The R function <code>table()</code> can be used to produce a <strong>confusion matrix</strong> in order to determine how many observations were correctly or incorrectly classified. It compares the observed and the predicted outcome values and shows the number of correct and incorrect predictions categorized by type of outcome. </p>
<pre class="r"><code># Confusion matrix, number of cases
table(observed.classes, predicted.classes)</code></pre>
<pre><code>##                 predicted.classes
## observed.classes neg pos
##              neg  48   4
##              pos  11  15</code></pre>
<pre class="r"><code># Confusion matrix, proportion of cases
table(observed.classes, predicted.classes) %>% 
  prop.table() %>% round(digits = 3)</code></pre>
<pre><code>##                 predicted.classes
## observed.classes   neg   pos
##              neg 0.615 0.051
##              pos 0.141 0.192</code></pre>
<div class="block">
<p>
The diagonal elements of the confusion matrix indicate correct predictions, while the off-diagonals represent incorrect predictions. So, the correct classification rate is the sum of the number on the diagonal divided by the sample size in the test data. In our example, that is (48 + 15)/78 = 81%.
</p>
</div>
<p>Each cell of the table has an important meaning:</p>
<p><img src="https://www.sthda.com/english/sthda-upload/images/machine-learning-essentials/confusion-matrix.png" alt="confusion matrix" /></p>
<ul>
<li><strong>True positives</strong> (d): these are cases in which we predicted the individuals would be diabetes-positive and they were.</li>
<li><strong>True negatives</strong> (a): We predicted diabetes-negative, and the individuals were diabetes-negative.</li>
<li><strong>False positives</strong> (b): We predicted diabetes-positive, but the individuals didn’t actually have diabetes. (Also known as a <em>Type I error</em>.)</li>
<li><strong>False negatives</strong> (c): We predicted diabetes-negative, but they did have diabetes. (Also known as a <em>Type II error</em>.)</li>
</ul>
<div class="success">
<p>
Technically the raw prediction accuracy of the model is defined as <code>(TruePositives + TrueNegatives)/SampleSize</code>.
</p>
</div>
</div>
<div id="precision-recall-and-specificity" class="section level2">
<h2>Precision, Recall and Specificity</h2>
<p>In addition to the raw classification accuracy, there are many other metrics that are widely used to examine the performance of a classification model, including:</p>
<p><strong>Precision</strong>, which is the proportion of true positives among all the individuals that have been predicted to be diabetes-positive by the model. This represents the accuracy of a predicted positive outcome. <code>Precision = TruePositives/(TruePositives + FalsePositives)</code>.</p>
<p><strong>Sensitivity</strong> (or <strong>Recall</strong>), which is the <strong>True Positive Rate</strong> (TPR) or the proportion of identified positives among the diabetes-positive population (class = 1). <code>Sensitivity = TruePositives/(TruePositives + FalseNegatives)</code>. </p>
<p><strong>Specificity</strong>, which measures the <strong>True Negative Rate</strong> (TNR), that is the proportion of identified negatives among the diabetes-negative population (class = 0). <code>Specificity = TrueNegatives/(TrueNegatives + FalseNegatives)</code>. </p>
<p><strong>False Positive Rate</strong> (FPR), which represents the proportion of identified positives among the healthy individuals (i.e. diabetes-negative). This can be seen as a false alarm. The FPR can be also calculated as <code>1-specificity</code>. When positives are rare, the FPR can be high, leading to the situation where a predicted positive is most likely a negative.</p>
<p><strong>Sensitivy</strong> and <strong>Specificity</strong> are commonly used to measure the performance of a predictive model.</p>
<p>These above mentioned metrics can be easily computed using the function <code>confusionMatrix()</code> [caret package].</p>
<p>In two-class setting, you might need to specify the optional argument <code>positive</code>, which is a character string for the factor level that corresponds to a “positive” result (if that makes sense for your data). If there are only two factor levels, the default is to use the first level as the “positive” result.</p>
<pre class="r"><code>confusionMatrix(predicted.classes, observed.classes,
                positive = "pos")</code></pre>
<pre><code>## Confusion Matrix and Statistics
## 
##           Reference
## Prediction neg pos
##        neg  48  11
##        pos   4  15
##                                         
##                Accuracy : 0.808         
##                  95% CI : (0.703, 0.888)
##     No Information Rate : 0.667         
##     P-Value [Acc > NIR] : 0.00439       
##                                         
##                   Kappa : 0.536         
##  Mcnemar&amp;#39;s Test P-Value : 0.12134       
##                                         
##             Sensitivity : 0.577         
##             Specificity : 0.923         
##          Pos Pred Value : 0.789         
##          Neg Pred Value : 0.814         
##              Prevalence : 0.333         
##          Detection Rate : 0.192         
##    Detection Prevalence : 0.244         
##       Balanced Accuracy : 0.750         
##                                         
##        &amp;#39;Positive&amp;#39; Class : pos           
## </code></pre>
<p>The above results show different statistical metrics among which the most important include:</p>
<ul>
<li>the cross-tabulation between prediction and reference known outcome</li>
<li>the model accuracy, 81%</li>
<li>the <a href="https://en.wikipedia.org/wiki/Cohen%27s_kappa">kappa</a> (54%), which is the accuracy corrected for chance.</li>
</ul>
<div class="success">
<p>
In our example, the sensitivity is ~58%, that is the proportion of diabetes-positive individuals that were correctly identified by the model as diabetes-positive.
</p>
<p>
The specificity of the model is ~92%, that is the proportion of diabetes-negative individuals that were correctly identified by the model as diabetes-negative.
</p>
<p>
The model precision or the proportion of positive predicted value is 79%.
</p>
</div>
<p>In medical science, sensitivity and specificity are two important metrics that characterize the performance of classifier or screening test. The importance between sensitivity and specificity depends on the context. Generally, we are concerned with one of these metrics.</p>
<p>In medical diagnostic, such as in our example, we are likely to be more concerned with minimal wrong positive diagnosis. So, we are more concerned about high Specificity. Here, the model specificity is 92%, which is very good.</p>
<p>In some situations, we may be more concerned with tuning a model so that the sensitivity/precision is improved. To this end, you can test different probability cutoff to decide which individuals are positive and which are negative.</p>
<p>Note that, here we have used <code>p > 0.5</code> as the probability threshold above which, we declare the concerned individuals as diabetes positive. However, if we are concerned about incorrectly predicting the diabetes-positive status for individuals who are truly positive, then we can consider lowering this threshold: <code>p > 0.2</code>.</p>
</div>
<div id="roc" class="section level2">
<h2>ROC curve</h2>
<div id="introduction" class="section level3">
<h3>Introduction</h3>
<p>The <strong>ROC curve</strong> (or <strong>receiver operating characteristics curve</strong> ) is a popular graphical measure for assessing the performance or the accuracy of a classifier, which corresponds to the total proportion of correctly classified observations.</p>
<p>For example, the accuracy of a medical diagnostic test can be assessed by considering the two possible types of errors: false positives, and false negatives. In classification point of view, the test will be declared positive when the corresponding predicted probability, returned by the classifier algorithm, is above a fixed threshold. This threshold is generally set to 0.5 (i.e., 50%), which corresponds to the random guessing probability.</p>
<p>So, in reference to our diabetes data example, for a given fixed probability cutoff:</p>
<ul>
<li>the <strong>true positive rate</strong> (or fraction) is the proportion of identified positives among the diabetes-positive population. Recall that, this is also known as the <strong>sensitivity</strong> of the predictive classifier model.</li>
<li>and the <strong>false positive rate</strong> is the proportion of identified positives among the healthy (i.e. diabetes-negative) individuals. This is also defined as <code>1-specificity</code>, where <strong>specificity</strong> measures the <strong>true negative rate</strong>, that is the proportion of identified negatives among the diabetes-negative population.</li>
</ul>
<p>Since we don’t usually know the probability cutoff in advance, the ROC curve is typically used to plot the true positive rate (or sensitivity on y-axis) against the false positive rate (or “1-specificity” on x-axis) at all possible probability cutoffs. This shows the trade off between the rate at which you can correctly predict something with the rate of incorrectly predicting something. Another visual representation of the ROC plot is to simply display the sensitive against the specificity.</p>
<div class="block">
<p>
The <strong>Area Under the Curve</strong> (<strong>AUC</strong>) summarizes the overall performance of the classifier, over all possible probability cutoffs. It represents the ability of a classification algorithm to distinguish 1s from 0s (i.e, events from non-events or positives from negatives).
</p>
</div>
<p>For a good model, the ROC curve should rise steeply, indicating that the true positive rate (y-axis) increases faster than the false positive rate (x-axis) as the probability threshold decreases.</p>
<p>So, the “ideal point” is the top left corner of the graph, that is a false positive rate of zero, and a true positive rate of one. This is not very realistic, but it does mean that the larger the AUC the better the classifier.</p>
<div class="block">
<p>
The AUC metric varies between 0.50 (random classifier) and 1.00. Values above 0.80 is an indication of a good classifier.
</p>
</div>
<p>In this section, we’ll show you how to compute and plot ROC curve in R for two-class and multiclass classification tasks. We’ll use the linear discriminant analysis to classify individuals into groups.</p>
</div>
<div id="computing-and-plotting-roc-curve" class="section level3">
<h3>Computing and plotting ROC curve</h3>
<p>The ROC analysis can be easily performed using the R package <code>pROC</code>.</p>
<pre class="r"><code>library(pROC)
# Compute roc
res.roc <- roc(observed.classes, prediction.probabilities)
plot.roc(res.roc, print.auc = TRUE)</code></pre>
<p><img src="https://www.sthda.com/english/sthda-upload/figures/machine-learning-essentials/035-classification-model-evaluation-r-base-roc-plot-1.png" width="384" /></p>
<p>The gray diagonal line represents a classifier no better than random chance.</p>
<p>A highly performant classifier will have an ROC that rises steeply to the top-left corner, that is it will correctly identify lots of positives without misclassifying lots of negatives as positives.</p>
<div class="success">
<p>
In our example, the AUC is 0.85, which is close to the maximum ( max = 1). So, our classifier can be considered as very good. A classifier that performs no better than chance is expected to have an AUC of 0.5 when evaluated on an independent test set not used to train the model.
</p>
</div>
<p>If we want a classifier model with a specificity of at least 60%, then the sensitivity is about 0.88%. The corresponding probability threshold can be extract as follow:</p>
<pre class="r"><code># Extract some interesting results
roc.data <- data_frame(
  thresholds = res.roc$thresholds,
  sensitivity = res.roc$sensitivities,
  specificity = res.roc$specificities
)
# Get the probality threshold for specificity = 0.6
roc.data %>% filter(specificity >= 0.6)</code></pre>
<pre><code>## # A tibble: 44 x 3
##   thresholds sensitivity specificity
##        <dbl>       <dbl>       <dbl>
## 1      0.111       0.885       0.615
## 2      0.114       0.885       0.635
## 3      0.114       0.885       0.654
## 4      0.115       0.885       0.673
## 5      0.119       0.885       0.692
## 6      0.131       0.885       0.712
## # ... with 38 more rows</code></pre>
<p>The best threshold with the highest sum sensitivity + specificity can be printed as follow. There might be more than one threshold.</p>
<pre class="r"><code>plot.roc(res.roc, print.auc = TRUE, print.thres = "best")</code></pre>
<p><img src="https://www.sthda.com/english/sthda-upload/figures/machine-learning-essentials/035-classification-model-evaluation-roc-plot-best-threshold-1.png" width="384" /></p>
<div class="success">
<p>
Here, the best probability cutoff is 0.335 resulting to a predictive classifier with a specificity of 0.84 and a sensitivity of 0.660.
</p>
</div>
<p>Note that, <code>print.thres</code> can be also a numeric vector containing a direct definition of the thresholds to display:</p>
<pre class="r"><code>plot.roc(res.roc, print.thres = c(0.3, 0.5, 0.7))</code></pre>
</div>
<div id="multiple-roc-curves" class="section level3">
<h3>Multiple ROC curves</h3>
<p>If you have grouping variables in your data, you might wish to create multiple ROC curves on the same plot. This can be done using ggplot2.</p>
<pre class="r"><code># Create some grouping variable
glucose <- ifelse(test.data$glucose < 127.5, "glu.low", "glu.high")
age <- ifelse(test.data$age < 28.5, "young", "old")
roc.data <- roc.data %>%
  filter(thresholds !=-Inf) %>%
  mutate(glucose = glucose, age =  age)

# Create ROC curve
ggplot(roc.data, aes(specificity, sensitivity)) + 
  geom_path(aes(color = age))+
  scale_x_reverse(expand = c(0,0))+
  scale_y_continuous(expand = c(0,0))+
  geom_abline(intercept = 1, slope = 1, linetype = "dashed")+
  theme_bw()</code></pre>
<p><img src="https://www.sthda.com/english/sthda-upload/figures/machine-learning-essentials/035-classification-model-evaluation-ggplot2-roc-curve-1.png" width="384" /></p>
</div>
</div>
<div id="multiclass-settings" class="section level2">
<h2>Multiclass settings</h2>
<p>We start by building a linear discriminant model using the <code>iris</code> data set, which contains the length and width of sepals and petals for three iris species. We want to predict the species based on the sepal and petal parameters using LDA.</p>
<pre class="r"><code># Load the data
data("iris")
# Split the data into training (80%) and test set (20%)
set.seed(123)
training.samples <- iris$Species %>%
  createDataPartition(p = 0.8, list = FALSE)
train.data <- iris[training.samples, ]
test.data <- iris[-training.samples, ]
# Build the model on the train set
library(MASS)
model <- lda(Species ~., data = train.data)</code></pre>
<p>Performance metrics (sensitivity, specificity, …) of the predictive model can be calculated, separately for each class, comparing each factor level to the remaining levels (i.e. a “one versus all” approach).</p>
<pre class="r"><code># Make predictions on the test data
predictions <- model %>% predict(test.data)
# Model accuracy
confusionMatrix(predictions$class, test.data$Species)</code></pre>
<pre><code>## Confusion Matrix and Statistics
## 
##             Reference
## Prediction   setosa versicolor virginica
##   setosa         10          0         0
##   versicolor      0         10         0
##   virginica       0          0        10
## 
## Overall Statistics
##                                     
##                Accuracy : 1         
##                  95% CI : (0.884, 1)
##     No Information Rate : 0.333     
##     P-Value [Acc > NIR] : 4.86e-15  
##                                     
##                   Kappa : 1         
##  Mcnemar&amp;#39;s Test P-Value : NA        
## 
## Statistics by Class:
## 
##                      Class: setosa Class: versicolor Class: virginica
## Sensitivity                  1.000             1.000            1.000
## Specificity                  1.000             1.000            1.000
## Pos Pred Value               1.000             1.000            1.000
## Neg Pred Value               1.000             1.000            1.000
## Prevalence                   0.333             0.333            0.333
## Detection Rate               0.333             0.333            0.333
## Detection Prevalence         0.333             0.333            0.333
## Balanced Accuracy            1.000             1.000            1.000</code></pre>
<p>Note that, the ROC curves are typically used in binary classification but not for multiclass classification problems.</p>
</div>
<div id="discussion" class="section level2">
<h2>Discussion</h2>
<p>This chapter described different metrics for evaluating the performance of classification models. These metrics include:</p>
<ul>
<li>classification accuracy,</li>
<li>confusion matrix,</li>
<li>Precision, Recall and Specificity,</li>
<li>and ROC curve</li>
</ul>
<p>To evaluate the performance of regression models, read the Chapter @ref(regression-model-accuracy-metrics).</p>
</div>


</div><!--end rdoc-->


<!-- END HTML -->]]></description>
			<pubDate>Sun, 11 Mar 2018 08:17:00 +0100</pubDate>
			
		</item>
		
	</channel>
</rss>
