<?xml version="1.0" encoding="UTF-8" ?>
<!-- RSS generated by PHPBoost on Fri, 24 Apr 2026 06:04:29 +0200 -->

<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
	<channel>
		<title><![CDATA[Last articles - STHDA : Model Selection Essentials in R]]></title>
		<atom:link href="https://www.sthda.com/english/syndication/rss/articles/37" rel="self" type="application/rss+xml"/>
		<link>https://www.sthda.com</link>
		<description><![CDATA[Last articles - STHDA : Model Selection Essentials in R]]></description>
		<copyright>(C) 2005-2026 PHPBoost</copyright>
		<language>en</language>
		<generator>PHPBoost</generator>
		
		
		<item>
			<title><![CDATA[Best Subsets Regression Essentials in R]]></title>
			<link>https://www.sthda.com/english/articles/37-model-selection-essentials-in-r/155-best-subsets-regression-essentials-in-r/</link>
			<guid>https://www.sthda.com/english/articles/37-model-selection-essentials-in-r/155-best-subsets-regression-essentials-in-r/</guid>
			<description><![CDATA[<!-- START HTML -->

  <div id="rdoc">





<p>The <strong>best subsets regression</strong> is a model selection approach that consists of testing all possible combination of the predictor variables, and then selecting the best model according to some statistical criteria.</p>
<p>In this chapter, we’ll describe how to compute best subsets regression using 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="#example-of-data">Example of data</a></li>
<li><a href="#computing-best-subsets-regression">Computing best subsets regression</a></li>
<li><a href="#choosing-the-optimal-model">Choosing the optimal model</a><ul>
<li><a href="#model-selection-criteria-adjusted-r2-cp-and-bic">Model selection criteria: Adjusted R2, Cp and BIC</a></li>
<li><a href="#k-fold-cross-validation">K-fold cross-validation</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>leaps</code>, for computing best subsets regression</li>
</ul>
<pre class="r"><code>library(tidyverse)
library(caret)
library(leaps)</code></pre>
</div>
<div id="example-of-data" class="section level2">
<h2>Example of data</h2>
<p>We’ll use the built-in R <code>swiss</code> data, introduced in the Chapter @ref(regression-analysis), for predicting fertility score on the basis of socio-economic indicators.</p>
<pre class="r"><code># Load the data
data("swiss")
# Inspect the data
sample_n(swiss, 3)</code></pre>
</div>
<div id="computing-best-subsets-regression" class="section level2">
<h2>Computing best subsets regression</h2>
<p>The R function <code>regsubsets()</code> [<code>leaps</code> package] can be used to identify different best models of different sizes.

You need to specify the option <code>nvmax</code>, which represents the maximum number of predictors to incorporate in the model. For example, if <code>nvmax = 5</code>, the function will return up to the best 5-variables model, that is, it returns the best 1-variable model, the best 2-variables model, …, the best 5-variables models.</p>
<p>In our example, we have only 5 predictor variables in the data. So, we’ll use <code>nvmax = 5</code>.</p>
<pre class="r"><code>models <- regsubsets(Fertility~., data = swiss, nvmax = 5)
summary(models)</code></pre>
<pre><code>## Subset selection object
## Call: st_build()
## 5 Variables  (and intercept)
##                  Forced in Forced out
## Agriculture          FALSE      FALSE
## Examination          FALSE      FALSE
## Education            FALSE      FALSE
## Catholic             FALSE      FALSE
## Infant.Mortality     FALSE      FALSE
## 1 subsets of each size up to 5
## Selection Algorithm: exhaustive
##          Agriculture Examination Education Catholic Infant.Mortality
## 1  ( 1 ) " "         " "         "*"       " "      " "             
## 2  ( 1 ) " "         " "         "*"       "*"      " "             
## 3  ( 1 ) " "         " "         "*"       "*"      "*"             
## 4  ( 1 ) "*"         " "         "*"       "*"      "*"             
## 5  ( 1 ) "*"         "*"         "*"       "*"      "*"</code></pre>
<p>The function <code>summary()</code> reports the best set of variables for each model size. From the output above, an asterisk specifies that a given variable is included in the corresponding model.</p>
<p>For example, it can be seen that the best 2-variables model contains only Education and Catholic variables (<code>Fertility ~ Education + Catholic</code>). The best three-variable model is (<code>Fertility ~ Education + Catholic + Infant.mortality</code>), and so forth.</p>
<p>A natural question is: which of these best models should we finally choose for our predictive analytics?</p>
</div>
<div id="choosing-the-optimal-model" class="section level2">
<h2>Choosing the optimal model</h2>
<p>To answer to this questions, you need some statistical metrics or strategies to compare the overall performance of the models and to choose the best one. You need to estimate the prediction error of each model and to select the one with the lower prediction error.</p>
<div id="model-selection-criteria-adjusted-r2-cp-and-bic" class="section level3">
<h3>Model selection criteria: Adjusted R2, Cp and BIC</h3>
<p>The <code>summary()</code> function returns some metrics - Adjusted R2, Cp and BIC (see Chapter @ref(regression-model-accuracy-metrics)) - allowing us to identify the best overall model, where best is defined as the model that maximize the adjusted R2 and minimize the prediction error (RSS, cp and BIC).</p>
<p>The adjusted R2 represents the proportion of variation, in the outcome, that are explained by the variation in predictors values. the higher the adjusted R2, the better the model.</p>
<p>The best model, according to each of these metrics, can be extracted as follow:</p>
<pre class="r"><code>res.sum <- summary(models)
data.frame(
  Adj.R2 = which.max(res.sum$adjr2),
  CP = which.min(res.sum$cp),
  BIC = which.min(res.sum$bic)
)</code></pre>
<pre><code>##   Adj.R2 CP BIC
## 1      5  4   4</code></pre>
<p>There is no single correct solution to model selection, each of these criteria will lead to slightly different models. Remember that, <a href="https://en.wikipedia.org/wiki/All_models_are_wrong">“All models are wrong, some models are useful”</a>.</p>
<p>Here, adjusted R2 tells us that the best model is the one with all the 5 predictor variables. However, using the BIC and Cp criteria, we should go for the model with 4 variables.</p>
<p>So, we have different “best” models depending on which metrics we consider. We need additional strategies.</p>
<p>Note also that the adjusted R2, BIC and Cp are calculated on the training data that have been used to fit the model. This means that, the model selection, using these metrics, is possibly subject to overfitting and may not perform as well when applied to new data.</p>
<p>A more rigorous approach is to select a models based on the prediction error computed on a new test data using k-fold cross-validation techniques (Chapter @ref(cross-validation)).</p>
</div>
<div id="k-fold-cross-validation" class="section level3">
<h3>K-fold cross-validation</h3>
<p>The <strong>k-fold Cross-validation</strong> consists of first dividing the data into k subsets, also known as k-fold, where k is generally set to 5 or 10. Each subset (10%) serves successively as test data set and the remaining subset (90%) as training data. The average cross-validation error is computed as the model prediction error.</p>
<p>The k-fold cross-validation can be easily computed using the function <code>train()</code> [<code>caret</code> package] (Chapter @ref(cross-validation)).</p>
<p>Here, we’ll follow the procedure below:</p>
<ol style="list-style-type: decimal">
<li>Extract the different model formulas from the <code>models</code> object</li>
<li>Train a linear model on the formula using k-fold cross-validation (with k= 5) and compute the prediction error of each model</li>
</ol>
<p>We start by defining two helper functions:</p>
<ol style="list-style-type: decimal">
<li><code>get_model_formula()</code>, allowing to access easily the formula of the models returned by the function <code>regsubsets()</code>. Copy and paste the following code in your R console:</li>
</ol>
<pre class="r"><code># id: model id
# object: regsubsets object
# data: data used to fit regsubsets
# outcome: outcome variable
get_model_formula <- function(id, object, outcome){
  # get models data
  models <- summary(object)$which[id,-1]
  # Get outcome variable
  #form <- as.formula(object$call[[2]])
  #outcome <- all.vars(form)[1]
  # Get model predictors
  predictors <- names(which(models == TRUE))
  predictors <- paste(predictors, collapse = "+")
  # Build model formula
  as.formula(paste0(outcome, "~", predictors))
}</code></pre>
<p>For example to have the best 3-variable model formula, type this:</p>
<pre class="r"><code>get_model_formula(3, models, "Fertility")</code></pre>
<pre><code>## Fertility ~ Education + Catholic + Infant.Mortality
## <environment: 0x1164b8f08></code></pre>
<ol start="2" style="list-style-type: decimal">
<li><code>get_cv_error()</code>, to get the cross-validation (CV) error for a given model:</li>
</ol>
<pre class="r"><code>get_cv_error <- function(model.formula, data){
  set.seed(1)
  train.control <- trainControl(method = "cv", number = 5)
  cv <- train(model.formula, data = data, method = "lm",
              trControl = train.control)
  cv$results$RMSE
}</code></pre>
<p>Finally, use the above defined helper functions to compute the prediction error of the different best models returned by the <code>regsubsets()</code> function:</p>
<pre class="r"><code># Compute cross-validation error
model.ids <- 1:5
cv.errors <-  map(model.ids, get_model_formula, models, "Fertility") %>%
  map(get_cv_error, data = swiss) %>%
  unlist()
cv.errors</code></pre>
<pre><code>## [1] 9.42 8.45 7.93 7.68 7.92</code></pre>
<pre class="r"><code># Select the model that minimize the CV error
which.min(cv.errors)</code></pre>
<pre><code>## [1] 4</code></pre>
<p>It can be seen that the model with 4 variables is the best model. It has the lower prediction error. The regression coefficients of this model can be extracted as follow:</p>
<pre class="r"><code>coef(models, 4)</code></pre>
<pre><code>##      (Intercept)      Agriculture        Education         Catholic 
##           62.101           -0.155           -0.980            0.125 
## Infant.Mortality 
##            1.078</code></pre>
</div>
</div>
<div id="discussion" class="section level2">
<h2>Discussion</h2>
<p>This chapter describes the best subsets regression approach for choosing the best linear regression model that explains our data.</p>
<p>Note that, this method is computationally expensive and becomes unfeasible for a large data set with many variables. A better alternative is provided by the <strong>stepwise regression</strong> method. See Chapter @ref(stepwise-regression).</p>
</div>


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


<!-- END HTML -->]]></description>
			<pubDate>Sun, 11 Mar 2018 09:44:00 +0100</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[Stepwise Regression Essentials in R]]></title>
			<link>https://www.sthda.com/english/articles/37-model-selection-essentials-in-r/154-stepwise-regression-essentials-in-r/</link>
			<guid>https://www.sthda.com/english/articles/37-model-selection-essentials-in-r/154-stepwise-regression-essentials-in-r/</guid>
			<description><![CDATA[<!-- START HTML -->

  <div id="rdoc">





<p>The <strong>stepwise regression</strong> (or stepwise selection) consists of iteratively adding and removing predictors, in the predictive model, in order to find the subset of variables in the data set resulting in the best performing model, that is a model that lowers prediction error.</p>
<p>There are three strategies of stepwise regression <span class="citation">(James et al. 2014,<span class="citation">P. Bruce and Bruce (2017)</span>)</span>:</p>
<ol style="list-style-type: decimal">
<li><strong>Forward selection</strong>, which starts with no predictors in the model, iteratively adds the most contributive predictors, and stops when the improvement is no longer statistically significant.</li>
<li><strong>Backward selection</strong> (or <strong>backward elimination</strong>), which starts with all predictors in the model (full model), iteratively removes the least contributive predictors, and stops when you have a model where all predictors are statistically significant.</li>
<li><strong>Stepwise selection</strong> (or sequential replacement), which is a combination of forward and backward selections. You start with no predictors, then sequentially add the most contributive predictors (like forward selection). After adding each new variable, remove any variables that no longer provide an improvement in the model fit (like backward selection).</li>
</ol>
<div class="block">
<p>
Note that,
</p>
<ul>
<li>
forward selection and stepwise selection can be applied in the high-dimensional configuration, where the number of samples n is inferior to the number of predictors p, such as in genomic fields.
</li>
<li>
Backward selection requires that the number of samples n is larger than the number of variables p, so that the full model can be fit.
</li>
</ul>
</div>
<p>In this chapter, you’ll learn how to compute the stepwise regression methods 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="#computing-stepwise-regression">Computing stepwise regression</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>
<li><code>leaps</code>, for computing stepwise regression</li>
</ul>
<pre class="r"><code>library(tidyverse)
library(caret)
library(leaps)</code></pre>
</div>
<div id="computing-stepwise-regression" class="section level2">
<h2>Computing stepwise regression</h2>
<p>There are many functions and R packages for computing stepwise regression. These include:</p>
<ul>
<li><code>stepAIC()</code> [MASS package], which choose the best model by AIC. It has an option named <code>direction</code>, which can take the following values: i) “both” (for stepwise regression, both forward and backward selection); “backward” (for backward selection) and “forward” (for forward selection). It return the best final model.</li>
</ul>
<pre class="r"><code>library(MASS)
# Fit the full model 
full.model <- lm(Fertility ~., data = swiss)
# Stepwise regression model
step.model <- stepAIC(full.model, direction = "both", 
                      trace = FALSE)
summary(step.model)</code></pre>
<ul>
<li><code>regsubsets()</code> [leaps package], which has the tuning parameter <code>nvmax</code> specifying the maximal number of predictors to incorporate in the model (See Chapter @ref(best-subsets-regression)). It returns multiple models with different size up to nvmax. You need to compare the performance of the different models for choosing the best one. <code>regsubsets()</code> has the option <code>method</code>, which can take the values “backward”, “forward” and “seqrep” (seqrep = sequential replacement, combination of forward and backward selections).</li>
</ul>
<pre class="r"><code>models <- regsubsets(Fertility~., data = swiss, nvmax = 5,
                     method = "seqrep")
summary(models)</code></pre>
<p>Note that, the <code>train()</code> function [caret package] provides an easy workflow to perform stepwise selections using the <code>leaps</code> and the MASS packages. It has an option named <code>method</code>, which can take the following values:</p>
<ul>
<li><code>"leapBackward"</code>, to fit linear regression with <strong>backward selection</strong></li>
<li><code>"leapForward"</code>, to fit linear regression with <strong>forward selection</strong></li>
<li><code>"leapSeq"</code>, to fit linear regression with <strong>stepwise selection</strong> .</li>
</ul>
<p>You also need to specify the tuning parameter <code>nvmax</code>, which corresponds to the maximum number of predictors to be incorporated in the model.</p>
<p>For example, you can vary <code>nvmax</code> from 1 to 5. In this case, the function starts by searching different best models of different size, up to the best 5-variables model. That is, it searches the best 1-variable model, the best 2-variables model, …, the best 5-variables models.</p>
<p>The following example performs backward selection (<code>method = "leapBackward"</code>), using the <code>swiss</code> data set, to identify the best model for predicting Fertility on the basis of socio-economic indicators.</p>
<p>As the data set contains only 5 predictors, we’ll vary <code>nvmax</code> from 1 to 5 resulting to the identification of the 5 best models with different sizes: the best 1-variable model, the best 2-variables model, …, the best 5-variables model.</p>
<p>We’ll use 10-fold cross-validation to estimate the average prediction error (RMSE) of each of the 5 models (see Chapter @ref(cross-validation)). The RMSE statistical metric is used to compare the 5 models and to automatically choose the best one, where best is defined as the model that minimize the RMSE.</p>
<pre class="r"><code># Set seed for reproducibility
set.seed(123)
# Set up repeated k-fold cross-validation
train.control <- trainControl(method = "cv", number = 10)
# Train the model
step.model <- train(Fertility ~., data = swiss,
                    method = "leapBackward", 
                    tuneGrid = data.frame(nvmax = 1:5),
                    trControl = train.control
                    )
step.model$results</code></pre>
<pre><code>##   nvmax RMSE Rsquared  MAE RMSESD RsquaredSD MAESD
## 1     1 9.30    0.408 7.91   1.53      0.390  1.65
## 2     2 9.08    0.515 7.75   1.66      0.247  1.40
## 3     3 8.07    0.659 6.55   1.84      0.216  1.57
## 4     4 7.27    0.732 5.93   2.14      0.236  1.67
## 5     5 7.38    0.751 6.03   2.23      0.239  1.64</code></pre>
<p>The output above shows different metrics and their standard deviation for comparing the accuracy of the 5 best models. Columns are:</p>
<ul>
<li><code>nvmax</code>: the number of variable in the model. For example nvmax = 2, specify the best 2-variables model</li>
<li><code>RMSE</code> and <code>MAE</code> are two different metrics measuring the prediction error of each model. The lower the RMSE and MAE, the better the model.</li>
<li><code>Rsquared</code> indicates the correlation between the observed outcome values and the values predicted by the model. The higher the R squared, the better the model.</li>
</ul>
<p>In our example, it can be seen that the model with 4 variables (nvmax = 4) is the one that has the lowest RMSE. You can display the best tuning values (nvmax), automatically selected by the <code>train()</code> function, as follow:</p>
<pre class="r"><code>step.model$bestTune</code></pre>
<pre><code>##   nvmax
## 4     4</code></pre>
<p>This indicates that the best model is the one with nvmax = 4 variables. The function <code>summary()</code> reports the best set of variables for each model size, up to the best 4-variables model.</p>
<pre class="r"><code>summary(step.model$finalModel)</code></pre>
<pre><code>## Subset selection object
## 5 Variables  (and intercept)
##                  Forced in Forced out
## Agriculture          FALSE      FALSE
## Examination          FALSE      FALSE
## Education            FALSE      FALSE
## Catholic             FALSE      FALSE
## Infant.Mortality     FALSE      FALSE
## 1 subsets of each size up to 4
## Selection Algorithm: backward
##          Agriculture Examination Education Catholic Infant.Mortality
## 1  ( 1 ) " "         " "         "*"       " "      " "             
## 2  ( 1 ) " "         " "         "*"       "*"      " "             
## 3  ( 1 ) " "         " "         "*"       "*"      "*"             
## 4  ( 1 ) "*"         " "         "*"       "*"      "*"</code></pre>
<p>An asterisk specifies that a given variable is included in the corresponding model. For example, it can be seen that the best 4-variables model contains Agriculture, Education, Catholic, Infant.Mortality (<code>Fertility ~ Agriculture + Education + Catholic + Infant.Mortality</code>).</p>
<p>The regression coefficients of the final model (id = 4) can be accessed as follow:</p>
<pre class="r"><code>coef(step.model$finalModel, 4)</code></pre>
<p>Or, by computing the linear model using only the selected predictors:</p>
<pre class="r"><code>lm(Fertility ~ Agriculture + Education + Catholic + Infant.Mortality, 
   data = swiss)</code></pre>
<pre><code>## 
## Call:
## lm(formula = Fertility ~ Agriculture + Education + Catholic + 
##     Infant.Mortality, data = swiss)
## 
## Coefficients:
##      (Intercept)       Agriculture         Education          Catholic  
##           62.101            -0.155            -0.980             0.125  
## Infant.Mortality  
##            1.078</code></pre>
</div>
<div id="discussion" class="section level2">
<h2>Discussion</h2>
<p>This chapter describes stepwise regression methods in order to choose an optimal simple model, without compromising the model accuracy.</p>
<p>We have demonstrated how to use the <code>leaps</code> R package for computing stepwise regression. Another alternative is the function <code>stepAIC()</code> available in the MASS package. It has an option called <code>direction</code>, which can have the following values: “both”, “forward”, “backward”.</p>
<pre class="r"><code>library(MASS)
res.lm <- lm(Fertility ~., data = swiss)
step <- stepAIC(res.lm, direction = "both", trace = FALSE)
step</code></pre>
<p>Additionally, the caret package has method to compute stepwise regression using the MASS package (<code>method = "lmStepAIC"</code>):</p>
<pre class="r"><code># Train the model
step.model <- train(Fertility ~., data = swiss,
                    method = "lmStepAIC", 
                    trControl = train.control,
                    trace = FALSE
                    )

# Model accuracy
step.model$results
# Final model coefficients
step.model$finalModel
# Summary of the model
summary(step.model$finalModel)</code></pre>
<p>Stepwise regression is very useful for high-dimensional data containing multiple predictor variables. Other alternatives are the penalized regression (ridge and lasso regression) (Chapter @ref(penalized-regression)) and the principal components-based regression methods (PCR and PLS) (Chapter @ref(pcr-and-pls-regression)).</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:40:00 +0100</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[Penalized Regression Essentials: Ridge, Lasso &amp; Elastic Net]]></title>
			<link>https://www.sthda.com/english/articles/37-model-selection-essentials-in-r/153-penalized-regression-essentials-ridge-lasso-elastic-net/</link>
			<guid>https://www.sthda.com/english/articles/37-model-selection-essentials-in-r/153-penalized-regression-essentials-ridge-lasso-elastic-net/</guid>
			<description><![CDATA[<!-- START HTML -->

  <div id="rdoc">





<p>The standard linear model (or the ordinary least squares method) performs poorly in a situation, where you have a large multivariate data set containing a number of variables superior to the number of samples.</p>
<p>A better alternative is the <strong>penalized regression</strong> allowing to create a linear regression model that is penalized, for having too many variables in the model, by adding a constraint in the equation <span class="citation">(James et al. 2014,<span class="citation">P. Bruce and Bruce (2017)</span>)</span>. This is also known as <strong>shrinkage</strong> or <strong>regularization</strong> methods.</p>
<p>The consequence of imposing this penalty, is to reduce (i.e. shrink) the coefficient values towards zero. This allows the less contributive variables to have a coefficient close to zero or equal zero.</p>
<p>Note that, the shrinkage requires the selection of a tuning parameter (lambda) that determines the amount of shrinkage.</p>
<p>In this chapter we’ll describe the most commonly used penalized regression methods, including <strong>ridge regression</strong>, <strong>lasso regression</strong> and <strong>elastic net regression</strong>. We’ll also provide practical examples in R.</p>
<p>Contents:</p>
<div id="TOC">
<ul>
<li><a href="#shrinkage-methods">Shrinkage methods</a><ul>
<li><a href="#ridge-regression">Ridge regression</a></li>
<li><a href="#lasso-regression">Lasso regression</a></li>
<li><a href="#elastic-net">Elastic Net</a></li>
</ul></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-penalized-linear-regression">Computing penalized linear regression</a><ul>
<li><a href="#additional-data-preparation">Additional data preparation</a></li>
<li><a href="#r-functions">R functions</a></li>
<li><a href="#computing-ridge-regression">Computing ridge regression</a></li>
<li><a href="#computing-lasso-regression">Computing lasso regression</a></li>
<li><a href="#computing-elastic-net-regession">Computing elastic net regession</a></li>
<li><a href="#comparing-the-different-models">Comparing the different models</a></li>
<li><a href="#using-caret-package">Using caret package</a></li>
</ul></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="shrinkage-methods" class="section level2">
<h2>Shrinkage methods</h2>
<div id="ridge-regression" class="section level3">
<h3>Ridge regression</h3>
<p>Ridge regression shrinks the regression coefficients, so that variables, with minor contribution to the outcome, have their coefficients close to zero.</p>
<p>The shrinkage of the coefficients is achieved by penalizing the regression model with a penalty term called <strong>L2-norm</strong>, which is the sum of the squared coefficients.</p>
<p>The amount of the penalty can be fine-tuned using a constant called lambda (<span class="math inline">\(\lambda\)</span>). Selecting a good value for <span class="math inline">\(\lambda\)</span> is critical.</p>
<p>When <span class="math inline">\(\lambda = 0\)</span>, the penalty term has no effect, and ridge regression will produce the classical least square coefficients. However, as <span class="math inline">\(\lambda\)</span> increases to infinite, the impact of the shrinkage penalty grows, and the ridge regression coefficients will get close zero.</p>
<p>Note that, in contrast to the ordinary least square regression, ridge regression is highly affected by the scale of the predictors. Therefore, it is better to standardize (i.e., scale) the predictors before applying the ridge regression <span class="citation">(James et al. 2014)</span>, so that all the predictors are on the same scale.</p>
<p>The standardization of a predictor <code>x</code>, can be achieved using the formula <code>x' = x / sd(x)</code>, where sd(x) is the standard deviation of x. The consequence of this is that, all standardized predictors will have a standard deviation of one allowing the final fit to not depend on the scale on which the predictors are measured.</p>
<p>One important advantage of the ridge regression, is that it still performs well, compared to the ordinary least square method (Chapter @ref(linear-regression)), in a situation where you have a large multivariate data with the number of predictors (p) larger than the number of observations (n).</p>
<p>One disadvantage of the ridge regression is that, it will include all the predictors in the final model, unlike the stepwise regression methods (Chapter @ref(stepwise-regression)), which will generally select models that involve a reduced set of variables.</p>
<p>Ridge regression shrinks the coefficients towards zero, but it will not set any of them exactly to zero. The lasso regression is an alternative that overcomes this drawback.</p>
</div>
<div id="lasso-regression" class="section level3">
<h3>Lasso regression</h3>
<p>Lasso stands for Least Absolute Shrinkage and Selection Operator. It shrinks the regression coefficients toward zero by penalizing the regression model with a penalty term called <strong>L1-norm</strong>, which is the sum of the absolute coefficients.</p>
<p>In the case of lasso regression, the penalty has the effect of forcing some of the coefficient estimates, with a minor contribution to the model, to be exactly equal to zero. This means that, lasso can be also seen as an alternative to the subset selection methods for performing variable selection in order to reduce the complexity of the model.</p>
<p>As in ridge regression, selecting a good value of <span class="math inline">\(\lambda\)</span> for the lasso is critical.</p>
<p>One obvious advantage of lasso regression over ridge regression, is that it produces simpler and more interpretable models that incorporate only a reduced set of the predictors. However, neither ridge regression nor the lasso will universally dominate the other.</p>
<p>Generally, lasso might perform better in a situation where some of the predictors have large coefficients, and the remaining predictors have very small coefficients.</p>
<p>Ridge regression will perform better when the outcome is a function of many predictors, all with coefficients of roughly equal size <span class="citation">(James et al. 2014)</span>.</p>
<p>Cross-validation methods can be used for identifying which of these two techniques is better on a particular data set.</p>
</div>
<div id="elastic-net" class="section level3">
<h3>Elastic Net</h3>
<p>Elastic Net produces a regression model that is penalized with both the <strong>L1-norm</strong> and <strong>L2-norm</strong>. The consequence of this is to effectively shrink coefficients (like in ridge regression) and to set some coefficients to zero (as in LASSO).</p>
</div>
</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>We’ll use the <code>Boston</code> data set [in <code>MASS</code> package], introduced in Chapter @ref(regression-analysis), for predicting the median house value (<code>mdev</code>), in Boston Suburbs, based on multiple predictor 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("Boston", package = "MASS")
# Split the data into training and test set
set.seed(123)
training.samples <- Boston$medv %>%
  createDataPartition(p = 0.8, list = FALSE)
train.data  <- Boston[training.samples, ]
test.data <- Boston[-training.samples, ]</code></pre>
</div>
<div id="computing-penalized-linear-regression" class="section level2">
<h2>Computing penalized linear regression</h2>
<div id="additional-data-preparation" class="section level3">
<h3>Additional data preparation</h3>
<p>You need to create two objects:</p>
<ul>
<li><code>y</code> for storing the outcome variable</li>
<li><code>x</code> for holding the predictor variables. This should be created using the function <code>model.matrix()</code> allowing to automatically transform any qualitative variables (if any) into dummy variables (Chapter @ref(regression-with-categorical-variables)), which is important because glmnet() can only take numerical, quantitative inputs. After creating the model matrix, we remove the intercept component at index = 1.</li>
</ul>
<pre class="r"><code># Predictor variables
x <- model.matrix(medv~., train.data)[,-1]
# Outcome variable
y <- train.data$medv</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 linear regression models.</p>
<p>The simplified format is as follow:</p>
<pre class="r"><code>glmnet(x, y, 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>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 sections, we start by computing ridge, lasso and elastic net regression models. Next, we’ll compare the different models in order to choose the best one for our data.
</p>
</div>
<p>The best model is defined as the model that has the lowest prediction error, RMSE (Chapter @ref(regression-model-accuracy-metrics)).</p>
</div>
<div id="computing-ridge-regression" class="section level3">
<h3>Computing ridge regression</h3>
<pre class="r"><code># Find the best lambda using cross-validation
set.seed(123) 
cv <- cv.glmnet(x, y, alpha = 0)
# Display the best lambda value
cv$lambda.min</code></pre>
<pre><code>## [1] 0.758</code></pre>
<pre class="r"><code># Fit the final model on the training data
model <- glmnet(x, y, alpha = 0, lambda = cv$lambda.min)
# Display regression coefficients
coef(model)</code></pre>
<pre><code>## 14 x 1 sparse Matrix of class "dgCMatrix"
##                    s0
## (Intercept)  28.69633
## crim         -0.07285
## zn            0.03417
## indus        -0.05745
## chas          2.49123
## nox         -11.09232
## rm            3.98132
## age          -0.00314
## dis          -1.19296
## rad           0.14068
## tax          -0.00610
## ptratio      -0.86400
## black         0.00937
## lstat        -0.47914</code></pre>
<pre class="r"><code># Make predictions on the test data
x.test <- model.matrix(medv ~., test.data)[,-1]
predictions <- model %>% predict(x.test) %>% as.vector()
# Model performance metrics
data.frame(
  RMSE = RMSE(predictions, test.data$medv),
  Rsquare = R2(predictions, test.data$medv)
)</code></pre>
<pre><code>##   RMSE Rsquare
## 1 4.98   0.671</code></pre>
<div class="warning">
<p>
Note that by default, the function glmnet() standardizes variables so that their scales are comparable. However, the coefficients are always returned on the original scale.
</p>
</div>
</div>
<div id="computing-lasso-regression" class="section level3">
<h3>Computing lasso regression</h3>
<p>The only difference between the R code used for ridge regression is that, for lasso regression you need to specify the argument <code>alpha = 1</code> instead of <code>alpha = 0</code> (for ridge regression).</p>
<pre class="r"><code># Find the best lambda using cross-validation
set.seed(123) 
cv <- cv.glmnet(x, y, alpha = 1)
# Display the best lambda value
cv$lambda.min</code></pre>
<pre><code>## [1] 0.00852</code></pre>
<pre class="r"><code># Fit the final model on the training data
model <- glmnet(x, y, alpha = 1, lambda = cv$lambda.min)
# Dsiplay regression coefficients
coef(model)</code></pre>
<pre><code>## 14 x 1 sparse Matrix of class "dgCMatrix"
##                    s0
## (Intercept)  36.90539
## crim         -0.09222
## zn            0.04842
## indus        -0.00841
## chas          2.28624
## nox         -16.79651
## rm            3.81186
## age           .      
## dis          -1.59603
## rad           0.28546
## tax          -0.01240
## ptratio      -0.95041
## black         0.00965
## lstat        -0.52880</code></pre>
<pre class="r"><code># Make predictions on the test data
x.test <- model.matrix(medv ~., test.data)[,-1]
predictions <- model %>% predict(x.test) %>% as.vector()
# Model performance metrics
data.frame(
  RMSE = RMSE(predictions, test.data$medv),
  Rsquare = R2(predictions, test.data$medv)
)</code></pre>
<pre><code>##   RMSE Rsquare
## 1 4.99   0.671</code></pre>
</div>
<div id="computing-elastic-net-regession" class="section level3">
<h3>Computing elastic net regession</h3>
<p>The elastic net regression can be easily computed using the <code>caret</code> workflow, which invokes the <code>glmnet</code> package.</p>
<p>We use <code>caret</code> to automatically select the best tuning parameters <code>alpha</code> and <code>lambda</code>. The <code>caret</code> packages tests a range of possible <code>alpha</code> and <code>lambda</code> values, then selects the best values for lambda and alpha, resulting to a final model that is an elastic net model.</p>
<p>Here, we’ll test the combination of 10 different values for <code>alpha</code> and <code>lambda</code>. This is specified using the option <code>tuneLength</code>.</p>
<p>The best <code>alpha</code> and <code>lambda</code> values are those values that minimize the cross-validation error (Chapter @ref(cross-validation)).</p>
<pre class="r"><code># Build the model using the training set
set.seed(123)
model <- train(
  medv ~., data = train.data, method = "glmnet",
  trControl = trainControl("cv", number = 10),
  tuneLength = 10
)
# Best tuning parameter
model$bestTune</code></pre>
<pre><code>##   alpha lambda
## 6   0.1   0.21</code></pre>
<pre class="r"><code># Coefficient of the final model. You need
# to specify the best lambda
coef(model$finalModel, model$bestTune$lambda)</code></pre>
<pre><code>## 14 x 1 sparse Matrix of class "dgCMatrix"
##                     1
## (Intercept)  33.04083
## crim         -0.07898
## zn            0.04136
## indus        -0.03093
## chas          2.34443
## nox         -14.30442
## rm            3.90863
## age           .      
## dis          -1.41783
## rad           0.20564
## tax          -0.00879
## ptratio      -0.91214
## black         0.00946
## lstat        -0.51770</code></pre>
<pre class="r"><code># Make predictions on the test data
x.test <- model.matrix(medv ~., test.data)[,-1]
predictions <- model %>% predict(x.test)
# Model performance metrics
data.frame(
  RMSE = RMSE(predictions, test.data$medv),
  Rsquare = R2(predictions, test.data$medv)
)</code></pre>
<pre><code>##   RMSE Rsquare
## 1 4.98   0.672</code></pre>
</div>
<div id="comparing-the-different-models" class="section level3">
<h3>Comparing the different models</h3>
<p>The different models performance metrics are comparable. Using lasso or elastic net regression set the coefficient of the predictor variable <code>age</code> to zero, leading to a simpler model compared to the ridge regression, which include all predictor variables.</p>
<div class="success">
<p>
All things equal, we should go for the simpler model. In our example, we can choose the lasso or the elastic net regression models.
</p>
</div>
<p>Note that, we can easily compute and compare ridge, lasso and elastic net regression using the <code>caret</code> workflow.</p>
<p><code>caret</code> will automatically choose the best tuning parameter values, compute the final model and evaluate the model performance using cross-validation techniques.</p>
</div>
<div id="using-caret-package" class="section level3">
<h3>Using caret package</h3>
<ol start="0" style="list-style-type: decimal">
<li><strong>Setup a grid range of lambda values</strong>:</li>
</ol>
<pre class="r"><code>lambda <- 10^seq(-3, 3, length = 100)</code></pre>
<ol style="list-style-type: decimal">
<li><strong>Compute ridge regression</strong>:</li>
</ol>
<pre class="r"><code># Build the model
set.seed(123)
ridge <- train(
  medv ~., data = train.data, method = "glmnet",
  trControl = trainControl("cv", number = 10),
  tuneGrid = expand.grid(alpha = 0, lambda = lambda)
  )
# Model coefficients
coef(ridge$finalModel, ridge$bestTune$lambda)
# Make predictions
predictions <- ridge %>% predict(test.data)
# Model prediction performance
data.frame(
  RMSE = RMSE(predictions, test.data$medv),
  Rsquare = R2(predictions, test.data$medv)
)</code></pre>
<ol start="2" style="list-style-type: decimal">
<li><strong>Compute lasso regression</strong>:</li>
</ol>
<pre class="r"><code># Build the model
set.seed(123)
lasso <- train(
  medv ~., data = train.data, method = "glmnet",
  trControl = trainControl("cv", number = 10),
  tuneGrid = expand.grid(alpha = 1, lambda = lambda)
  )
# Model coefficients
coef(lasso$finalModel, lasso$bestTune$lambda)
# Make predictions
predictions <- lasso %>% predict(test.data)
# Model prediction performance
data.frame(
  RMSE = RMSE(predictions, test.data$medv),
  Rsquare = R2(predictions, test.data$medv)
)</code></pre>
<ol start="3" style="list-style-type: decimal">
<li><strong>Elastic net regression</strong>:</li>
</ol>
<pre class="r"><code># Build the model
set.seed(123)
elastic <- train(
  medv ~., data = train.data, method = "glmnet",
  trControl = trainControl("cv", number = 10),
  tuneLength = 10
  )
# Model coefficients
coef(elastic$finalModel, elastic$bestTune$lambda)
# Make predictions
predictions <- elastic %>% predict(test.data)
# Model prediction performance
data.frame(
  RMSE = RMSE(predictions, test.data$medv),
  Rsquare = R2(predictions, test.data$medv)
)</code></pre>
<ol start="4" style="list-style-type: decimal">
<li><strong>Comparing models performance</strong>:</li>
</ol>
<p>The performance of the different models - ridge, lasso and elastic net - can be easily compared using <code>caret</code>. The best model is defined as the one that minimizes the prediction error.</p>
<pre class="r"><code>models <- list(ridge = ridge, lasso = lasso, elastic = elastic)
resamples(models) %>% summary( metric = "RMSE")</code></pre>
<pre><code>## 
## Call:
## summary.resamples(object = ., metric = "RMSE")
## 
## Models: ridge, lasso, elastic 
## Number of resamples: 10 
## 
## RMSE 
##         Min. 1st Qu. Median Mean 3rd Qu. Max. NA&amp;#39;s
## ridge   3.10    3.96   4.38 4.73    5.52 7.43    0
## lasso   3.16    4.03   4.39 4.73    5.51 7.27    0
## elastic 3.13    4.00   4.37 4.72    5.52 7.32    0</code></pre>
<div class="success">
<p>
It can be seen that the elastic net model has the lowest median RMSE.
</p>
</div>
</div>
</div>
<div id="discussion" class="section level2">
<h2>Discussion</h2>
<p>In this chapter we described the most commonly used penalized regression methods, including ridge regression, lasso regression and elastic net regression. These methods are very useful in a situation, where you have a large multivariate data sets.</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-->

 
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
  (function () {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src  = "https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
    document.getElementsByTagName("head")[0].appendChild(script);
  })();
</script>

<!-- END HTML -->]]></description>
			<pubDate>Sun, 11 Mar 2018 09:29:00 +0100</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[Principal Component and Partial Least Squares Regression Essentials ]]></title>
			<link>https://www.sthda.com/english/articles/37-model-selection-essentials-in-r/152-principal-component-and-partial-least-squares-regression-essentials/</link>
			<guid>https://www.sthda.com/english/articles/37-model-selection-essentials-in-r/152-principal-component-and-partial-least-squares-regression-essentials/</guid>
			<description><![CDATA[<!-- START HTML -->

  <div id="rdoc">





<p>This chapter presents regression methods based on dimension reduction techniques, which can be very useful when you have a large data set with multiple correlated predictor variables.</p>
<p>Generally, all dimension reduction methods work by first summarizing the original predictors into few new variables called principal components (PCs), which are then used as predictors to fit the linear regression model. These methods avoid multicollinearity between predictors, which a big issue in regression setting (see Chapter @ref(multicollinearity)).</p>
<p>When using the dimension reduction methods, it’s generally recommended to standardize each predictor to make them comparable. Standardization consists of dividing the predictor by its standard deviation.</p>
<p>Here, we described two well known regression methods based on dimension reduction: <strong>Principal Component Regression</strong> (<strong>PCR</strong>) and <strong>Partial Least Squares</strong> (<strong>PLS</strong>) regression. We also provide practical examples in R.</p>
<p>Contents:</p>
<div id="TOC">
<ul>
<li><a href="#principal-component-regression">Principal component regression</a></li>
<li><a href="#partial-least-squares-regression">Partial least squares regression</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="#computation">Computation</a><ul>
<li><a href="#computing-principal-component-regression">Computing principal component regression</a></li>
<li><a href="#computing-partial-least-squares">Computing partial least squares</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="principal-component-regression" class="section level2">
<h2>Principal component regression</h2>
<p>The principal component regression (PCR) first applies <a href="https://www.sthda.com/english/articles/31-principal-component-methods-in-r-practical-guide/112-pca-principal-component-analysis-essentials/">Principal Component Analysis</a> on the data set to summarize the original predictor variables into few new variables also known as principal components (PCs), which are a linear combination of the original data.</p>
<p>These PCs are then used to build the linear regression model. The number of principal components, to incorporate in the model, is chosen by cross-validation (cv). Note that, PCR is suitable when the data set contains highly correlated predictors.</p>
</div>
<div id="partial-least-squares-regression" class="section level2">
<h2>Partial least squares regression</h2>
<p>A possible drawback of PCR is that we have no guarantee that the selected principal components are associated with the outcome. Here, the selection of the principal components to incorporate in the model is not supervised by the outcome variable.</p>
<p>An alternative to PCR is the <strong>Partial Least Squares</strong> (PLS) regression, which identifies new principal components that not only summarizes the original predictors, but also that are related to the outcome. These components are then used to fit the regression model. So, compared to PCR, PLS uses a dimension reduction strategy that is supervised by the outcome.</p>
<p>Like PCR, PLS is convenient for data with highly-correlated predictors. The number of PCs used in PLS is generally chosen by cross-validation. Predictors and the outcome variables should be generally standardized, to make the variables comparable.</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>
<li><code>pls</code>, for computing PCR and PLS</li>
</ul>
<pre class="r"><code>library(tidyverse)
library(caret)
library(pls)</code></pre>
</div>
<div id="preparing-the-data" class="section level2">
<h2>Preparing the data</h2>
<p>We’ll use the <code>Boston</code> data set [in <code>MASS</code> package], introduced in Chapter @ref(regression-analysis), for predicting the median house value (<code>mdev</code>), in Boston Suburbs, based on multiple predictor 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("Boston", package = "MASS")
# Split the data into training and test set
set.seed(123)
training.samples <- Boston$medv %>%
  createDataPartition(p = 0.8, list = FALSE)
train.data  <- Boston[training.samples, ]
test.data <- Boston[-training.samples, ]</code></pre>
</div>
<div id="computation" class="section level2">
<h2>Computation</h2>
<p>The R function <code>train()</code> [<code>caret</code> package] provides an easy workflow to compute PCR and PLS by invoking the <code>pls</code> package. It has an option named <code>method</code>, which can take the value <code>pcr</code> or <code>pls</code>.</p>
<p>An additional argument is <code>scale = TRUE</code> for standardizing the variables to make them comparable.</p>
<p><code>caret</code> uses cross-validation to automatically identify the optimal number of principal components (<code>ncomp</code>) to be incorporated in the model.</p>
<p>Here, we’ll test 10 different values of the tuning parameter <code>ncomp</code>. This is specified using the option <code>tuneLength</code>. The optimal number of principal components is selected so that the cross-validation error (RMSE) is minimized.</p>
<div id="computing-principal-component-regression" class="section level3">
<h3>Computing principal component regression</h3>
<pre class="r"><code># Build the model on training set
set.seed(123)
model <- train(
  medv~., data = train.data, method = "pcr",
  scale = TRUE,
  trControl = trainControl("cv", number = 10),
  tuneLength = 10
  )
# Plot model RMSE vs different values of components
plot(model)
# Print the best tuning parameter ncomp that
# minimize the cross-validation error, RMSE
model$bestTune</code></pre>
<pre><code>##   ncomp
## 5     5</code></pre>
<pre class="r"><code># Summarize the final model
summary(model$finalModel)</code></pre>
<pre><code>## Data:    X dimension: 407 13 
##  Y dimension: 407 1
## Fit method: svdpc
## Number of components considered: 5
## TRAINING: % variance explained
##           1 comps  2 comps  3 comps  4 comps  5 comps
## X           47.48    58.40    68.00    74.75    80.94
## .outcome    38.10    51.02    64.43    65.24    71.17</code></pre>
<pre class="r"><code># Make predictions
predictions <- model %>% predict(test.data)
# Model performance metrics
data.frame(
  RMSE = caret::RMSE(predictions, test.data$medv),
  Rsquare = caret::R2(predictions, test.data$medv)
)</code></pre>
<pre><code>##   RMSE Rsquare
## 1 5.18   0.645</code></pre>
<p><img src="https://www.sthda.com/english/sthda-upload/figures/machine-learning-essentials/024-pcr-and-pls-regression-principal-component-regression-optimal-components-1.png" width="384" /></p>
<p>The plot shows the prediction error (RMSE, Chapter @ref(regression-model-accuracy-metrics)) made by the model according to the number of principal components incorporated in the model.</p>
<p>Our analysis shows that, choosing five principal components (ncomp = 5) gives the smallest prediction error RMSE.</p>
<p>The <code>summary()</code> function also provides the percentage of variance explained in the predictors (x) and in the outcome (<code>medv</code>) using different numbers of components.</p>
<p>For example, 80.94% of the variation (or information) contained in the predictors are captured by 5 principal components (<code>ncomp = 5</code>). Additionally, setting ncomp = 5, captures 71% of the information in the outcome variable (<code>medv</code>), which is good.</p>
<div class="success">
<p>
Taken together, cross-validation identifies ncomp = 5 as the optimal number of PCs that minimize the prediction error (RMSE) and explains enough variation in the predictors and in the outcome.
</p>
</div>
</div>
<div id="computing-partial-least-squares" class="section level3">
<h3>Computing partial least squares</h3>
<p>The R code is just like that of the PCR method.</p>
<pre class="r"><code># Build the model on training set
set.seed(123)
model <- train(
  medv~., data = train.data, method = "pls",
  scale = TRUE,
  trControl = trainControl("cv", number = 10),
  tuneLength = 10
  )
# Plot model RMSE vs different values of components
plot(model)
# Print the best tuning parameter ncomp that
# minimize the cross-validation error, RMSE
model$bestTune</code></pre>
<pre><code>##   ncomp
## 9     9</code></pre>
<pre class="r"><code># Summarize the final model
summary(model$finalModel)</code></pre>
<pre><code>## Data:    X dimension: 407 13 
##  Y dimension: 407 1
## Fit method: oscorespls
## Number of components considered: 9
## TRAINING: % variance explained
##           1 comps  2 comps  3 comps  4 comps  5 comps  6 comps  7 comps
## X           46.19    57.32    64.15    69.76    75.63    78.66    82.85
## .outcome    50.90    71.84    73.71    74.71    75.18    75.35    75.42
##           8 comps  9 comps
## X           85.92    90.36
## .outcome    75.48    75.49</code></pre>
<pre class="r"><code># Make predictions
predictions <- model %>% predict(test.data)
# Model performance metrics
data.frame(
  RMSE = caret::RMSE(predictions, test.data$medv),
  Rsquare = caret::R2(predictions, test.data$medv)
)</code></pre>
<pre><code>##   RMSE Rsquare
## 1 4.99   0.671</code></pre>
<p><img src="https://www.sthda.com/english/sthda-upload/figures/machine-learning-essentials/024-pcr-and-pls-regression-partial-least-square-regression-1.png" width="384" /></p>
<p>The optimal number of principal components included in the PLS model is 9. This captures 90% of the variation in the predictors and 75% of the variation in the outcome variable (<code>medv</code>).</p>
<p>In our example, the cross-validation error RMSE obtained with the PLS model is lower than the RMSE obtained using the PCR method. So, the PLS model is the best model, for explaining our data, compared to the PCR model.</p>
</div>
</div>
<div id="discussion" class="section level2">
<h2>Discussion</h2>
<p>This chapter describes principal component based regression methods, including principal component regression (PCR) and partial least squares regression (PLS). These methods are very useful for multivariate data containing correlated predictors.</p>
<p>The presence of correlation in the data allows to summarize the data into few non-redundant components that can be used in the regression model.</p>
<p>Compared to ridge regression and lasso (Chapter @ref(penalized-regression)), the final PCR and PLS models are more difficult to interpret, because they do not perform any kind of variable selection or even directly produce regression coefficient estimates.</p>
</div>


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


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