<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-regression-trees-in-150-lines-of-r-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-regression-trees-in-150-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/" target="_blank">STATWORX</a> we discuss algorithms daily to evaluate their usefulness for a specific project. 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 like implementing the algorithms in R by myself. Of course this means digging through the maths and the algorithms as well. However, you can challenge your understanding of the algorithm directly.</p>
<p>In my two subsequent blog post I will introduce two machine learning algorithms in 150 lines of R Code. This blog post will be about regression trees, which are the foundation of most tree-based algorithms. You can find the other blog post about coding gradient boosted machines from scratch on our <a rel="nofollow" href="https://www.statworx.com/blog/coding-gradient-boosted-machines-in-100-lines-of-code" target="_blank">blog</a>. The algorithms will cover all core mechanics, while being very generic. You can find all code on my <a rel="nofollow" href="https://www.github.com/andrebleier/cheapml" target="_blank">GitHub</a>.</p>
<h2>Gathering all puzzle pieces</h2>
<p><img alt="regression tree" src="https://i0.wp.com/www.statworx.com/wp-content/uploads/tree.png?w=450&ssl=1" class="wp-image-15876" data-recalc-dims="1"></p>
<p>Surely, there are tons of great articles out there which explain regression trees theoretically accompanied with a hands-on example. This is not the objective of this blog post. If you are interested in a hands-on tutorial with all necessary theory I strongly recommend this <a rel="nofollow" href="http://uc-r.github.io/regression_trees" target="_blank">tutorial</a>. 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. The only thing you need to know is our objective: We want to estimate our real-valued target (<code>y</code>) with a set of real-valued features (<code>X</code>).</p>
<p>Most probably you are already familiar with decision trees, which is a machine learning algorithm to solve classification tasks. As the name itself states regression trees solve regressions, i.e. estimation with continuous scaled targets. These kind of trees are the key part of every tree-based method, since the way you grow a tree is more of the same really. The differing parts among the implementations are mostly about the splitting rule. In this tutorial we will program a very simple, but generic implementation of a regression tree.</p>
<p>Fortunately, we do not have to cover much maths in this tutorial, because the algorithm itself is rather a technical than a mathematical challenge. With that said, the technical path I have chosen might not be the most efficient way, but I tried to trade-off efficiency with simplicity.</p>
<p>Anyway, as most of you might know decision or regression trees are rule-based approaches. Meaning, we are trying to split the data into partitions conditional to our feature space. The data partitioning is done with the help of a splitting criterion. There is no common ground on how to do those splits, there are rather multiple different splitting criteria with different pros and cons. We will focus on a rather simple criterion in this tutorial. Bear with me, here comes some maths.</p>
<p><img src="https://i2.wp.com/www.statworx.com/wp-content/ql-cache/quicklatex.com-bce30152a06d7bee8a710bb2aea6796e_l3.png?resize=356%2C25&ssl=1" alt="SSE = sum_{i in S_1} (y_i - bar(y)_1)^2 + sum_{i in S_2} (y_i - bar(y)_2)^2" width="356" title="Rendered by QuickLaTeX.com" data-recalc-dims="1" height="25"></p>
<p>Ok, so what does this state? This is the sum of squared errors determined in two different subsets (<img src="https://i2.wp.com/www.statworx.com/wp-content/ql-cache/quicklatex.com-94366be0a490b276dfa891caf550bb9b_l3.png?resize=17%2C16&ssl=1" alt="S_1" width="17" title="Rendered by QuickLaTeX.com" data-recalc-dims="1" height="16"> and <img src="https://i1.wp.com/www.statworx.com/wp-content/ql-cache/quicklatex.com-42795ee87a3faf709a8854b21544cbf4_l3.png?resize=18%2C15&ssl=1" alt="S_2" width="18" title="Rendered by QuickLaTeX.com" data-recalc-dims="1" height="15">). As the name suggests, that should be something we want to minimize. In fact, it is the squared distance between the mean and the target within this data subset. In every node of our regression tree we calculate the SSE for every potential split we could do in our data for every feature we have to figure out the best split we can achieve.</p>
<p>Let us have a look at the R Code:</p>
<pre><code># This is the splitting criterion we minimize (SSE [Sum Of Squared Errors]):
# SSE = \sum{i \in S_1} (y_i - \bar(y)_1)^2 + \sum{i \in S_2} (y_i - \bar(y)_2)^2
sse_var &lt;- function(x, y) {
  splits &lt;- sort(unique(x))
  sse &lt;- c()
  for (i in seq_along(splits)) {
    sp &lt;- splits[i]
    sse[i] &lt;- sum((y[x &lt; sp] - mean(y[x &lt; sp]))^2) +
              sum((y[x >= sp] - mean(y[x >= sp]))^2) 
  }
  split_at &lt;- splits[which.min(sse)]
  return(c(sse = min(sse), split = split_at))
}
</code></pre>
<p>The function takes two inputs our numeric feature <code>x</code> and our target real-valued <code>y</code>. We then go ahead and calculate the SSE for every unique value of our <code>x</code>. This means we calculate the SSE for every possible data subset we could obtain conditional on the feature. Often we want to cover more than one feature in our problem, which means that we have to run this function for every feature. As a result, the best splitting rule has the lowest SSE among all possible splits of all features. Once we have determined the best splitting rule we can split our data into these two subsets according to our criterion, which is nothing else than feature <code>x &lt;= split_at</code> and <code>x > split_at</code>. We call these two subsets children and they again can be split into subsets again.</p>
<p>Let us lose some more words on the SSE though, because it reveals our estimator. In this implementation our estimator in the leaf is simply the avarage value of our target within this data subset. This is the simplest version of a regression tree. However, with some additional work you can apply more sophisticated models, e.g. an ordinary least squares fit.</p>
<h2>The Algorithm</h2>
<p>Enough with the talking, let's get to the juice. In the following you will see the algorithm in all of its beauty. Afterwards we will breakdown the algorithm in easy-to-digest code chunks.</p>
<pre><code>#' reg_tree
#' Fits a simple regression tree with SSE splitting criterion. The estimator function
#' is the mean.
#' 
#' @param formula an object of class formula
#' @param data a data.frame or matrix
#' @param minsize a numeric value indicating the minimum size of observations
#'                in a leaf
#'
#' @return \itemize{
#' \item tree - the tree object containing all splitting rules and observations
#' \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
reg_tree &lt;- function(formula, data, minsize) {
  
  # 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]]
  
  # initialize while loop
  do_splits &lt;- TRUE
  
  # create output data.frame with splitting rules and observations
  tree_info &lt;- data.frame(NODE = 1, NOBS = nrow(data), FILTER = NA,
                          TERMINAL = &quot;SPLIT&quot;,
                          stringsAsFactors = FALSE)
  
  # keep splitting until there are only leafs left
  while(do_splits) {
    
    # which parents have to be splitted
    to_calculate &lt;- which(tree_info$TERMINAL == &quot;SPLIT&quot;)
    
    for (j in to_calculate) {
      
      # handle root node
      if (!is.na(tree_info[j, &quot;FILTER&quot;])) {
        # subset data according to the filter
        this_data &lt;- subset(data, eval(parse(text = tree_info[j, &quot;FILTER&quot;])))
        # get the design matrix
        X &lt;- model.matrix(formula, this_data)
      } else {
        this_data &lt;- data
      }
      
      # estimate splitting criteria
      splitting &lt;- apply(X,  MARGIN = 2, FUN = sse_var, y = y)
      
      # get the min SSE
      tmp_splitter &lt;- which.min(splitting[1,])
      
      # define maxnode
      mn &lt;- max(tree_info$NODE)
      
      # paste filter rules
      tmp_filter &lt;- c(paste(names(tmp_splitter), &quot;>=&quot;, 
                            splitting[2,tmp_splitter]),
                      paste(names(tmp_splitter), &quot;&lt;&quot;, 
                            splitting[2,tmp_splitter]))
      
      # Error handling! check if the splitting rule has already been invoked
      split_here  &lt;- !sapply(tmp_filter,
                             FUN = function(x,y) any(grepl(x, x = y)),
                             y = tree_info$FILTER)
      
      # append the splitting rules
      if (!is.na(tree_info[j, &quot;FILTER&quot;])) {
        tmp_filter  &lt;- paste(tree_info[j, &quot;FILTER&quot;], 
                             tmp_filter, sep = &quot; &amp; &quot;)
      } 
      
      # get the number of observations in current node
      tmp_nobs &lt;- sapply(tmp_filter,
                         FUN = function(i, x) {
                           nrow(subset(x = x, subset = eval(parse(text = i))))
                         },
                         x = this_data)  
      
      # insufficient minsize for split
      if (any(tmp_nobs &lt;= minsize)) {
        split_here &lt;- rep(FALSE, 2)
      }
      
      # create children data frame
      children &lt;- data.frame(NODE = c(mn+1, mn+2),
                             NOBS = tmp_nobs,
                             FILTER = tmp_filter,
                             TERMINAL = rep(&quot;SPLIT&quot;, 2),
                             row.names = NULL)[split_here,]
      
      # overwrite state of current node
      tree_info[j, &quot;TERMINAL&quot;] &lt;- ifelse(all(!split_here), &quot;LEAF&quot;, &quot;PARENT&quot;)
       
      # bind everything
      tree_info &lt;- rbind(tree_info, children)
      
      # check if there are any open splits left
      do_splits &lt;- !all(tree_info$TERMINAL != &quot;SPLIT&quot;)
    } # end for
  } # end while
  
  # calculate fitted values
  leafs &lt;- tree_info[tree_info$TERMINAL == &quot;LEAF&quot;, ]
  fitted &lt;- c()
  for (i in seq_len(nrow(leafs))) {
    # extract index
    ind &lt;- as.numeric(rownames(subset(data, eval(parse(text = leafs[i, &quot;FILTER&quot;])))))
    # estimator is the mean y value of the leaf
    fitted[ind] &lt;- mean(y[ind])
  }
  
  # return everything
  return(list(tree = tree_info, fit = fitted, formula = formula, data = data))
}
</code></pre>
<p>Uff, that was a lot of scrolling. Ok, so what do we have here. At first glance we see two loops a while loop and a for loop, which are essential to the algorithm. But let us start bit by bit. Let's have a look at the first code chunk.</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]]
  
  # initialize while loop
  do_splits &lt;- TRUE
  
  # create output data.frame with splitting rules and observations
  tree_info &lt;- data.frame(NODE = 1, NOBS = nrow(data), FILTER = NA, 
                          TERMINAL = &quot;SPLIT&quot;,
                          stringsAsFactors = FALSE)
