<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/coding-gradient-boosted-machines-in-100-lines-of-code/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://www.statworx.com/de/blog/coding-gradient-boosted-machines-in-100-lines-of-code/"> r-bloggers – STATWORX</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<h2>Motivation</h2>
<p>There are dozens of machine learning algorithms out there. It is impossible to learn all their mechanics, however, many algorithms sprout from the most established algorithms, e.g. ordinary least squares, gradient boosting, support vector machines, tree-based algorithms and neural networks. At <a rel="nofollow" href="https://www.statworx.com/de/blog/coding-gradient-boosted-machines-in-100-lines-of-code/www.statworx.com" target="_blank">STATWORX</a> we discuss algorithms daily to evaluate their usefulness for a specific project or problem. In any case, understanding these core algorithms is key to most machine learning algorithms in the literature.</p>
<p>While I like reading machine learning research papers, the maths is sometimes hard to follow. That is why I am a fan of implementing the algorithms in R by myself. Of course this means digging through the maths as well. However, you can challenge your understanding of the algorithm directly.</p>
<p>In my two subsequent blog posts I will introduce two machine learning algorithms in under 150 lines of R Code. The algorithms will cover all core mechanics, while being very generic. You can find all code on my <a rel="nofollow" href="https://www.statworx.com/de/blog/coding-gradient-boosted-machines-in-100-lines-of-code/www.github.com/andrebleier/cheapml" target="_blank">GitHub</a>.</p>
<p><img alt="gradient boosting machine" src="https://i0.wp.com/www.statworx.com/wp-content/uploads/machine.png?w=450&ssl=1" class="wp-image-15796" data-recalc-dims="1"></p>
<p>This blog post will introduce you to gradient boosted machines. Surely, there are tons of great articles out there which explain gradient boosting theoretically accompanied with a hands-on example. This is not the objective of this blog post. If you are interested in the theory and the evolution of the algorithm I would strongly recommend reading the paper of <a rel="nofollow" href="https://www.statworx.com/de/blog/coding-gradient-boosted-machines-in-100-lines-of-code/" target="_blank">Bühlmann and Hothorn (2007)</a>.<sup>(1)</sup> The objective of this blog post is to establish the theory of the algorithm by writing simple R code. You do not need any prior knowledge of the algorithm to follow.</p>
<h2>Gathering all puzzle pieces</h2>
<p>Gradient boosting is a very special machine learning algorithm, because it is rather a vehicle for machine learning algorithms rather than a machine learning algorithm itself. That is because you can incorporate any machine learning algorithm within gradient boosting. I admit that sounds quite confusing, but it will be clear by the end of this post.</p>
<p>Anyway, what do we need to boost those gradients? Well, we need to define our problem (a little maths is necessary <img alt="🙂" src="https://s.w.org/images/core/emoji/2.4/72x72/1f642.png" class="wp-smiley"> ).</p>
<p>We have the following problem: <img src="https://i2.wp.com/www.statworx.com/wp-content/ql-cache/quicklatex.com-0c39b30313b37700e995bae58fdd2225_l3.png?resize=93%2C16&ssl=1" alt="textbf{y} = textbf{X} boldsymbol{theta} + textbf{u}" width="93" title="Rendered by QuickLaTeX.com" data-recalc-dims="1" height="16"></p>
<p>This is just a simple regression equation, where we state that we want to map our features <img src="https://i1.wp.com/www.statworx.com/wp-content/ql-cache/quicklatex.com-c78d25ca17d7f9841722248ecd5af900_l3.png?resize=15%2C14&ssl=1" alt="textbf{X}" width="15" title="Rendered by QuickLaTeX.com" data-recalc-dims="1" height="14"> onto a real valued target <img src="https://i2.wp.com/www.statworx.com/wp-content/ql-cache/quicklatex.com-6391bec774f26c708b674b14da52a3e2_l3.png?resize=11%2C12&ssl=1" alt="textbf{y}" width="11" title="Rendered by QuickLaTeX.com" data-recalc-dims="1" height="12"> with estimator <img src="https://i0.wp.com/www.statworx.com/wp-content/ql-cache/quicklatex.com-ddf302e914ec9de856caff481f22374e_l3.png?resize=10%2C12&ssl=1" alt="boldsymbol{theta}" width="10" title="Rendered by QuickLaTeX.com" data-recalc-dims="1" height="12"> and an error term (residuals) <img src="https://i1.wp.com/www.statworx.com/wp-content/ql-cache/quicklatex.com-c1af968209892028c55e03f334630ab1_l3.png?resize=11%2C8&ssl=1" alt="textbf{u}" width="11" title="Rendered by QuickLaTeX.com" data-recalc-dims="1" height="8">. This is nothing out of the ordinary every machine learning algorithm starts here or somewhere close to this equation. However, unlike other machine learning algorithms, specifying a loss funciton is mandatory. </p>
<pre><code># this is our loss function
# y - the target
# yhat - the fitted values
loss &lt;- function(y, yhat) return(mean(1/2*(y-yhat)^2))
</code></pre>
<p>Our objective is to find the minimum of this loss function, which is an adaption of the mean squared error. The algorithm exploits the fact that in a minimum there is no slope in our loss function. The gradient of our function, which is the negative partial derivative with respect to <code>yhat</code>, describes this slope. So we can actually reformulate our objective to searching a gradient of zero or close to zero to ultimately fulfill our goal of minimzing the loss. </p>
<pre><code># the derivative of our loss function is the gradient
# y - the target
# yhat - the fitted values
gradient &lt;- function(y, yhat) {return(y - yhat)}
</code></pre>
<p>Now comes the interesting part of the algorithm. In our case the gradient coincides with the residuals <code>u = y – yhat</code>. Remember, we want the gradient to be zero or close to zero. Or put differently, we want the state <code>y = yhat</code>. The algorithm exploits this fact by simply iteratively fitting (boosting) the residuals (the gradient) instead of <code>y</code> itself. This means we update our gradient in every iteration to improve our fit in general. This step describes our movement to the minimum of our loss function. We will clarify this observation with a little exmple once we see the theory in action. </p>
<h2>The algorithm</h2>
<p>Let us first have a look at the algorithm as a whole. </p>
<pre><code># grad_boost
#' Fit a boosted linear model
#'
#' @param formula an object of class formula
#' @param data a data.frame or matrix
#' @param nu a numeric within the range of [0,1], the learning rate
#' @param stop a numeric value determining the total boosting iterations
#' @param loss.fun a convex loss function which is continuously differentiable
#' @param grad.fun a function which computes the gradient of the loss function
#' @param yhat.init a numeric value determining the starting point
#'
#' @return \itemize{
#' \item theta - this is our estimator
#' \item u - this is the last gradient value
#' \item fit - our fitted values, i.e. X %*% theta
#' \item formula - the underlying formula
#' \item data - the underlying data
#' }
#' @export
#'
#' @examples # Complete runthrough see: www.github.com/andrebleier/cheapml
grad_boost &lt;- function(formula, data, nu = 0.01, stop, 
                       grad.fun, loss.fun, yhat.init = 0) {
  
  # coerce to data.frame
  data &lt;- as.data.frame(data)
  
  # handle formula
  formula &lt;- terms.formula(formula)
  
  # get the design matrix
  X &lt;- model.matrix(formula, data)
    
  # extract target
  y &lt;- data[, as.character(formula)[2]]

  # initial fit
  fit &lt;- yhat.init
  
  # initialize the gradient with yhat.init
  u &lt;- grad.fun(y = y, yhat = fit)
  
  # initial working parameter (our theta)
  # this is just an empty body
  theta &lt;- rep(0, ncol(X))
  
  # track loss
  loss &lt;- c()
  
  # boost from 1 to stop
  for (i in 1:stop) {
    
    # estimate working parameter (via OLS)
    # theta_i = (X'X)^-1 X'y
    # This is the (base procedure) where you can literally place 
    # any optimization algorithm
    base_prod &lt;- lm.fit(x = X, y = u)
    theta_i &lt;- coef(base_prod)
  
    # update our theta
    theta &lt;- theta + nu*as.vector(theta_i)
    
    # new fitted values
    fit &lt;- fit + nu * fitted(base_prod)
    
    # update gradient
    u &lt;- grad.fun(y = y, yhat = fit)
    
    # update loss 
    loss &lt;- append(loss, loss.fun(y = y, yhat = fit))
  }  
  
  # naming the estimator
  names(theta) &lt;- colnames(X)
  
  # define return
  return(list(theta = theta, u = u, fit = fit, loss = loss, 
              formula = formula, data = data))
}
</code></pre>
<p>All the magic happens within the <code>for</code> loop, which is coded in less than 30 lines of code. Everything else is just input/output handling and so on. </p>
<p>Let us breakdown what is happening.</p>
<pre><code># coerce to data.frame
  data &lt;- as.data.frame(data)
  
  # handle formula
  formula &lt;- terms.formula(formula)
  
  # get the design matrix
  X &lt;- model.matrix(formula, data)
    
  # extract target
  y &lt;- data[, as.character(formula)[2]]

  # initial fit
  fit &lt;- f.init
  
  # initialize the gradient with yhat.init
  u &lt;- grad.fun(y = y, yhat = fit)
  
  # initial working parameter (our theta)
  # this is just an empty body
  theta &lt;- rep(0, ncol(X))
  
  # track loss
  loss &lt;- c()
