<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/in-database-xgboost-predictions-with-r/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://rviews.rstudio.com/2018/11/07/in-database-xgboost-predictions-with-r/"> R Views</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>Moving predictive machine learning algorithms into large-scale production environments can present many challenges. For example, problems arise when attempting to calculate prediction probabilities (“scores”) for many thousands of subjects using many thousands of features located on remote databases.</p>
<p><a rel="nofollow" href="https://cran.r-project.org/web/packages/xgboost/" target="_blank"><code>xgboost</code></a> (<a rel="nofollow" href="https://xgboost.readthedocs.io/en/latest/index.html" target="_blank">docs</a>), a popular algorithm for classification and regression, and the model of choice in many winning <a rel="nofollow" href="https://www.kaggle.com/" target="_blank">Kaggle</a> competitions, is no exception. However, to run <code>xgboost</code>, the subject-features matrix <a rel="nofollow" href="https://xgboost.readthedocs.io/en/latest/faq.html#i-have-a-big-dataset" target="_blank">must be loaded into memory</a>, a <strong>cumbersome and expensive</strong> process.</p>
<p>Available solutions require using expensive high-memory machines, or implementing external memory across distributed machines (expensive and in <a rel="nofollow" href="https://xgboost.readthedocs.io/en/latest/tutorials/external_memory.html" target="_blank">beta</a>). Both solutions still require transferring all feature data from the database to the local machine(s), loading it into memory, calculating the probabilities for the subjects, and then transferring the probabilities back to the database for storage. I have seen this take, <strong>20-50 minutes for ~1MM subjects</strong>.</p>
<p>In this post, we will consider <strong>in-database scoring</strong>, a simple alternative for calculating batch predictions without having to transfer features stored in a database to the machine where the model is located. Instead, we will convert the model predictions into SQL commands and thereby transfer the scoring process to the database.</p>
<p><img src="https://i1.wp.com/rviews.rstudio.com/post/2018-11-05-Roland-xgboost_files/xgboost_workflows.PNG?w=450&ssl=1" data-recalc-dims="1" height="400"></p>
<p>We will convert the <code>xgboost</code> model prediction process into a SQL query, and thereby accomplish the same task while leveraging a cloud database’s scalability to efficiently calculate the predictions.</p>
<p>To accomplish this, we’ll need to work through a few steps. First, we’ll import the model as a list of nested tree structures that we can iterate through recursively. Then, we’ll create a function that will recursively descend through a tree and translate it into a SQL CASE statement. After that, we’ll create a query that sums the CASE statements for all trees before logit-transforming it to calculate a probability.</p>
<p>This first block of code loads the required packages and converts the model object to a list of trees that we can work with:</p>
<pre><code>library(xgboost)
library(jsonlite) 
library(whisker)

# our model exists in the variable `xgb_model`:
# dump the list of trees as JSON and import it as `model_trees` using jsonlite
model_trees &lt;- jsonlite::fromJSON(
  xgb.dump(xgb_model, with_stats = FALSE, dump_format='json'), 
  simplifyDataFrame = FALSE)