</code></pre>
<p>Essentially, this is everything before the while loop. Here, we see some input handling in the beginning and the extraction of our design matrix <code>X</code> and our target <code>y</code>. All our featuers are within this design matrix. <code>do_splits</code> is the condition for our while loop, which we will cover in a bit. The data frame <code>tree_info</code> is the key storage element in our algorithm, because it will contain every information we need about our tree. The essential piece of this object is the filter column. This column saves the paths (filter) we have to take through (to apply to) our data to get to a leaf (a terminal node) in our regression tree. We initiate this <code>data.frame</code> with <code>NODE = 1</code>, since at the beginning we are in the root node of our tree with the whole data set at our expense. Furthermore, there is a column called <code>TERMINAL</code>, which controls the state of the node. We have three different states <code>SPLIT</code>, <code>LEAF</code> and <code>PARENT</code>. When we describe a node with the <code>SPLIT</code> state, we mark it for a potential split. The state <code>PARENT</code> indicates, that we have already split this node. Lastly, the state <code>LEAF</code> marks terminal nodes of our regression tree.</p>
<h3>Reaching the treetop</h3>
<p>When do we reach such a terminal node? In many implementations there is a minimum size parameter, where we determine valid splits by the amount of observations of its children. If the children have lower data points than the minimum size the split is invalid and will not be done. Imagine not having this parameter in our case, we could end up with leafs covering only one observation. Another termination rule is if the lowest SSE is at a split we have already invoked within the branch and hence has already been invoked in this branch. The split at such a point would be nonsense, since we would end up with the same subset over and over again.</p>
<p>Basically, this is everything there is to the algorithm. The while and for loop just ensure, that we estimate and create every node in our <code>tree_info</code>. Thus, you can perceive the <code>tree_info</code> as sort of a job list, since we create new jobs within this data frame. Let us walk through the actual R code.</p>
<pre><code>  # keep splitting until there are only leafs left
  while(do_splits) {
    
    # which parents have to be splitted
    to_calculate &lt;- which(tree_info$TERMINAL == &quot;SPLIT&quot;)
    
    for (j in to_calculate) {
      
      # handle root node
      if (!is.na(tree_info[j, &quot;FILTER&quot;])) {
        # subset data according to the filter
        this_data &lt;- subset(data, eval(parse(text = tree_info[j, &quot;FILTER&quot;])))
        # get the design matrix
        X &lt;- model.matrix(formula, this_data)
      } else {
        this_data &lt;- data
      }
      
      # estimate splitting criteria
      splitting &lt;- apply(X,  MARGIN = 2, FUN = sse_var, y = y)
      
      # get the min SSE
      tmp_splitter &lt;- which.min(splitting[1,])
      
      # define maxnode
      mn &lt;- max(tree_info$NODE)
      
      # paste filter rules
      tmp_filter &lt;- c(paste(names(tmp_splitter), &quot;>=&quot;, 
                            splitting[2,tmp_splitter]),
                      paste(names(tmp_splitter), &quot;&lt;&quot;, 
                            splitting[2,tmp_splitter]))
      
      # Error handling! check if the splitting rule has already been invoked
      split_here  &lt;- !sapply(tmp_filter,
                             FUN = function(x,y) any(grepl(x, x = y)),
                             y = tree_info$FILTER)
      
      # append the splitting rules
      if (!is.na(tree_info[j, &quot;FILTER&quot;])) {
        tmp_filter  &lt;- paste(tree_info[j, &quot;FILTER&quot;], 
                             tmp_filter, sep = &quot; &amp; &quot;)
      } 
      
      # get the number of observations in current node
      tmp_nobs &lt;- sapply(tmp_filter,
                         FUN = function(i, x) {
                           nrow(subset(x = x, subset = eval(parse(text = i))))
                         },
                         x = this_data)  
      
      # insufficient minsize for split
      if (any(tmp_nobs &lt;= minsize)) {
        split_here &lt;- rep(FALSE, 2)
      }
      
      # create children data frame
      children &lt;- data.frame(NODE = c(mn+1, mn+2),
                             NOBS = tmp_nobs,
                             FILTER = tmp_filter,
                             TERMINAL = rep(&quot;SPLIT&quot;, 2),
                             row.names = NULL)[split_here,]
      
      # overwrite state of current node
      tree_info[j, &quot;TERMINAL&quot;] &lt;- ifelse(all(!split_here), &quot;LEAF&quot;, &quot;PARENT&quot;)
       
      # bind everything
      tree_info &lt;- rbind(tree_info, children)
      
      # check if there are any open splits left
      do_splits &lt;- !all(tree_info$TERMINAL != &quot;SPLIT&quot;)
    } # end for
  } # end while
