<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/native-scoring-in-sql-server-2017-using-r/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://tomaztsql.wordpress.com/2018/05/28/native-scoring-in-sql-server-2017-using-r/"> R – TomazTsql</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>Native scoring is a much overlooked feature in SQL Server 2017 (available only under Windows and only on-prem), that provides scoring and predicting in pre-build and stored machine learning models in near real-time.</p>
<p><img data-orig-file="https://tomaztsql.files.wordpress.com/2018/05/stopwatch.png?w=456" data-orig-size="256,256" data-medium-file="https://tomaztsql.files.wordpress.com/2018/05/stopwatch.png?w=456?w=256" data-attachment-id="4972" data-image-meta="{" data-image-description="" src="https://tomaztsql.files.wordpress.com/2018/05/stopwatch.png?w=456" data-permalink="https://tomaztsql.wordpress.com/2018/05/28/native-scoring-in-sql-server-2017-using-r/stopwatch/#main" data-large-file="https://tomaztsql.files.wordpress.com/2018/05/stopwatch.png?w=456?w=256" alt="stopwatch" data-image-title="stopwatch" sizes="(max-width: 256px) 100vw, 256px" data-comments-opened="1" class="wp-image-4972" data-recalc-dims="1"></p>
<h6>                                                                                             Icons made by <a rel="nofollow" href="https://www.flaticon.com/authors/smashicons" title="Smashicons" target="_blank">Smashicons</a> from <a rel="nofollow" href="https://www.flaticon.com/" title="Flaticon" target="_blank">www.flaticon.com</a> is licensed by <a rel="nofollow" href="http://creativecommons.org/licenses/by/3.0/" title="Creative Commons BY 3.0" target="_blank">CC 3.0 BY</a></h6>
<p> </p>
<p>Depending on the definition of real-time, and what does it mean for your line of business, I will not go into the definition of real-time, but for sure, we can say scoring 10.000 rows in a second from a mediocre client computer (similar to mine) .</p>
<p>Native scoring in SQL Server 2017 comes with couple of limitations, but also with a lot of benefits. Limitations are:</p>
<ul>
<li>currently supports only SQL server 2017 and Windows platform</li>
<li>trained model should not exceed 100 MiB in size</li>
<li>Native scoring with PREDICT function supports only following algorithms from RevoScaleR library:
<ul>
<li><span>rxLinMod</span> (linear model as linear regression)</li>
<li><span>rxLogit</span> (logistic regression)</li>
<li><span>rxBTrees</span> (Parallel external memory algorithm for Stochastic Gradient Boosted Decision Trees)</li>
<li><span>rxDtree</span> (External memory algorithm for Classification and Regression Trees</li>
<li><span>rxDForest</span> (External memory algorithm for Classification and Regression Decision Trees)</li>
</ul>
</li>
</ul>
<p>Benefits of using PREDICT function for native scoring are:</p>
<ul>
<li>No configuration of R or ML environment is needed (assuming that the trained models are already stored in the database),</li>
<li>Code is cleaner, more readable, and no additional R code is needed when performing scoring,</li>
<li>No R engine is called in the run-time, so tremendous deduction of  CPU and I/O costs as well as, no external calls,</li>
<li>Client or server running Native scoring with PREDICT function does not need R engine installed, because it uses C++ libraries from Microsoft, that can read serialized model stored in a table and un-serialize it and generate predictions, all without the need of R</li>
</ul>
<p>Overall, if you are looking for a faster predictions in your enterprise and would love to have a faster code and solution deployment, especially integration with other applications or building API in your ecosystem, native scoring with PREDICT function will surely be advantage to you. Although not all of the predictions/scores are supported, majority of predictions can be done using regression models or decision trees models (it is estimated that both type (with derivatives of regression models and ensemble methods) of algorithms are used in 85% of the predictive analytics).</p>
<p>To put the PREDICT function to the test, I have deliberately taken the semi-larger dataset, available in RevoScaleR package in R – AirlineDemoSmall.csv. Using a simple BULK INSERT, we get the data into the database:</p>
<pre>BULK INSERT ArrivalDelay
 FROM 'C:\Program Files\Microsoft SQL Server\140\R_SERVER\library\RevoScaleR\SampleData\AirlineDemoSmall.csv'
 WITH 
 ( FIELDTERMINATOR =',', ROWTERMINATOR = '0x0a', FIRSTROW = 2, CODEPAGE = 'RAW');</pre>
<p>Once data is in the database, I will split the data into training and test sub-sets.</p>
<pre>SELECT TOP 20000 *
INTO ArrDelay_Train
FROM ArrDelay ORDER BY NEWID()
-- (20000 rows affected)

SELECT *
INTO ArrDelay_Test
FROM ArrDelay AS AR
WHERE NOT EXISTS (SELECT * FROM ArrDelay_Train as ATR
                     WHERE
                       ATR.arrDelay = AR.arrDelay
                   AND ATR.[DayOfWeek] = AR.[DayOfWeek]
                   AND ATR.CRSDepTime = AR.CRSDepTime
                 )
-- (473567 rows affected</pre>
<p>And the outlook of the dataset is relatively simple:</p>
<pre>ArrDelay CRSDepTime DayOfWeek
1        9,383332   3
4        18,983334  4
0        13,883333  4
65       21,499998  7
-3       6,416667   1</pre>
<h3>Creating models</h3>
<p>So we will create essentially two same models using rxLinMod function with same formula, but one with additional parameter for real-time scoring set to TRUE.</p>
<pre><strong>-- regular model creation</strong>
DECLARE @model VARBINARY(MAX);
EXECUTE sp_execute_external_script
 @language = N'R'
 ,@script = N'
 arrDelay.LM &lt;- rxLinMod(ArrDelay ~ DayOfWeek + CRSDepTime, 
                         data = InputDataSet)
 model &lt;- rxSerializeModel(arrDelay.LM)'
 ,@input_data_1 = N'SELECT * FROM ArrDelay_Train'
 ,@params = N'@model varbinary(max) OUTPUT'
 ,@model = @model OUTPUT
 INSERT [dbo].arrModels([model_name], [native_model])
 VALUES('arrDelay.LM.V1', @model) ;

<strong>-- Model for Native scoring</strong>
DECLARE @model VARBINARY(MAX);

EXECUTE sp_execute_external_script
 @language = N'R'
 ,@script = N'
 arrDelay.LM &lt;- rxLinMod(ArrDelay ~ DayOfWeek + CRSDepTime, 
                             data = InputDataSet)
 model &lt;- rxSerializeModel(arrDelay.LM, <strong>realtimeScoringOnly = TRUE</strong>)'
 ,@input_data_1 = N'SELECT * FROM ArrDelay_Train'
 ,@params = N'@model varbinary(max) OUTPUT'
 ,@model = @model OUTPUT
 INSERT [dbo].arrModels([model_name], [native_model])
 VALUES('arrDelay.LM.NativeScoring.V1', @model) ;</pre>
<p>Both models will have same training set, and will be stored into a table for future scoring. Upon first inspection, we can see there is a difference in the model size:</p>
<p><img data-orig-file="https://tomaztsql.files.wordpress.com/2018/05/model_size.png?w=456" data-orig-size="642,86" data-medium-file="https://tomaztsql.files.wordpress.com/2018/05/model_size.png?w=456?w=300" data-attachment-id="4971" data-image-meta="{" data-image-description="" src="https://tomaztsql.files.wordpress.com/2018/05/model_size.png?w=456" data-permalink="https://tomaztsql.wordpress.com/2018/05/28/native-scoring-in-sql-server-2017-using-r/model_size/#main" data-large-file="https://tomaztsql.files.wordpress.com/2018/05/model_size.png?w=456?w=642" alt="model_size" data-image-title="model_size" sizes="(max-width: 642px) 100vw, 642px" data-comments-opened="1" class="wp-image-4971" data-recalc-dims="1"></p>
<h3>Scoring Models</h3>
<p>Both models  took relatively the same amount of time to train and to store in the table. Both can also be created on R Machine Learning server and stored in the same way (with or without argument realtimeScoringOnly). The model size gives you an idea, why and how the realtime scoring can be achieved -> is to keep your model as small as possible. Both models will give you exact same predictions scores, just that the native scoring will be much faster. Note also, if you are planning to do any text analysis with real-time scoring, keep in mind the 100 MiB limitation, as the text prediction models often exceed this limitation.</p>
<p>Comparing the execution of scoring models, I will compare using “traditional way” of using external procedure sp_execute_external_script and using <a rel="nofollow" href="https://docs.microsoft.com/en-us/sql/t-sql/queries/predict-transact-sql?view=sql-server-2017" target="_blank">PREDICT</a> function.</p>
<pre>------------------------------------
-- Using sp_execute_external_script
------------------------------------
DECLARE @model VARBINARY(MAX) = (SELECT native_model FROM arrModels 
WHERE model_name = '<strong>arrDelay.LM.V1</strong>')

EXEC sp_execute_external_script
 @language = N'R'
 ,@script = N'
 modelLM &lt;- rxUnserializeModel(model)
 OutputDataSet &lt;- rxPredict( model=modelLM,
                 data = ArrDelay_Test,
                 type = &quot;link&quot;,
                 predVarNames = &quot;ArrDelay_Pred&quot;,
                 extraVarsToWrite = c(&quot;ArrDelay&quot;,&quot;CRSDepTime&quot;,&quot;DayOfWeek&quot;)
 )'
 ,@input_data_1 = N'SELECT * FROM dbo.ArrDelay_Test'
 ,@input_data_1_name = N'ArrDelay_Test'
 ,@params = N'@model VARBINARY(MAX)'
 ,@model = @model
WITH RESULT SETS
((
 AddDelay_Pred FLOAT
,ArrDelay INT 
,CRSDepTime NUMERIC(16,5)
,[DayOfWeek] INT
))
-- (473567 rows affected)
-- Duration 00:00:08

---------------------------
-- Using Real Time Scoring
---------------------------
DECLARE @model varbinary(max) = ( SELECT native_model FROM arrModels 
WHERE model_name = '<strong>arrDelay.LM.NativeScoring.V1</strong>');

SELECT 
 NewData.*
 ,p.*
 FROM PREDICT(MODEL = @model, DATA = dbo.ArrDelay_Test as newData)
 WITH(ArrDelay_Pred FLOAT) as p;
GO
-- (473567 rows affected)
-- Duration 00:00:04</pre>
<p>Both examples are different from each other, but PREDICT function looks much more readable and neater. Time performance is also on the PREDICT function side, as the model returns the predictions much faster.</p>
<p>In addition, I have mentioned that PREDICT function does not need R engine or Launchpad Service to be running in the same environment, where the code will be executed. To put this to test, I will simply stop the SQL Server Launchpad Service:</p>
<p><img data-orig-file="https://tomaztsql.files.wordpress.com/2018/05/service_stop.png?w=456" data-orig-size="1151,154" data-medium-file="https://tomaztsql.files.wordpress.com/2018/05/service_stop.png?w=456?w=300" data-attachment-id="4973" data-image-meta="{" data-image-description="" src="https://tomaztsql.files.wordpress.com/2018/05/service_stop.png?w=456" data-permalink="https://tomaztsql.wordpress.com/2018/05/28/native-scoring-in-sql-server-2017-using-r/service_stop/#main" data-large-file="https://tomaztsql.files.wordpress.com/2018/05/service_stop.png?w=456?w=700" alt="Service_stop" data-image-title="Service_stop" sizes="(max-width: 700px) 100vw, 700px" data-comments-opened="1" class="wp-image-4973" data-recalc-dims="1"></p>
<p>After executing the first set of predictions using sp_execute_external_script, SQL Server or Machine Learning Server will notify you that the service is not running:</p>
<p><img data-orig-file="https://tomaztsql.files.wordpress.com/2018/05/fail_to_communicate.png?w=456" data-orig-size="747,113" data-medium-file="https://tomaztsql.files.wordpress.com/2018/05/fail_to_communicate.png?w=456?w=300" data-attachment-id="4975" data-image-meta="{" data-image-description="" src="https://tomaztsql.files.wordpress.com/2018/05/fail_to_communicate.png?w=456" data-permalink="https://tomaztsql.wordpress.com/2018/05/28/native-scoring-in-sql-server-2017-using-r/fail_to_communicate/#main" data-large-file="https://tomaztsql.files.wordpress.com/2018/05/fail_to_communicate.png?w=456?w=700" alt="fail_to_communicate" data-image-title="fail_to_communicate" sizes="(max-width: 700px) 100vw, 700px" data-comments-opened="1" class="wp-image-4975" data-recalc-dims="1"></p>
<p>whereas, the PREDICT function will work flawlessly.</p>
<h3>Verdict</h3>
<p>For sure, faster predictions are the something that can be very welcoming in gaming industry, in transport, utility and metal industry, financial as well as any other types, where real-time predictions against OLTP systems will be much appreciated. With the light-weight models and good algorithm support, I would for sure give it an additional thought, especially, if you see a good potential in faster and near real-time predictions.</p>
<p>As always, complete code and data sample are available at <a rel="nofollow" href="https://github.com/tomaztk/NativeScoring" target="_blank">Github</a>. Happy coding! <img alt="🙂" src="https://i0.wp.com/s0.wp.com/wp-content/mu-plugins/wpcom-smileys/twemoji/2/72x72/1f642.png?w=456&ssl=1" class="wp-smiley" data-recalc-dims="1"></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://tomaztsql.wordpress.com/2018/05/28/native-scoring-in-sql-server-2017-using-r/"> R – TomazTsql</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 alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/NOAxmDmfXiQ" height="1"></a></div>