</code></pre>
<p>The first part is just input handling, but we can see that we have to initialize the gradient, by starting with a best guess fit <code>yhat.init</code>, e.g. zero. After initializing, we need some containers to store our loss and our estimator <code>theta</code>.</p>
<p>The next part is all about our optimization, where we iteratively approaching the minimum of our prespecified loss function.</p>
<pre><code># boost from 1 to stop
for (i in 1:stop) {
    
    # estimate working parameter (via OLS)
    # theta_i = (X'X)^-1 X'y
    # This is the (base procedure) where you can literally place 
    # any optimization algorithm
    base_prod &lt;- lm.fit(x = X, y = u)
    theta_i &lt;- coef(base_prod)
  
    # update our theta
    theta &lt;- theta + nu*as.vector(theta_i)
    
    # new fitted values
    fit &lt;- fit + nu * fitted(base_prod)
    
    # update gradient
    u &lt;- grad.fun(y = y, yhat = fit)
    
    # update loss 
    loss &lt;- append(loss, loss.fun(y = y, yhat = fit))
}
</code></pre>
<h2>Unveiling the magic</h2>
<p>Alright, let’s get to the gravy. We will go through the first iteration step by step. The first thing we are doing is to estimate the gradient with a simple regression. Yes, a simple regression which you unfortunately have to accept here for a moment. Remember how we initialized the gradient. In the first iteration we are doing ordinary least squares with our features <code>X</code> and our target <code>y</code>, because the gradient coincides with our target, i.e. <code>u = y - 0</code>. What happens next is the last missing puzzle piece to gradient boosting. We are simply updating our estimator <code>theta</code> the fitted values <code>fit</code> and our gradient <code>u</code>. But what does this accomplish? Suppose, this multiplier <code>nu</code> is equal to one, then the following is quite straightforward. We are stating that our new fit – we initialized it with zero – is plain ordinary least squares and our estimator <code>theta</code> is the OLS estimate as well. After updating the gradient we observe that the gradient in iteration two is actually the residuals from the OLS fit of iteration one. </p>
<p>Let us recap that in some code real quick. In the first iteration we were actually fitting <code>y</code>, since <code>u = y - 0</code> and in the second iteration we are fitting <code>u = resid(base_prod)</code>, since <code>u = y – fitted(base_prod)</code>. Thus, if we repeat this often enough <code>u</code> should converge to zero, since our fit will improve everytime. But why should it improve everytime? The algorithm allows us to fit the gradient – which again are the residuals – at every iteration with completely new estimates <code>theta_i</code>. Naturally, this guess will be good enough to let the gradient converge towards zero or put differently minimize the distance between our target <code>y</code> and our fit <code>yhat</code>. And yes, this means that with gradient boosting we can theoretically reach the equilibrium of <code>y = yhat</code>, which we desire. But do we though? Remember we could theoretically reach that state in every problem we estimate with gradient boosting. Well, the important point to note here is that we can only do this for the data we have at hand. Chances are very high when observing new data, that our gradient boosted machine is garbage, because our estimator <code>theta</code> does not cover the underlying effect of our featuers on the target, but covers rather a combination which minimizes our loss function with the data we fed it. That is why we have to control the boosting iterations. We have to terminate the iterative fitting at the right time, to get a <code>theta</code> which explains the effect we are interested in rather than minimizing loss functions. There are so-called early-stopping techniques which terminate the learning by an exceeding of an out of sample risk to avoid this phenomenom called overfitting the data.</p>
<p>Anyway, let us come back to the parameter <code>nu</code>. This is the shrinkage (learning rate) parameter. It controls how big the steps towards the minimum of our loss function are. Suppose, the same scenario as above with <code>nu = 0.1</code>, that would mean we would not get the full OLS fit, but only 10% of it. As a result, we would need more iterations to converge to the minimum, however, empirically smaller learning rates have been found to yield better predictive accuracies.<sup>(2)</sup> </p>
<p>At the beginning I have stated that gradient boosting is rather a vehicle for machine learning algorithms than a machine learning algorithm itself. Essentially, this is because instead of <code>lm.fit</code> we could have used any other optimization function here. Most gradient boosted machines out there use tree-based algorithms, e.g. <a rel="nofollow" href="https://www.statworx.com/blog/xgboost-tree-vs-linear/" target="_blank">xgboost</a>. This makes the gradient boosted machine to a very unique machine learning algorithm.</p>
<p>I have created a little runthrough with data from my <a rel="nofollow" href="https://www.statworx.com/blog/benchmarking-feature-selection-algorithms-with-xy/" target="_blank">simulation function</a> on my <a rel="nofollow" href="https://www.statworx.com/de/blog/coding-gradient-boosted-machines-in-100-lines-of-code/www.github.com/andrebleier/cheapml" target="_blank">GitHub</a>, which you can checkout and try everything on your own step by step. There will be a subsequent blog post about regression trees, for which you can keep an eye out.</p>
<h2>References</h2>
<ol>
<li>Bühlmann, P., &amp; Hothorn, T. (2007). Boosting algorithms: Regularization, prediction and model fitting. <em>Statistical Science</em>, <em>22</em>(4), 477-505</li>
<li>Friedman, J. H. (2001). Greedy function approximation: a gradient boosting machine. <em>Annals of statistics</em>, 1189-1232.</li>
</ol>
<div>
<h6>Über den Autor</h6>
<p><img src="https://i2.wp.com/www.statworx.com/wp-content/uploads/andre-1-300x300.jpg?resize=180%2C180&ssl=1" width="180" alt="André Bleier" class="wp-user-avatar wp-user-avatar-180" data-recalc-dims="1" height="180"></p>
<div>
<h4>André Bleier</h4>
<p>The most exciting part of being a data scientist at <a rel="nofollow" href="https://www.statworx.com/" target="_blank">STATWORX</a> is to find this unique solution to a problem by fusing machine learning, statistics and business knowledge.</p>
</div>
</div>
<p>Der Beitrag <a rel="nofollow" href="https://www.statworx.com/de/blog/coding-gradient-boosted-machines-in-100-lines-of-code/" target="_blank">Coding Gradient boosted machines in 100 lines of code</a> erschien zuerst auf <a rel="nofollow" href="https://www.statworx.com/de/" target="_blank">STATWORX</a>.</p>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://www.statworx.com/de/blog/coding-gradient-boosted-machines-in-100-lines-of-code/"> r-bloggers – STATWORX</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/6FLI4Mw8Ks8" height="1"></a></div>