<?xml version="1.0" encoding="UTF-8" ?>
<!-- RSS generated by PHPBoost on Sun, 08 Mar 2026 10:20:12 +0100 -->

<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
	<channel>
		<title><![CDATA[Last articles - STHDA : Statistical Machine Learning Essentials]]></title>
		<atom:link href="https://www.sthda.com/english/syndication/rss/articles/35" rel="self" type="application/rss+xml"/>
		<link>https://www.sthda.com</link>
		<description><![CDATA[Last articles - STHDA : Statistical Machine Learning Essentials]]></description>
		<copyright>(C) 2005-2026 PHPBoost</copyright>
		<language>en</language>
		<generator>PHPBoost</generator>
		
		
		<item>
			<title><![CDATA[KNN: K-Nearest Neighbors Essentials]]></title>
			<link>https://www.sthda.com/english/articles/35-statistical-machine-learning-essentials/142-knn-k-nearest-neighbors-essentials/</link>
			<guid>https://www.sthda.com/english/articles/35-statistical-machine-learning-essentials/142-knn-k-nearest-neighbors-essentials/</guid>
			<description><![CDATA[<!-- START HTML -->

  <div id="rdoc">

<p>The <strong>k-nearest neighbors</strong> (<strong>KNN</strong>) algorithm is a simple <em>machine learning</em> method used for both classification and regression. The kNN algorithm predicts the outcome of a new observation by comparing it to k similar cases in the training data set, where k is defined by the analyst.</p>
<p>In this chapter, we start by describing the basics of the KNN algorithm for both classification and regression settings. Next, we provide practical example in <em>R</em> for preparing the data and computing KNN model.</p>
<p>Additionally, you’ll learn how to make predictions and to assess the performance of the built model in the predicting the outcome of new test observations.</p>
<p>Contents:</p>
<div id="TOC">
<ul>
<li><a href="#knn-algorithm">KNN algorithm</a></li>
<li><a href="#loading-required-r-packages">Loading required R packages</a></li>
<li><a href="#classification">Classification</a><ul>
<li><a href="#example-of-data-set">Example of data set</a></li>
<li><a href="#computing-knn-classifier">Computing KNN classifier</a></li>
</ul></li>
<li><a href="#knn-for-regression">KNN for 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="knn-algorithm" class="section level2">
<h2>KNN algorithm</h2>
<ul>
<li><strong>KNN algorithm for classification</strong>:</li>
</ul>
<p>To classify a given new observation (new_obs), the k-nearest neighbors method starts by identifying the k most similar training observations (i.e. neighbors) to our new_obs, and then assigns new_obs to the class containing the majority of its neighbors.</p>
<ul>
<li><strong>KNN algorithm for regression</strong>:</li>
</ul>
<p>Similarly, to predict a continuous outcome value for given new observation (new_obs), the KNN algorithm computes the average outcome value of the k training observations that are the most similar to new_obs, and returns this value as new_obs predicted outcome value.</p>
<ul>
<li><strong>Similarity measures</strong>:</li>
</ul>
<p>Note that, the (dis)similarity between observations is generally determined using <a href="https://www.sthda.com/english/articles/26-clustering-basics/86-clustering-distance-measures-essentials/">Euclidean distance measure</a>, which is very sensitive to the scale on which predictor variable measurements are made. So, it’s generally recommended to standardize (i.e., normalize) the predictor variables for making their scales comparable.</p>
<p>The following sections shows how to build a k-nearest neighbor predictive model for classification and regression settings.</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)</code></pre>
</div>
<div id="classification" class="section level2">
<h2>Classification</h2>
<div id="example-of-data-set" class="section level3">
<h3>Example of data set</h3>
<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 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-knn-classifier" class="section level3">
<h3>Computing KNN classifier</h3>
<p>We’ll use the <code>caret</code> package, which automatically tests different possible values of k, then chooses the optimal k that minimizes the cross-validation (“cv”) error, and fits the final best KNN model that explains the best our data.</p>
<p>Additionally <code>caret</code> can automatically preprocess the data in order to normalize the predictor variables.</p>
<p>We’ll use the following arguments in the function <code>train()</code>:</p>
<ul>
<li><code>trControl</code>, to set up 10-fold cross validation</li>
<li><code>preProcess</code>, to normalize the data</li>
<li><code>tuneLength</code>, to specify the number of possible k values to evaluate</li>
</ul>
<pre class="r"><code># Fit the model on the training set
set.seed(123)
model <- train(
  diabetes ~., data = train.data, method = "knn",
  trControl = trainControl("cv", number = 10),
  preProcess = c("center","scale"),
  tuneLength = 20
  )
# Plot model accuracy vs different values of k
plot(model)</code></pre>
<p><img src="https://www.sthda.com/english/sthda-upload/figures/machine-learning-essentials/038-knn-k-nearest-neighbors-fit-the-model-and-choose-the-best-k-1.png" width="384" /></p>
<pre class="r"><code># Print the best tuning parameter k that
# maximizes model accuracy
model$bestTune</code></pre>
<pre><code>##    k
## 5 13</code></pre>
<pre class="r"><code># 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.769</code></pre>
<p>The overall prediction accuracy of our model is 76.9%, which is good (see Chapter @ref(classification-model-evaluation) for learning key metrics used to evaluate a classification model performance).</p>
</div>
</div>
<div id="knn-for-regression" class="section level2">
<h2>KNN for regression</h2>
<p>In this section, we’ll describe how to predict a continuous variable using KNN.</p>
<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, using different predictor variables.</p>
<ol style="list-style-type: decimal">
<li><strong>Randomly split the data</strong> into training set (80% for building a predictive model) and test set (20% for evaluating the model). Make sure to set seed for reproducibility.</li>
</ol>
<pre class="r"><code># Load the data
data("Boston", package = "MASS")
# Inspect the data
sample_n(Boston, 3)
# 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>
<ol start="2" style="list-style-type: decimal">
<li><strong>Compute KNN using caret</strong>.</li>
</ol>
<p>The best k is the one that minimize the prediction error RMSE (root mean squared error).</p>
<p>The RMSE corresponds to the square root of the average difference between the observed known outcome values and the predicted values, <code>RMSE = mean((observeds - predicteds)^2) %>% sqrt()</code>. The lower the RMSE, the better the model.</p>
<pre class="r"><code># Fit the model on the training set
set.seed(123)
model <- train(
  medv~., data = train.data, method = "knn",
  trControl = trainControl("cv", number = 10),
  preProcess = c("center","scale"),
  tuneLength = 10
  )
# Plot model error RMSE vs different values of k
plot(model)
# Best tuning parameter k that minimize the RMSE
model$bestTune
# Make predictions on the test data
predictions <- model %>% predict(test.data)
head(predictions)
# Compute the prediction error RMSE
RMSE(predictions, test.data$medv)</code></pre>
</div>
<div id="discussion" class="section level2">
<h2>Discussion</h2>
<p>This chapter describes the basics of KNN (k-nearest neighbors) modeling, which is conceptually, one of the simpler machine learning method.</p>
<p>It’s recommended to standardize the data when performing the KNN analysis. We provided R codes to easily compute KNN predictive model and to assess the model performance on test data.</p>
<p>When fitting the KNN algorithm, the analyst needs to specify the number of neighbors (k) to be considered in the KNN algorithm for predicting the outcome of an observation. The choice of k considerably impacts the output of KNN. k = 1 corresponds to a highly flexible method resulting to a training error rate of 0 (overfitting), but the test error rate may be quite high.</p>
<p>You need to test multiple k-values to decide an optimal value for your data. This can be done automatically using the <code>caret</code> package, which chooses a value of k that minimize the cross-validation error @ref(cross-validation).</p>
</div>


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


<!-- END HTML -->]]></description>
			<pubDate>Sun, 11 Mar 2018 01:09:00 +0100</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[CART Model: Decision Tree Essentials ]]></title>
			<link>https://www.sthda.com/english/articles/35-statistical-machine-learning-essentials/141-cart-model-decision-tree-essentials/</link>
			<guid>https://www.sthda.com/english/articles/35-statistical-machine-learning-essentials/141-cart-model-decision-tree-essentials/</guid>
			<description><![CDATA[<!-- START HTML -->

  <div id="rdoc">

<p>The <strong>decision tree</strong> method is a powerful and popular predictive machine learning technique that is used for both <em>classification</em> and <em>regression</em>. So, it is also known as <strong>Classification and Regression Trees</strong> (<strong>CART</strong>).</p>
<p>Note that the R implementation of the CART algorithm is called <em>RPART</em> (Recursive Partitioning And Regression Trees) available in a package of the same name.</p>
<p>In this chapter we’ll describe the basics of tree models and provide R codes to compute classification and regression trees.</p>
<p>Contents:</p>
<div id="TOC">
<ul>
<li><a href="#loading-required-r-packages">Loading required R packages</a></li>
<li><a href="#decision-tree-algorithm">Decision tree algorithm</a><ul>
<li><a href="#basics-and-visual-representation">Basics and visual representation</a></li>
<li><a href="#choosing-the-trees-split-points">Choosing the trees split points</a></li>
<li><a href="#making-predictions">Making predictions</a></li>
</ul></li>
<li><a href="#classification-trees">Classification trees</a><ul>
<li><a href="#example-of-data-set">Example of data set</a></li>
<li><a href="#fully-grown-trees">Fully grown trees</a></li>
<li><a href="#pruning-the-tree">Pruning the tree</a></li>
</ul></li>
<li><a href="#regression-trees">Regression trees</a><ul>
<li><a href="#example-of-data-set-1">Example of data set</a></li>
<li><a href="#create-the-regression-tree">Create the regression tree</a></li>
</ul></li>
<li><a href="#conditionnal-inference-tree">Conditionnal inference tree</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>rpart</code> for computing decision tree models</li>
</ul>
<pre class="r"><code>library(tidyverse)
library(caret)
library(rpart)</code></pre>
</div>
<div id="decision-tree-algorithm" class="section level2">
<h2>Decision tree algorithm</h2>
<div id="basics-and-visual-representation" class="section level3">
<h3>Basics and visual representation</h3>
<p>The algorithm of decision tree models works by repeatedly partitioning the data into multiple sub-spaces, so that the outcomes in each final sub-space is as homogeneous as possible. This approach is technically called <em>recursive partitioning</em>.</p>
<p>The produced result consists of a set of rules used for predicting the outcome variable, which can be either:</p>
<ul>
<li>a continuous variable, for regression trees</li>
<li>a categorical variable, for classification trees</li>
</ul>
<p>The decision rules generated by the CART predictive model are generally visualized as a binary tree.</p>
<p>The following example represents a tree model predicting the species of iris flower based on the length (in cm) and width of sepal and petal.</p>
<pre class="r"><code>library(rpart)
model <- rpart(Species ~., data = iris)
par(xpd = NA) # otherwise on some devices the text is clipped
plot(model)
text(model, digits = 3)</code></pre>
<p><img src="https://www.sthda.com/english/sthda-upload/figures/machine-learning-essentials/039-decision-tree-models-graphical-display-of-tree-models-1.png" width="412.8" /></p>
<p>The plot shows the different possible splitting rules that can be used to effectively predict the type of outcome (here, iris species). For example, the top split assigns observations having <code>Petal.length < 2.45</code> to the left branch, where the predicted species are <code>setosa</code>.</p>
<p>The different rules in tree can be printed as follow:</p>
<pre class="r"><code>print(model, digits = 2)</code></pre>
<pre><code>## n= 150 
## 
## node), split, n, loss, yval, (yprob)
##       * denotes terminal node
## 
## 1) root 150 100 setosa (0.333 0.333 0.333)  
##   2) Petal.Length< 2.5 50   0 setosa (1.000 0.000 0.000) *
##   3) Petal.Length>=2.5 100  50 versicolor (0.000 0.500 0.500)  
##     6) Petal.Width< 1.8 54   5 versicolor (0.000 0.907 0.093) *
##     7) Petal.Width>=1.8 46   1 virginica (0.000 0.022 0.978) *</code></pre>
<p>These rules are produced by repeatedly splitting the predictor variables, starting with the variable that has the highest association with the response variable. The process continues until some predetermined stopping criteria are met.</p>
<p>The resulting tree is composed of <em>decision nodes</em>, <em>branches</em> and <em>leaf nodes</em>. The tree is placed from upside to down, so the <em>root</em> is at the top and leaves indicating the outcome is put at the bottom.</p>
<p>Each decision node corresponds to a single input predictor variable and a split cutoff on that variable. The leaf nodes of the tree are the outcome variable which is used to make predictions.</p>
<p>The tree grows from the top (root), at each node the algorithm decides the best split cutoff that results to the greatest purity (or homogeneity) in each subpartition.</p>
<p>The tree will stop growing by the following three criteria <span class="citation">(Zhang 2016)</span>:</p>
<ol style="list-style-type: decimal">
<li>all leaf nodes are pure with a single class;</li>
<li>a pre-specified minimum number of training observations that cannot be assigned to each leaf nodes with any splitting methods;</li>
<li>The number of observations in the leaf node reaches the pre-specified minimum one.</li>
</ol>
<p>A fully grown tree will overfit the training data and the resulting model might not be performant for predicting the outcome of new test data. Techniques, such as <strong>pruning</strong>, are used to control this problem.</p>
</div>
<div id="choosing-the-trees-split-points" class="section level3">
<h3>Choosing the trees split points</h3>
<p>Technically, <strong>for regression modeling</strong>, the split cutoff is defined so that the residual sum of squared error (RSS) is minimized across the training samples that fall within the subpartition.</p>
<p>Recall that, the RSS is the sum of the squared difference between the observed outcome values and the predicted ones, <code>RSS = sum((Observeds - Predicteds)^2)</code>. See Chapter @ref(linear-regression)</p>
<p><strong>In classification settings</strong>, the split point is defined so that the population in subpartitions are pure as much as possible. Two measures of purity are generally used, including the <em>Gini index</em> and the <em>entropy</em> (or <em>information gain</em>).</p>
<p>For a given subpartition, <code>Gini = sum(p(1-p))</code> and <code>entropy = -1*sum(p*log(p))</code>, where p is the proportion of misclassified observations within the subpartition.</p>
<p>The sum is computed across the different categories or classes in the outcome variable. The Gini index and the entropy varie from 0 (greatest purity) to 1 (maximum degree of impurity)</p>
</div>
<div id="making-predictions" class="section level3">
<h3>Making predictions</h3>
<p>The different rule sets established in the tree are used to predict the outcome of a new test data.</p>
<p>The following R code predict the species of a new collected iris flower:</p>
<pre class="r"><code>newdata <- data.frame(
  Sepal.Length = 6.5, Sepal.Width = 3.0,
  Petal.Length = 5.2, Petal.Width = 2.0
)
model %>% predict(newdata, "class") </code></pre>
<pre><code>##         1 
## virginica 
## Levels: setosa versicolor virginica</code></pre>
<div class="success">
<p>
The new data is predicted to be virginica.
</p>
</div>
</div>
</div>
<div id="classification-trees" class="section level2">
<h2>Classification trees</h2>
<div id="example-of-data-set" class="section level3">
<h3>Example of data set</h3>
<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 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="fully-grown-trees" class="section level3">
<h3>Fully grown trees</h3>
<p>Here, we’ll create a fully grown tree showing all predictor variables in the data set.</p>
<pre class="r"><code># Build the model
set.seed(123)
model1 <- rpart(diabetes ~., data = train.data, method = "class")
# Plot the trees
par(xpd = NA) # Avoid clipping the text in some device
plot(model1)
text(model1, digits = 3)</code></pre>
<p><img src="https://www.sthda.com/english/sthda-upload/figures/machine-learning-essentials/039-decision-tree-models-fully-grown-classification-trees-1.png" width="576" /></p>
<pre class="r"><code># Make predictions on the test data
predicted.classes <- model1 %>% 
  predict(test.data, type = "class")
head(predicted.classes)</code></pre>
<pre><code>##  21  25  28  29  32  36 
## neg pos neg pos pos neg 
## Levels: neg pos</code></pre>
<pre class="r"><code># Compute model accuracy rate on test data
mean(predicted.classes == test.data$diabetes)</code></pre>
<pre><code>## [1] 0.782</code></pre>
<div class="success">
<p>
The overall accuracy of our tree model is 78%, which is not so bad.
</p>
</div>
<p>However, this full tree including all predictor appears to be very complex and can be difficult to interpret in the situation where you have a large data sets with multiple predictors.</p>
<p>Additionally, it is easy to see that, a fully grown tree will overfit the training data and might lead to poor test set performance.</p>
<p>A strategy to limit this overfitting is to prune back the tree resulting to a simpler tree with fewer splits and better interpretation at the cost of a little bias <span class="citation">(James et al. 2014, <span class="citation">P. Bruce and Bruce (2017)</span>)</span>.</p>
</div>
<div id="pruning-the-tree" class="section level3">
<h3>Pruning the tree</h3>
<p>Briefly, our goal here is to see if a smaller subtree can give us comparable results to the fully grown tree. If yes, we should go for the simpler tree because it reduces the likelihood of overfitting.</p>
<p>One possible robust strategy of pruning the tree (or stopping the tree to grow) consists of avoiding splitting a partition if the split does not significantly improves the overall quality of the model.</p>
<p>In <code>rpart</code> package, this is controlled by the <em>complexity parameter</em> (cp), which imposes a penalty to the tree for having two many splits. The default value is 0.01. The higher the <code>cp</code>, the smaller the tree.</p>
<p>A too small value of <code>cp</code> leads to overfitting and a too large cp value will result to a too small tree. Both cases decrease the predictive performance of the model.</p>
<p>An optimal <code>cp</code> value can be estimated by testing different cp values and using cross-validation approaches to determine the corresponding prediction accuracy of the model. The best <code>cp</code> is then defined as the one that maximize the cross-validation accuracy (Chapter @ref(cross-validation)).</p>
<p>Pruning can be easily performed in the <code>caret</code> package workflow, which invokes the <code>rpart</code> method for automatically testing different possible values of <code>cp</code>, then choose the optimal <code>cp</code> that maximize the cross-validation (“cv”) accuracy, and fit the final best CART model that explains the best our data.</p>
<p>You can use the following arguments in the function <code>train()</code> [from caret package]:</p>
<ul>
<li><code>trControl</code>, to set up 10-fold cross validation</li>
<li><code>tuneLength</code>, to specify the number of possible <code>cp</code> values to evaluate. Default value is 3, here we’ll use 10.</li>
</ul>
<pre class="r"><code># Fit the model on the training set
set.seed(123)
model2 <- train(
  diabetes ~., data = train.data, method = "rpart",
  trControl = trainControl("cv", number = 10),
  tuneLength = 10
  )
# Plot model accuracy vs different values of
# cp (complexity parameter)
plot(model2)</code></pre>
<p><img src="https://www.sthda.com/english/sthda-upload/figures/machine-learning-essentials/039-decision-tree-models-choosing-the-best-complexity-parameter-1.png" width="384" /></p>
<pre class="r"><code># Print the best tuning parameter cp that
# maximizes the model accuracy
model2$bestTune</code></pre>
<pre><code>##       cp
## 2 0.0321</code></pre>
<pre class="r"><code># Plot the final tree model
par(xpd = NA) # Avoid clipping the text in some device
plot(model2$finalModel)
text(model2$finalModel,  digits = 3)</code></pre>
<p><img src="https://www.sthda.com/english/sthda-upload/figures/machine-learning-essentials/039-decision-tree-models-pruning-trees-1.png" width="384" /></p>
<pre class="r"><code># Decision rules in the model
model2$finalModel</code></pre>
<pre><code>## n= 314 
## 
## node), split, n, loss, yval, (yprob)
##       * denotes terminal node
## 
##  1) root 314 104 neg (0.6688 0.3312)  
##    2) glucose< 128 188  26 neg (0.8617 0.1383) *
##    3) glucose>=128 126  48 pos (0.3810 0.6190)  
##      6) glucose< 166 88  44 neg (0.5000 0.5000)  
##       12) age< 23.5 16   1 neg (0.9375 0.0625) *
##       13) age>=23.5 72  29 pos (0.4028 0.5972) *
##      7) glucose>=166 38   4 pos (0.1053 0.8947) *</code></pre>
<pre class="r"><code># Make predictions on the test data
predicted.classes <- model2 %>% predict(test.data)
# Compute model accuracy rate on test data
mean(predicted.classes == test.data$diabetes)</code></pre>
<pre><code>## [1] 0.795</code></pre>
<div class="success">
<p>
From the output above, it can be seen that the best value for the complexity parameter (cp) is 0.032, allowing a simpler tree, easy to interpret, with an overall accuracy of 79%, which is comparable to the accuracy (78%) that we have obtained with the full tree. The prediction accuracy of the pruned tree is even better compared to the full tree.
</p>
<p>
Taken together, we should go for this simpler model.
</p>
</div>
</div>
</div>
<div id="regression-trees" class="section level2">
<h2>Regression trees</h2>
<p>Previously, we described how to build a classification tree for predicting the group (i.e. class) of observations.

In this section, we’ll describe how to build a tree for predicting a continuous variable, a method called regression analysis (Chapter @ref(regression-analysis)).</p>
<p>The R code is identical to what we have seen in previous sections. Pruning should be also applied here to limit overfiting.</p>
<p>Similarly to classification trees, the following R code uses the <code>caret</code> package to build regression trees and to predict the output of a new test data set.</p>
<div id="example-of-data-set-1" class="section level3">
<h3>Example of data set</h3>
<p>Data set: 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, using different 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")
# Inspect the data
sample_n(Boston, 3)
# 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="create-the-regression-tree" class="section level3">
<h3>Create the regression tree</h3>
<p>Here, the best <code>cp</code> value is the one that minimize the prediction error RMSE (root mean squared error).</p>
<p>The prediction error is measured by the RMSE, which corresponds to the average difference between the observed known values of the outcome and the predicted value by the model. RMSE is computed as <code>RMSE = mean((observeds - predicteds)^2) %>% sqrt()</code>. The lower the RMSE, the better the model.</p>
<p>Choose the best cp value:</p>
<pre class="r"><code># Fit the model on the training set
set.seed(123)
model <- train(
  medv ~., data = train.data, method = "rpart",
  trControl = trainControl("cv", number = 10),
  tuneLength = 10
  )
# Plot model error vs different values of
# cp (complexity parameter)
plot(model)
# Print the best tuning parameter cp that
# minimize the model RMSE
model$bestTune</code></pre>
<p><img src="https://www.sthda.com/english/sthda-upload/figures/machine-learning-essentials/039-decision-tree-models-regression-trees-cp-complexity-parameter-1.png" width="384" /></p>
<p>Plot the final tree model:</p>
<pre class="r"><code># Plot the final tree model
par(xpd = NA) # Avoid clipping the text in some device
plot(model$finalModel)
text(model$finalModel, digits = 3)</code></pre>
<p><img src="https://www.sthda.com/english/sthda-upload/figures/machine-learning-essentials/039-decision-tree-models-regression-trees-1.png" width="576" /></p>
<pre class="r"><code># Decision rules in the model
model$finalModel
# Make predictions on the test data
predictions <- model %>% predict(test.data)
head(predictions)
# Compute the prediction error RMSE
RMSE(predictions, test.data$medv)</code></pre>
</div>
</div>
<div id="conditionnal-inference-tree" class="section level2">
<h2>Conditionnal inference tree</h2>
<p>The conditional inference tree (ctree) uses significance test methods to select and split recursively the most related predictor variables to the outcome. This can limit overfitting compared to the classical rpart algorithm.</p>
<p>At each splitting step, the algorithm stops if there is no dependence between predictor variables and the outcome variable. Otherwise the variable that is the most associated to the outcome is selected for splitting.</p>
<p>The conditional tree can be easily computed using the <code>caret</code> workflow, which will invoke the function <code>ctree()</code> available in the <code>party</code> package.</p>
<ol style="list-style-type: decimal">
<li>Demo data: <code>PimaIndiansDiabetes2</code>. First split the data into training (80%) and test set (20%)</li>
</ol>
<pre class="r"><code># Load the data
data("PimaIndiansDiabetes2", package = "mlbench")
pima.data <- na.omit(PimaIndiansDiabetes2)
# 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>Build conditional trees using the tuning parameters <code>maxdepth</code> and <code>mincriterion</code> for controlling the tree size. <code>caret</code> package selects automatically the optimal tuning values for your data, but here we’ll specify <code>maxdepth</code> and <code>mincriterion</code>.</li>
</ol>
<p>The following example create a classification tree:</p>
<pre class="r"><code>library(party)
set.seed(123)
model <- train(
  diabetes ~., data = train.data, method = "ctree2",
  trControl = trainControl("cv", number = 10),
  tuneGrid = expand.grid(maxdepth = 3, mincriterion = 0.95 )
  )
plot(model$finalModel)</code></pre>
<p><img src="https://www.sthda.com/english/sthda-upload/figures/machine-learning-essentials/039-decision-tree-models-ctree-r-conditional-inference-tree-1.png" width="672" /></p>
<pre class="r"><code># Make predictions on the test data
predicted.classes <- model %>% predict(test.data)
# Compute model accuracy rate on test data
mean(predicted.classes == test.data$diabetes)</code></pre>
<pre><code>## [1] 0.744</code></pre>
<p>The p-value indicates the association between a given predictor variable and the outcome variable. For example, the first decision node at the top shows that <code>glucose</code> is the variable that is most strongly associated with <code>diabetes</code> with a p value < 0.001, and thus is selected as the first node.</p>
</div>
<div id="discussion" class="section level2">
<h2>Discussion</h2>
<p>This chapter describes how to build classification and regression tree in R. Trees provide a visual tool that are very easy to interpret and to explain to people.</p>
<p>Tree models might be very performant compared to the linear regression model (Chapter @ref(linear-regression)), when there is a highly non-linear and complex relationships between the outcome variable and the predictors.</p>
<p>However, building only one single tree from a training data set might results to a less performant predictive model. A single tree is unstable and the structure might be altered by small changes in the training data.</p>
<p>For example, the exact split point of a given predictor variable and the predictor to be selected at each step of the algorithm are strongly dependent on the training data set. Using a slightly different training data may alter the first variable to split in, and the structure of the tree can be completely modified.</p>
<p>Other machine learning algorithms - including <em>bagging</em>, <em>random forest</em> and <em>boosting</em> - can be used to build multiple different trees from one single data set leading to a better predictive performance. But, with these methods the interpretability observed for a single tree is lost. Note that all these above mentioned strategies are based on the CART algorithm. See Chapter @ref(bagging-and-random-forest) and @ref(boosting).</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 id="ref-zhang2016">
<p>Zhang, Zhongheng. 2016. “Decision Tree Modeling Using R.” <em>Annals of Translational Medicine</em> 4 (15).</p>
</div>
</div>
</div>


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


<!-- END HTML -->]]></description>
			<pubDate>Sun, 11 Mar 2018 00:45:00 +0100</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[Bagging and Random Forest Essentials]]></title>
			<link>https://www.sthda.com/english/articles/35-statistical-machine-learning-essentials/140-bagging-and-random-forest-essentials/</link>
			<guid>https://www.sthda.com/english/articles/35-statistical-machine-learning-essentials/140-bagging-and-random-forest-essentials/</guid>
			<description><![CDATA[<!-- START HTML -->

  <div id="rdoc">

<p>In the Chapter @ref(decision-tree-models), we have described how to build decision trees for predictive modeling.</p>
<p>The standard decision tree model, CART for classification and regression trees, build only one single tree, which is then used to predict the outcome of new observations. The output of this strategy is very unstable and the tree structure might be severally affected by a small change in the training data set.</p>
<p>There are different powerful alternatives to the classical CART algorithm, including <strong>bagging</strong>, <strong>Random Forest</strong> and <strong>boosting</strong>.</p>
<p><strong>Bagging</strong> stands for <em>bootstrap aggregating</em>. It consists of building multiple different decision tree models from a single training data set by repeatedly using multiple bootstrapped subsets of the data and averaging the models. Here, each tree is build independently to the others. Read more on bootstrapping in the Chapter @ref(bootstrap-resampling).</p>
<p><strong>Random Forest</strong> algorithm, is one of the most commonly used and the most powerful machine learning techniques. It is a special type of bagging applied to decision trees.</p>
<p>Compared to the standard CART model (Chapter @ref(decision-tree-models)), the random forest provides a strong improvement, which consists of applying bagging to the data and bootstrap sampling to the predictor variables at each split <span class="citation">(James et al. 2014, <span class="citation">P. Bruce and Bruce (2017)</span>)</span>. This means that at each splitting step of the tree algorithm, a random sample of n predictors is chosen as split candidates from the full set of the predictors.</p>
<p>Random forest can be used for both classification (predicting a categorical variable) and regression (predicting a continuous variable).</p>
<p>In this chapter, we’ll describe how to compute random forest algorithm in R for building a powerful predictive model. Additionally, you’ll learn how to rank the predictor variable according to their importance in contributing to the model accuracy.</p>
<p>Contents:</p>
<div id="TOC">
<ul>
<li><a href="#loading-required-r-packages">Loading required R packages</a></li>
<li><a href="#classification">Classification</a><ul>
<li><a href="#example-of-data-set">Example of data set</a></li>
<li><a href="#computing-random-forest-classifier">Computing random forest classifier</a></li>
<li><a href="#variable-importance">Variable importance</a></li>
</ul></li>
<li><a href="#regression">Regression</a><ul>
<li><a href="#example-of-data-set-1">Example of data set</a></li>
<li><a href="#computing-random-forest-regression-trees">Computing random forest regression trees</a></li>
</ul></li>
<li><a href="#hyperparameters">Hyperparameters</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>randomForest</code> for computing random forest algorithm</li>
</ul>
<pre class="r"><code>library(tidyverse)
library(caret)
library(randomForest)</code></pre>
</div>
<div id="classification" class="section level2">
<h2>Classification</h2>
<div id="example-of-data-set" class="section level3">
<h3>Example of data set</h3>
<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>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-random-forest-classifier" class="section level3">
<h3>Computing random forest classifier</h3>
<p>We’ll use the <code>caret</code> workflow, which invokes the <code>randomforest()</code> function [randomForest package], to automatically select the optimal number (<code>mtry</code>) of predictor variables randomly sampled as candidates at each split, and fit the final best random forest model that explains the best our data.</p>
<p>We’ll use the following arguments in the function <code>train()</code>:</p>
<ul>
<li><code>trControl</code>, to set up 10-fold cross validation</li>
</ul>
<pre class="r"><code># Fit the model on the training set
set.seed(123)
model <- train(
  diabetes ~., data = train.data, method = "rf",
  trControl = trainControl("cv", number = 10),
  importance = TRUE
  )
# Best tuning parameter
model$bestTune</code></pre>
<pre><code>##   mtry
## 3    8</code></pre>
<pre class="r"><code># Final model
model$finalModel</code></pre>
<pre><code>## 
## Call:
##  randomForest(x = x, y = y, mtry = param$mtry, importance = TRUE) 
##                Type of random forest: classification
##                      Number of trees: 500
## No. of variables tried at each split: 8
## 
##         OOB estimate of  error rate: 22%
## Confusion matrix:
##     neg pos class.error
## neg 185  25       0.119
## pos  44  60       0.423</code></pre>
<pre class="r"><code># Make predictions on the test data
predicted.classes <- model %>% predict(test.data)
head(predicted.classes)</code></pre>
<pre><code>## [1] neg pos neg neg 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.808</code></pre>
<p>By default, 500 trees are trained. The optimal number of variables sampled at each split is 8.</p>
<p>Each bagged tree makes use of around two-thirds of the observations. The remaining one-third of the observations not used to fit a given bagged tree are referred to as the out-of-bag (OOB) observations <span class="citation">(James et al. 2014)</span>.</p>
<p>For a given tree, the out-of-bag (OOB) error is the model error in predicting the data left out of the training set for that tree <span class="citation">(P. Bruce and Bruce 2017)</span>. OOB is a very straightforward way to estimate the test error of a bagged model, without the need to perform cross-validation or the validation set approach.</p>
<p>In our example, the OBB estimate of error rate is 24%.</p>
<div class="success">
<p>
The prediction accuracy on new test data is 79%, which is good.
</p>
</div>
</div>
<div id="variable-importance" class="section level3">
<h3>Variable importance</h3>
<p>The importance of each variable can be printed using the function <code>importance()</code> [randomForest package]:</p>
<pre class="r"><code>importance(model$finalModel)</code></pre>
<pre><code>##            neg    pos MeanDecreaseAccuracy MeanDecreaseGini
## pregnant 11.57  0.318                10.36             8.86
## glucose  38.93 28.437                46.17            53.30
## pressure -1.94  0.846                -1.06             8.09
## triceps   6.19  3.249                 6.85             9.92
## insulin   8.65 -2.037                 6.01            12.43
## mass      7.71  2.299                 7.57            14.58
## pedigree  6.57  1.083                 5.66            14.50
## age       9.51 12.310                15.75            16.76</code></pre>
<p>The result shows:</p>
<ul>
<li><code>MeanDecreaseAccuracy</code>, which is the average decrease of model accuracy in predicting the outcome of the out-of-bag samples when a specific variable is excluded from the model.</li>
<li><code>MeanDecreaseGini</code>, which is the average decrease in node impurity that results from splits over that variable. The Gini impurity index is only used for classification problem. In the regression the node impurity is measured by training set RSS. These measures, calculated using the training set, are less reliable than a measure calculated on out-of-bag data. See Chapter @ref(decision-tree-models) for node impurity measures (Gini index and RSS).</li>
</ul>
<div class="success">
<p>
Note that, by default (argument importance = FALSE), randomForest only calculates the Gini impurity index. However, computing the model accuracy by variable (argument importance = TRUE) requires supplementary computations which might be time consuming in the situations, where thousands of models (trees) are being fitted.
</p>
</div>
<p>Variables importance measures can be plotted using the function <code>varImpPlot()</code> [randomForest package]:</p>
<pre class="r"><code># Plot MeanDecreaseAccuracy
varImpPlot(model$finalModel, type = 1)

# Plot MeanDecreaseGini
varImpPlot(model$finalModel, type = 2)</code></pre>
<p><img src="https://www.sthda.com/english/sthda-upload/figures/machine-learning-essentials/040-bagging-and-random-forest-variable-importance-1.png" width="336" /><img src="https://www.sthda.com/english/sthda-upload/figures/machine-learning-essentials/040-bagging-and-random-forest-variable-importance-2.png" width="336" /></p>
<p>The results show that across all of the trees considered in the random forest, the glucose and age variables are the two most important variables.</p>
<p>The function <code>varImp()</code> [in caret] displays the importance of variables in percentage:</p>
<pre class="r"><code>varImp(model)</code></pre>
<pre><code>## rf variable importance
## 
##          Importance
## glucose       100.0
## age            33.5
## pregnant       19.0
## mass           16.2
## triceps        15.4
## pedigree       12.8
## insulin        11.2
## pressure        0.0</code></pre>
</div>
</div>
<div id="regression" class="section level2">
<h2>Regression</h2>
<p>Similarly, you can build a random forest model to perform regression, that is to predict a continuous variable.</p>
<div id="example-of-data-set-1" class="section level3">
<h3>Example of data set</h3>
<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, using different predictor variables.</p>
<p>Randomly split the data into training set (80% for building a predictive model) and test set (20% for evaluating the model).</p>
<pre class="r"><code># Load the data
data("Boston", package = "MASS")
# Inspect the data
sample_n(Boston, 3)
# 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-random-forest-regression-trees" class="section level3">
<h3>Computing random forest regression trees</h3>
<p>Here the prediction error is measured by the RMSE, which corresponds to the average difference between the observed known values of the outcome and the predicted value by the model. RMSE is computed as <code>RMSE = mean((observeds - predicteds)^2) %>% sqrt()</code>. The lower the RMSE, the better the model.</p>
<pre class="r"><code># Fit the model on the training set
set.seed(123)
model <- train(
  medv ~., data = train.data, method = "rf",
  trControl = trainControl("cv", number = 10)
  )
# Best tuning parameter mtry
model$bestTune
# Make predictions on the test data
predictions <- model %>% predict(test.data)
head(predictions)
# Compute the average prediction error RMSE
RMSE(predictions, test.data$medv)</code></pre>
</div>
</div>
<div id="hyperparameters" class="section level2">
<h2>Hyperparameters</h2>
<p>Note that, the random forest algorithm has a set of hyperparameters that should be tuned using cross-validation to avoid overfitting.</p>
<p>These include:</p>
<ul>
<li><code>nodesize</code>: Minimum size of terminal nodes. Default value for classification is 1 and default for regression is 5.</li>
<li><code>maxnodes</code>: Maximum number of terminal nodes trees in the forest can have. If not given, trees are grown to the maximum possible (subject to limits by nodesize).</li>
</ul>
<p>Ignoring these parameters might lead to overfitting on noisy data set <span class="citation">(P. Bruce and Bruce 2017)</span>. Cross-validation can be used to test different values, in order to select the optimal value.</p>
<p>Hyperparameters can be tuned manually using the <code>caret</code> package. For a given parameter, the approach consists of fitting many models with different values of the parameters and then comparing the models.</p>
<p>The following example tests different values of <code>nodesize</code> using the <code>PimaIndiansDiabetes2</code> data set for classification:</p>
<p>(This will take 1-2 minutes execution time)</p>
<pre class="r"><code>data("PimaIndiansDiabetes2", package = "mlbench")
models <- list()
for (nodesize in c(1, 2, 4, 8)) {
    set.seed(123)
    model <- train(
      diabetes~., data = na.omit(PimaIndiansDiabetes2), method="rf", 
      trControl = trainControl(method="cv", number=10),
      metric = "Accuracy",
      nodesize = nodesize
      )
    model.name <- toString(nodesize)
    models[[model.name]] <- model
}
# Compare results
resamples(models) %>% summary(metric = "Accuracy")</code></pre>
<pre><code>## 
## Call:
## summary.resamples(object = ., metric = "Accuracy")
## 
## Models: 1, 2, 4, 8 
## Number of resamples: 10 
## 
## Accuracy 
##    Min. 1st Qu. Median  Mean 3rd Qu.  Max. NA&amp;#39;s
## 1 0.692   0.750  0.785 0.793   0.840 0.897    0
## 2 0.692   0.744  0.808 0.788   0.841 0.850    0
## 4 0.692   0.744  0.795 0.786   0.825 0.846    0
## 8 0.692   0.750  0.808 0.796   0.841 0.897    0</code></pre>
<p>It can be seen that, using a <code>nodesize</code> value of 2 or 8 leads to the most median accuracy value.</p>
</div>
<div id="discussion" class="section level2">
<h2>Discussion</h2>
<p>This chapter describes the basics of bagging and random forest machine learning algorithms. We also provide practical examples in R for classification and regression analyses.</p>
<p>Another alternative to bagging and random forest is boosting (Chapter @ref(boosting)).</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 00:32:00 +0100</pubDate>
			
		</item>
		
		<item>
			<title><![CDATA[Gradient Boosting Essentials in R Using XGBOOST]]></title>
			<link>https://www.sthda.com/english/articles/35-statistical-machine-learning-essentials/139-gradient-boosting-essentials-in-r-using-xgboost/</link>
			<guid>https://www.sthda.com/english/articles/35-statistical-machine-learning-essentials/139-gradient-boosting-essentials-in-r-using-xgboost/</guid>
			<description><![CDATA[<!-- START HTML -->

  <div id="rdoc">

<p>Previously, we have described bagging and random forest machine learning algorithms for building a powerful predictive model (Chapter @ref(bagging-and-random-forest)).</p>
<p>Recall that bagging consists of taking multiple subsets of the training data set, then building multiple independent decision tree models, and then average the models allowing to create a very performant predictive model compared to the classical CART model (Chapter @ref(decision-tree-models)).</p>
<p>This chapter describes an alternative method called <strong>boosting</strong>, which is similar to the bagging method, except that the trees are grown sequentially: each successive tree is grown using information from previously grown trees, with the aim to minimize the error of the previous models <span class="citation">(James et al. 2014)</span>.</p>
<p>For example, given a current regression tree model, the procedure is as follow:</p>
<ol style="list-style-type: decimal">
<li>Fit a decision tree using the model residual errors as the outcome variable.</li>
<li>Add this new decision tree, adjusted by a shrinkage parameter <code>lambda</code>, into the fitted function in order to update the residuals. lambda is a small positive value, typically comprised between 0.01 and 0.001 <span class="citation">(James et al. 2014)</span>.</li>
</ol>
<p>This approach results in slowly and successively improving the fitted the model resulting a very performant model. Boosting has different tuning parameters including:</p>
<ul>
<li>The number of trees B</li>
<li>The shrinkage parameter lambda</li>
<li>The number of splits in each tree.</li>
</ul>
<p>There are different variants of boosting, including <em>Adaboost</em>, <em>gradient boosting</em> and <em>stochastic gradient boosting</em>.</p>
<p>Stochastic gradient boosting, implemented in the R package <em>xgboost</em>, is the most commonly used boosting technique, which involves resampling of observations and columns in each round. It offers the best performance. xgboost stands for extremely gradient boosting.</p>
<p>Boosting can be used for both classification and regression problems.</p>
<p>In this chapter we’ll describe how to compute boosting 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="#classification">Classification</a><ul>
<li><a href="#example-of-data-set">Example of data set</a></li>
<li><a href="#boosted-classification-trees">Boosted classification trees</a></li>
<li><a href="#variable-importance">Variable importance</a></li>
</ul></li>
<li><a href="#regression">Regression</a><ul>
<li><a href="#example-of-data-set-1">Example of data set</a></li>
<li><a href="#boosted-regression-trees">Boosted regression trees</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="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>xgboost</code> for computing boosting algorithm</li>
</ul>
<pre class="r"><code>library(tidyverse)
library(caret)
library(xgboost)</code></pre>
</div>
<div id="classification" class="section level2">
<h2>Classification</h2>
<div id="example-of-data-set" class="section level3">
<h3>Example of data set</h3>
<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>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="boosted-classification-trees" class="section level3">
<h3>Boosted classification trees</h3>
<p>We’ll use the <code>caret</code> workflow, which invokes the <code>xgboost</code> package, to automatically adjust the model parameter values, and fit the final best boosted tree that explains the best our data.</p>
<p>We’ll use the following arguments in the function <code>train()</code>:</p>
<ul>
<li><code>trControl</code>, to set up 10-fold cross validation</li>
</ul>
<pre class="r"><code># Fit the model on the training set
set.seed(123)
model <- train(
  diabetes ~., data = train.data, method = "xgbTree",
  trControl = trainControl("cv", number = 10)
  )
# Best tuning parameter
model$bestTune</code></pre>
<pre><code>##    nrounds max_depth eta gamma colsample_bytree min_child_weight subsample
## 18     150         1 0.3     0              0.8                1         1</code></pre>
<pre class="r"><code># Make predictions on the test data
predicted.classes <- model %>% predict(test.data)
head(predicted.classes)</code></pre>
<pre><code>## [1] neg pos neg neg pos neg
## Levels: neg pos</code></pre>
<pre class="r"><code># Compute model prediction accuracy rate
mean(predicted.classes == test.data$diabetes)</code></pre>
<pre><code>## [1] 0.744</code></pre>
<div class="success">
<p>
The prediction accuracy on new test data is 74%, which is good.
</p>
</div>
<p>For more explanation about the boosting tuning parameters, type <code>?xgboost</code> in R to see the documentation.</p>
</div>
<div id="variable-importance" class="section level3">
<h3>Variable importance</h3>
<p>The function <code>varImp()</code> [in caret] displays the importance of variables in percentage:</p>
<pre class="r"><code>varImp(model)</code></pre>
<pre><code>## xgbTree variable importance
## 
##          Overall
## glucose   100.00
## mass       20.23
## pregnant   15.83
## insulin    13.15
## pressure    9.51
## triceps     8.18
## pedigree    0.00
## age         0.00</code></pre>
</div>
</div>
<div id="regression" class="section level2">
<h2>Regression</h2>
<p>Similarly, you can build a random forest model to perform regression, that is to predict a continuous variable.</p>
<div id="example-of-data-set-1" class="section level3">
<h3>Example of data set</h3>
<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, using different predictor variables.</p>
<p>Randomly split the data into training set (80% for building a predictive model) and test set (20% for evaluating the model).</p>
<pre class="r"><code># Load the data
data("Boston", package = "MASS")
# Inspect the data
sample_n(Boston, 3)
# 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="boosted-regression-trees" class="section level3">
<h3>Boosted regression trees</h3>
<p>Here the prediction error is measured by the RMSE, which corresponds to the average difference between the observed known values of the outcome and the predicted value by the model.</p>
<pre class="r"><code># Fit the model on the training set
set.seed(123)
model <- train(
  medv ~., data = train.data, method = "xgbTree",
  trControl = trainControl("cv", number = 10)
  )
# Best tuning parameter mtry
model$bestTune
# Make predictions on the test data
predictions <- model %>% predict(test.data)
head(predictions)
# Compute the average prediction error RMSE
RMSE(predictions, test.data$medv)</code></pre>
</div>
</div>
<div id="discussion" class="section level2">
<h2>Discussion</h2>
<p>This chapter describes the boosting machine learning techniques and provide examples in R for building a predictive model. See also bagging and random forest methods in Chapter @ref(bagging-and-random-forest).</p>
</div>
<div id="references" class="section level2 unnumbered">
<h2>References</h2>
<div id="refs" class="references">
<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 00:22:00 +0100</pubDate>
			
		</item>
		
	</channel>
</rss>