</code></pre>
<p><img src="https://i0.wp.com/rviews.rstudio.com/post/2018-11-05-Roland-xgboost_files/xgboost_tree_structure.PNG?w=450&ssl=1" data-recalc-dims="1" height="400"></p>
<p>Now, we need to translate each tree into a SQL CASE statement. Each tree represents a set of decisions based on whether a variable (the ‘split’) is less than a threshold value (the ‘split_condition’). The result of the decision could be ‘yes’, ‘no’, or ‘missing’. In each case, the tree provides the ‘node_id’ of the next decision to evaluate. When we reach a leaf, no decision needs to be made and instead a value is returned. An example tree is shown below:</p>
<p>We’ll also need a dictionary that maps an integer to its associated feature name, since the trees themselves refer to 0-indexed integers instead of the feature names. We can accomplish that by creating the following list:</p>
<pre><code>feature_dict &lt;- as.list(xgb_model$feature_names)
</code></pre>
<p>Using our <code>feature_dict</code> object, we can recursively descend through the tree and translate each node into a CASE statement, producing a sequence of nested CASE statements. The following function does just that:</p>
<pre><code>xgb_tree_sql &lt;- function(tree, feature_dict, sig=5){
  # split variables must exist to generate subquery for tree children
  sv &lt;- c(&quot;split&quot;, &quot;split_condition&quot;, &quot;yes&quot;, &quot;no&quot;, &quot;missing&quot;, &quot;children&quot;)

  # we have a leaf, just return the leaf value  
  if(&quot;leaf&quot; %in% names(tree)){
    return(round(tree[['leaf']],sig))
  }

  else if(all(sv %in% names(tree))){
    tree$split_long &lt;- feature_dict[[tree$split+1]] # +1 because xgboost is 0-indexed
    
    cs &lt;- c(tree$yes, tree$no, tree$missing)
    cd &lt;- data.frame(
      k = c(min(cs), max(cs)),
      v = c(1,2)
    )

    tree$missing_sql &lt;- xgb_tree_sql(tree$children[[cd$v[cd$k==tree$missing]]], feature_dict)
    tree$yes_sql &lt;- xgb_tree_sql(tree$children[[cd$v[cd$k==tree$yes]]], feature_dict)
    tree$no_sql &lt;- xgb_tree_sql(tree$children[[cd$v[cd$k==tree$no]]], feature_dict)
    
    q &lt;- &quot;
      CASE 
        WHEN {{{split_long}}} IS NULL THEN {{{missing_sql}}}
        WHEN {{{split_long}}} &lt; {{{split_condition}}} THEN {{{yes_sql}}}
        ELSE {{{no_sql}}}
      END
    &quot;

    return(whisker.render(q,tree))    
    
  }
  
}
</code></pre>
<p>When we transform one tree into a sequence of nested CASE statements, we are producing a statement that yields that tree’s contribution to the total score. We now need to sum the output of each tree and then calculate the total probability prediction. In other words, we need to add up a list of nested CASE statements and then logit-transform the result.</p>
<p>Note that below we make use of the R <code>whisker</code> package. This logic-less templating language is a great way to easily transform associative-arrays into SQL that contains easily identifiable labels as placeholders. We find this more readable than sequences of <code>paste</code> statements.</p>
<pre><code>xgb_sql_score_query &lt;- function(list_of_trees, features_table, feature_dict, key_field = &quot;id&quot;){
  
  # a swap list to render queries via whisker
  swap &lt;- list(
    key_field = key_field,
    features_table = features_table
  )
    
  # score_queries contains the score query for each tree in the list_of_trees
  score_queries &lt;- lapply(list_of_trees, function(tree){
    xgb_tree_sql(tree, feature_dict)
  })

  # the query clause to sum the scores from each tree 
  swap$sum_of_scores &lt;- paste(score_queries, collapse=' + ')
        
  # score query that logit-transforms the sum_of_scores 
  q &lt;- &quot;
    SELECT
      {{{key_field}}},
      1/(1+exp(-1*( {{{sum_of_scores}}} ))) AS score
    FROM `{{{features_table}}}`
  &quot;

  return(whisker.render(q,swap))

}

</code></pre>
<p>We are now ready to generate the score query from our model:</p>
<pre><code>queries &lt;- xgb_sql_score_query(
  model trees, 
  'mydataset.my_feature_table',
  feature_dict
)

for(q in queries){
  # example: run the query with the R bigrquery package
  bq_project_query('my_project', q)
}
</code></pre>
<p>In summary, production models typically calculate predictions for <strong>all subjects</strong> on a daily, hourly, or even more frequent basis; however, moving feature data between a database and a local “scoring” machine is expensive and slow. Transferring the scoring calculations to run within the database, as we’ve shown above, can significantly reduce both cost and run time.</p>
<p>The astute reader may notice that, depending on the database, this will only work for a limited number of trees. When that becomes a problem, it is possible to add another layer that stores the summed scores for batches of trees as views or tables, and then aggregates their results. Beyond that, when queries with views become too long, it is possible to add an additional layer than aggregates batches of views into tables. We will save all of this for a future post.</p>
<p>Roland Stevenson is a data scientist and consultant who may be reached on <a rel="nofollow" href="https://www.linkedin.com/in/roland-stevenson/" target="_blank">Linkedin</a></p>
<p> </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://rviews.rstudio.com/2018/11/07/in-database-xgboost-predictions-with-r/"> R Views</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/elQmdgVlPNE" height="1"></a></div>