</code></pre>
<p>The while loop covers our tree depth and our for loop all splits within this certain depth. Within the while loop we seek every row in our <code>tree_info</code>, which we still have to estimate, i.e. all nodes in the <code>&quot;SPLIT&quot;</code> state. In the first iteration it would be the first row, our root node. The for loop iterates over all potential splitting nodes. The first if condition ensures that we filter our data according to the tree depth. Of course, there is no filter in the root node that is why we take the data as is. But imagine calculating possible splits for a parent in depth level two. The filter would look similar to this one: <code>&quot;feature_1 > 5.33 &amp; feature_2 &lt;= 3.22&quot;</code>. </p>
<h3>How do we apply splitting?</h3>
<p>Afterwards we seek the minimum SSE by applying the <code>sse_var</code> function to every feature. Note, that in this version we can only handle numeric features. Once we have found the best splitting variable, here named <code>tmp_splitter</code>, we build the according filter rule in object <code>tmp_filter</code>. </p>
<p>We still have to check if this is a valid split, i.e. we have not invoked this split for this branch yet and we have sufficient observations in our children. Our indicator <code>split_here</code> rules whether we split our node. Well, that is about it. In the last passage of the loop we prepare the output for this node. That is, handling the state of the calculated node and adding the children information to our job list <code>tree_info</code>. After the for loop we have to check whether our tree is fully grown. The variable <code>do_splits</code> checks whether there are any nodes left we have to calculate. We terminate the calculation if there are no <code>&quot;SPLIT&quot;</code> nodes left in our <code>tree_info</code>. </p>
<h3>Extracting our estimates</h3>
<pre><code> # calculate fitted values
  leafs &lt;- tree_info[tree_info$TERMINAL == &quot;LEAF&quot;, ]
  fitted &lt;- c()
  for (i in seq_len(nrow(leafs))) {
    # extract index
    ind &lt;- as.numeric(rownames(subset(data, eval(parse(
        					   text = leafs[i, &quot;FILTER&quot;])))))
    # estimator is the mean y value of the leaf
    fitted[ind] &lt;- mean(y[ind])
  }
</code></pre>
<p>At the end of our calculation we have a filter rule for every leaf in our tree. With the help of these filters we can easily calculate the fitted values by simply applying the filter on our data and calculating our fit, i.e. the mean of our target in this leaf. I am sure by now you can think of a way to implement more sophisticated estimators, which I would leave up to you.</p>
<p>Well, that's a regression tree with minimum size restriction. I have created a little runthrough with data from my <a rel="nofollow" href="https://www.statworx.com/de/blog/coding-regression-trees-in-150-lines-of-code/blog/benchmarking-feature-selection-algorithms-with-xy/" target="_blank">simulation package</a> on my <a rel="nofollow" href="https://www.github.com/andrebleier/cheapml" target="_blank">GitHub</a>, which you can checkout and try everything on your own. Make sure to checkout my other blog post about <a rel="nofollow" href="https://www.statworx.com/blog/coding-gradient-boosted-machines-in-100-lines-of-code" target="_blank">coding gradient boosted machines from scratch</a>.</p>
<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>
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<h1>ABOUT US</h1>
</div>
</div>
</div>
<hr>
<div>
<p><span><span>STATWORX</span><br></span><span>is a consulting company for data science, statistics, machine learning and artificial intelligence </span><span>located in Frankfurt, Zurich and Vienna. Sign up for our NEWSLETTER and receive reads and treats from the world of data science and AI.</span> </p>
</div>
<p><a data-x-toggle="1" tabindex="0" data-x-toggleable="e15819-7">
<p> <span>
<p><span>
<p><i data-x-icon-o=""></i></p>
<p> <span><span>Sign Up Now!</span></span> </p></span>
<p>




<p>Der Beitrag <a rel="nofollow" href="https://www.statworx.com/de/blog/coding-regression-trees-in-150-lines-of-code/" target="_blank">Coding Regression trees in 150 lines of R 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-regression-trees-in-150-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/GgRQNtIp0hA" height="1"></a></div></span></a></div></div></div></div>