<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="http://www.r-bloggers.com/bike-rental-demand-estimation-with-microsoft-r-server/"></div></div><div><a data-url="http://www.r-bloggers.com/bike-rental-demand-estimation-with-microsoft-r-server/" data-counturl="http://www.r-bloggers.com/bike-rental-demand-estimation-with-microsoft-r-server/" data-count="horizontal" data-text="Bike Rental Demand Estimation with Microsoft R Server" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://blog.revolutionanalytics.com/2016/05/bike-rental-demand.html"> Revolutions</a></strong>, and kindly contributed to <a rel="nofollow" href="http://www.r-bloggers.com/">R-bloggers)</a> </div>
<div>
<p><em>by Katherine Zhao, Hong Lu, Zhongmou Li, Data Scientists at Microsoft</em></p>
<p>Bicycle rental has become popular as a convenient and environmentally friendly transportation option. Accurate estimation of bike demand at different locations and different times would help bicycle-sharing systems better meet rental demand and allocate bikes to locations.</p>
<p>In this blog post, we walk through how to use <a target="_blank" href="https://www.microsoft.com/en-us/server-cloud/products/r-server/">Microsoft R Server</a> (MRS) to build a regression model to predict bike rental demand. In the example below, we demonstrate an end-to-end machine learning solution development process in MRS, including data importing, data cleaning, feature engineering, parameter sweeping, and model training and evaluation.</p>
<h2>Data</h2>
<p>The <a target="_blank" href="https://archive.ics.uci.edu/ml/datasets/Bike+Sharing+Dataset">Bike Rental UCI dataset</a> is used as the input raw data for this sample. This dataset is based on real-world data from the Capital Bikeshare company, which operates a bike rental network in Washington DC in the United States.</p>
<p>The dataset contains 17,379 rows and 17 columns, with each row representing the number of bike rentals within a specific hour of a day in the years 2011 or 2012. Weather conditions (such as temperature, humidity, and wind speed) are included in the raw data, and the dates are categorized as holiday vs. weekday, etc.</p>
<p>The field to predict is <strong><em>cnt</em></strong>, which contains a count value ranging from 1 to 977, representing the number of bike rentals within a specific hour.</p>
<h2>Model Overview</h2>
<p>In this example, we use historical bike rental counts as well as the weather condition data to predict the number of bike rentals within a specific hour in the future. We approach this problem as a regression problem, since the label column (number of rentals) contains continuous real numbers.</p>
<p>Along this line, we split the raw data into two parts: data records in year 2011 to learn the regression model, and data records in year 2012 to score and evaluate the model. Specifically, we employ the Decision Forest Regression algorithm as the regression model and build two models on different feature sets. Finally, we evaluate their prediction performance. We will elaborate the details in the following sections.</p>
<h2>Microsoft R Server</h2>
<p>We build the models using the <code>RevoScaleR</code> library in MRS. The <code>RevoScaleR</code> library provides extremely fast statistical analysis on terabyte-class datasets without needing specialized hardware. <code>RevoScaleR</code>'s distributed computing capabilities can use a different (possibly remote) computing context using the same <code>RevoScaleR</code> commands to manage and analyze local data. A wide range of <code>rx</code> prefixed functions provide functionality for:</p>
<ul>
<li>Accessing external data sets (SAS, SPSS, ODBC, Teradata, and delimited and fixed format text) for analysis in R.</li>
<li>Efficiently storing and retrieving data in a high-performance data file.</li>
<li>Cleaning, exploring, and manipulating data.</li>
<li>Fast, basic statistical analysis.</li>
<li>Train and score advanced machine learning models.</li>
</ul>
<h2>Running the Experiment</h2>
<p>Overall, there are five major steps of building this example using Microsoft R Server:</p>
<ul>
<li><a target="_blank" href="http://blog.revolutionanalytics.com/2016/05/bike-rental-demand.html#step-1">Step 1: Import and Clean Data</a></li>
<li><a target="_blank" href="http://blog.revolutionanalytics.com/2016/05/bike-rental-demand.html#step-2">Step 2: Perform Feature Engineering</a></li>
<li><a target="_blank" href="http://blog.revolutionanalytics.com/2016/05/bike-rental-demand.html#step-3">Step 3: Prepare Training, Test and Score Datasets</a></li>
<li><a target="_blank" href="http://blog.revolutionanalytics.com/2016/05/bike-rental-demand.html#step-4">Step 4: Sweep Parameters and Train Regression Models</a></li>
<li><a target="_blank" href="http://blog.revolutionanalytics.com/2016/05/bike-rental-demand.html#step-5">Step 5: Test, Evaluate, and Compare Models</a></li>
</ul>
<h3><a name="step-1"></a>Step 1: Import and Clean Data</h3>
<p>First, we import the Bike Rental UCI dataset. Since there are a small portion of missing records within the dataset, we use <code>rxDataStep()</code> to replace the missing records with the latest non-missing observations. <code>rxDataStep()</code> is a commonly used function for data manipulation. It transforms the input dataset chunk by chunk and saves the results to the output dataset.</p>
<div>
<div>
<pre><span># Define the tranformation function for the rxDataStep.</span>
xform &lt;- <a target="_blank" href="http://inside-r.org/r-doc/base/function"><span>function</span></a><span>(</span>dataList<span>)</span> <span>{</span>
  <span># Identify the features with missing values.</span>
  featureNames &lt;- <a target="_blank" href="http://inside-r.org/r-doc/base/c"><span>c</span></a><span>(</span><span>&quot;weathersit&quot;</span><span>,</span> <span>&quot;temp&quot;</span><span>,</span> <span>&quot;atemp&quot;</span><span>,</span> <span>&quot;hum&quot;</span><span>,</span> <span>&quot;windspeed&quot;</span><span>,</span> <span>&quot;cnt&quot;</span><span>)</span>
  <span># Use &quot;na.locf&quot; function to carry forward last observation.</span>
  dataList<span>[</span>featureNames<span>]</span> &lt;- <a target="_blank" href="http://inside-r.org/r-doc/base/lapply"><span>lapply</span></a><span>(</span>dataList<span>[</span>featureNames<span>]</span><span>,</span> <a target="_blank" href="http://inside-r.org/packages/cran/zoo">zoo</a>::na.locf<span>)</span>
  <span># Return the data list.</span>
  <a target="_blank" href="http://inside-r.org/r-doc/base/return"><span>return</span></a><span>(</span>dataList<span>)</span>
<span>}</span>
 
<span># Use rxDataStep to replace missings with the latest non-missing observations.</span>
cleanXdf &lt;- rxDataStep<span>(</span>inData = mergeXdf<span>,</span> outFile = outFileClean<span>,</span> overwrite = <span>TRUE</span><span>,</span>
                       <span># Apply the &quot;last observation carried forward&quot; operation.</span>
                       transformFunc = xform<span>,</span>  
                       <span># Identify the features to apply the tranformation.</span>
                       transformVars = <a target="_blank" href="http://inside-r.org/r-doc/base/c"><span>c</span></a><span>(</span><span>&quot;weathersit&quot;</span><span>,</span> <span>&quot;temp&quot;</span><span>,</span> <span>&quot;atemp&quot;</span><span>,</span> <span>&quot;hum&quot;</span><span>,</span> <span>&quot;windspeed&quot;</span><span>,</span> <span>&quot;cnt&quot;</span><span>)</span><span>,</span>
                       <span># Drop the &quot;dteday&quot; feature.</span>
                       varsToDrop = <span>&quot;dteday&quot;</span><span>)</span>
Step <span>2</span>: Perform <a target="_blank" href="http://inside-r.org/packages/cran/feature">Feature</a> Engineering</pre>
</div>
</div>
<h3><a name="step-2"></a>Step 2: Perform Feature Engineering</h3>
<p>In addition to the original features in the raw data, we add number of bikes rented in each of the previous 12 hours as features to provide better predictive power. We create a <code>computeLagFeatures()</code> helper function to compute the 12 lag features and use it as the transformation function in <code>rxDataStep()</code>.</p>
<p>Note that <code>rxDataStep()</code> processes data chunk by chunk and lag feature computation requires data from previous rows. In <code>computLagFeatures()</code>, we use the internal function <code>.rxSet()</code> to save the last <em>n</em> rows of a chunk to a variable <strong><em>lagData</em></strong>. When processing the next chunk, we use another internal function <code>.rxGet()</code> to retrieve the values stored in <strong><em>lagData</em></strong> and compute the lag features.</p>
<div>
<div>
<pre><span># Add number of bikes that were rented in each of</span>
<span># the previous 12 hours as 12 lag features.</span>
computeLagFeatures &lt;- <a target="_blank" href="http://inside-r.org/r-doc/base/function"><span>function</span></a><span>(</span>dataList<span>)</span> <span>{</span>
  <span># Total number of lags that need to be added.</span>
  numLags &lt;- <a target="_blank" href="http://inside-r.org/r-doc/base/length"><span>length</span></a><span>(</span>nLagsVector<span>)</span>
  <span># Lag feature names as lagN.</span>
  varLagNameVector &lt;- <a target="_blank" href="http://inside-r.org/r-doc/base/paste"><span>paste</span></a><span>(</span><span>&quot;cnt_&quot;</span><span>,</span> nLagsVector<span>,</span> <span>&quot;hour&quot;</span><span>,</span> sep=<span>&quot;&quot;</span><span>)</span>
 
  <span># Set the value of an object &quot;storeLagData&quot; in the transform environment.</span>
  <span>if</span> <span>(</span>!<a target="_blank" href="http://inside-r.org/r-doc/base/exists"><span>exists</span></a><span>(</span><span>&quot;storeLagData&quot;</span><span>)</span><span>)</span>
  <span>{</span>
    lagData &lt;- <a target="_blank" href="http://inside-r.org/r-doc/base/mapply"><span>mapply</span></a><span>(</span><a target="_blank" href="http://inside-r.org/r-doc/base/rep"><span>rep</span></a><span>,</span> dataList<span>[</span><span>[</span>varName<span>]</span><span>]</span><span>[</span><span>1</span><span>]</span><span>,</span> times = nLagsVector<span>)</span>
    <a target="_blank" href="http://inside-r.org/r-doc/base/names"><span>names</span></a><span>(</span>lagData<span>)</span> &lt;- varLagNameVector
    .rxSet<span>(</span><span>&quot;storeLagData&quot;</span><span>,</span> lagData<span>)</span>
  <span>}</span>
 
  <span>if</span> <span>(</span>!.rxIsTestChunk<span>)</span>
  <span>{</span>
    <span>for</span> <span>(</span>iL <span>in</span> <span>1</span>:numLags<span>)</span>
    <span>{</span>
      <span># Number of rows in the current chunk.</span>
      numRowsInChunk &lt;- <a target="_blank" href="http://inside-r.org/r-doc/base/length"><span>length</span></a><span>(</span>dataList<span>[</span><span>[</span>varName<span>]</span><span>]</span><span>)</span>
      nlags &lt;- nLagsVector<span>[</span>iL<span>]</span>
      varLagName &lt;- <a target="_blank" href="http://inside-r.org/r-doc/base/paste"><span>paste</span></a><span>(</span><span>&quot;cnt_&quot;</span><span>,</span> nlags<span>,</span> <span>&quot;hour&quot;</span><span>,</span> sep = <span>&quot;&quot;</span><span>)</span>
      <span># Retrieve lag data from the previous chunk.</span>
      lagData &lt;- .rxGet<span>(</span><span>&quot;storeLagData&quot;</span><span>)</span>
      <span># Concatenate lagData and the &quot;cnt&quot; feature.</span>
      allData &lt;- <a target="_blank" href="http://inside-r.org/r-doc/base/c"><span>c</span></a><span>(</span>lagData<span>[</span><span>[</span>varLagName<span>]</span><span>]</span><span>,</span> dataList<span>[</span><span>[</span>varName<span>]</span><span>]</span><span>)</span>
      <span># Take the first N rows of allData, where N is</span>
      <span># the total number of rows in the original dataList.</span>
      dataList<span>[</span><span>[</span>varLagName<span>]</span><span>]</span> &lt;- allData<span>[</span><span>1</span>:numRowsInChunk<span>]</span>
      <span># Save last nlag rows as the new lagData to be used</span>
      <span># to process in the next chunk.</span>
      lagData<span>[</span><span>[</span>varLagName<span>]</span><span>]</span> &lt;- <a target="_blank" href="http://inside-r.org/r-doc/utils/tail"><span>tail</span></a><span>(</span>allData<span>,</span> nlags<span>)</span>
      .rxSet<span>(</span><span>&quot;storeLagData&quot;</span><span>,</span> lagData<span>)</span>
    <span>}</span>
  <span>}</span>
  <a target="_blank" href="http://inside-r.org/r-doc/base/return"><span>return</span></a><span>(</span>dataList<span>)</span>
<span>}</span>
 
<span># Apply the &quot;computeLagFeatures&quot; on the bike data.</span>
lagXdf &lt;- rxDataStep<span>(</span>inData = cleanXdf<span>,</span> outFile = outFileLag<span>,</span>
                     transformFunc = computeLagFeatures<span>,</span>
                     transformObjects = <a target="_blank" href="http://inside-r.org/r-doc/base/list"><span>list</span></a><span>(</span>varName = <span>&quot;cnt&quot;</span><span>,</span>
                                             nLagsVector = <a target="_blank" href="http://inside-r.org/r-doc/base/seq"><span>seq</span></a><span>(</span><span>12</span><span>)</span><span>)</span><span>,</span>
                     transformVars = <span>&quot;cnt&quot;</span><span>,</span> overwrite = <span>TRUE</span><span>)</span></pre>
</div>
</div>
<h3><a name="step-3"></a>Step 3: Prepare Training, Test and Score Datasets</h3>
<p>Before training the regression model, we split data into two parts: data records in year 2011 to learn the regression model, and data records in year 2012 to score and evaluate the model. In order to obtain the best combination of parameters for regression models, we further divide year 2011 data into training and test datasets: 80% of the records are randomly selected to train regression models with various combinations of parameters, and the remaining 20% are used to evaluate the models obtained and determine the optimal combination.</p>
<div>
<div>
<pre><span># Split data by &quot;yr&quot; so that the training and test data contains records</span>
<span># for the year 2011 and the score data contains records for 2012.</span>
rxSplit<span>(</span>inData = lagXdf<span>,</span>
        outFilesBase = paste0<span>(</span>td<span>,</span> <span>&quot;/modelData&quot;</span><span>)</span><span>,</span>
        splitByFactor = <span>&quot;yr&quot;</span><span>,</span>
        overwrite = <span>TRUE</span><span>,</span>
        reportProgress = <span>0</span><span>,</span>
        verbose = <span>0</span><span>)</span>
 
<span># Point to the .xdf files for the training &amp; test and score set.</span>
trainTest &lt;- RxXdfData<span>(</span>paste0<span>(</span>td<span>,</span> <span>&quot;/modelData.yr.0.xdf&quot;</span><span>)</span><span>)</span>
score &lt;- RxXdfData<span>(</span>paste0<span>(</span>td<span>,</span> <span>&quot;/modelData.yr.1.xdf&quot;</span><span>)</span><span>)</span>
 
<span># Randomly split records for the year 2011 into training and test sets</span>
<span># for sweeping parameters.</span>
<span># 80% of data as training and 20% as test.</span>
rxSplit<span>(</span>inData = trainTest<span>,</span>
        outFilesBase = paste0<span>(</span>td<span>,</span> <span>&quot;/sweepData&quot;</span><span>)</span><span>,</span>
        outFileSuffixes = <a target="_blank" href="http://inside-r.org/r-doc/base/c"><span>c</span></a><span>(</span><span>&quot;Train&quot;</span><span>,</span> <span>&quot;Test&quot;</span><span>)</span><span>,</span>
        splitByFactor = <span>&quot;splitVar&quot;</span><span>,</span>
        overwrite = <span>TRUE</span><span>,</span>
        transforms = <a target="_blank" href="http://inside-r.org/r-doc/base/list"><span>list</span></a><span>(</span>splitVar = <a target="_blank" href="http://inside-r.org/r-doc/base/factor"><span>factor</span></a><span>(</span><a target="_blank" href="http://inside-r.org/r-doc/base/sample"><span>sample</span></a><span>(</span><a target="_blank" href="http://inside-r.org/r-doc/base/c"><span>c</span></a><span>(</span><span>&quot;Train&quot;</span><span>,</span> <span>&quot;Test&quot;</span><span>)</span><span>,</span>
                                                   size = .rxNumRows<span>,</span>
                                                   <a target="_blank" href="http://inside-r.org/r-doc/base/replace"><span>replace</span></a> = <span>TRUE</span><span>,</span>
                                                   <a target="_blank" href="http://inside-r.org/packages/cran/prob">prob</a> = <a target="_blank" href="http://inside-r.org/r-doc/base/c"><span>c</span></a><span>(</span><span>.80</span><span>,</span> <span>.20</span><span>)</span><span>)</span><span>,</span>
                                            <a target="_blank" href="http://inside-r.org/r-doc/base/levels"><span>levels</span></a> = <a target="_blank" href="http://inside-r.org/r-doc/base/c"><span>c</span></a><span>(</span><span>&quot;Train&quot;</span><span>,</span> <span>&quot;Test&quot;</span><span>)</span><span>)</span><span>)</span><span>,</span>
        rngSeed = <span>17</span><span>,</span>
        consoleOutput = <span>TRUE</span><span>)</span>
 
<span># Point to the .xdf files for the training and test set.</span>
train &lt;- RxXdfData<span>(</span>paste0<span>(</span>td<span>,</span> <span>&quot;/sweepData.splitVar.Train.xdf&quot;</span><span>)</span><span>)</span>
test &lt;- RxXdfData<span>(</span>paste0<span>(</span>td<span>,</span> <span>&quot;/sweepData.splitVar.Test.xdf&quot;</span><span>)</span><span>)</span></pre>
</div>
</div>
<div> </div>
<h3><a name="step-4"></a>Step 4: Sweep Parameters and Train Regression Models</h3>
<p>In this step, we construct two training datasets based on the same raw input data, but with different sets of features:</p>
<ul>
<li>Set A = weather + holiday + weekday + weekend features for the predicted day</li>
<li>Set B = Set A + number of bikes rented in each of the previous 12 hours, which captures very recent demand for the bikes</li>
</ul>
<p>In order to perform parameter sweeping, we create a helper function to evaluate the performance of a model trained with a given combination of number of trees and maximum depth. We use <em>Root Mean Squared Error (RMSE)</em> as the evaluation metric.</p>
<div>
<div>
<pre><span># Define a function to train and test models with given parameters</span>
<span># and then return Root Mean Squared Error (RMSE) as the performance metric.</span>
TrainTestDForestfunction &lt;- <a target="_blank" href="http://inside-r.org/r-doc/base/function"><span>function</span></a><span>(</span>trainData<span>,</span> testData<span>,</span> form<span>,</span> numTrees<span>,</span> maxD<span>)</span>
<span>{</span>
  <span># Build decision forest regression models with given parameters.</span>
  dForest &lt;- rxDForest<span>(</span>form<span>,</span> <a target="_blank" href="http://inside-r.org/r-doc/utils/data"><span>data</span></a> = trainData<span>,</span>
                       method = <span>&quot;anova&quot;</span><span>,</span>
                       maxDepth = maxD<span>,</span>
                       nTree = numTrees<span>,</span>
                       seed = <span>123</span><span>)</span>
  <span># Predict the the number of bike rental on the test data.</span>
  rxPredict<span>(</span>dForest<span>,</span> <a target="_blank" href="http://inside-r.org/r-doc/utils/data"><span>data</span></a> = testData<span>,</span>
            predVarNames = <span>&quot;cnt_Pred&quot;</span><span>,</span>
            residVarNames = <span>&quot;cnt_Resid&quot;</span><span>,</span>
            overwrite = <span>TRUE</span><span>,</span>
            computeResiduals = <span>TRUE</span><span>)</span>
  <span># Calcualte the RMSE.</span>
  result &lt;- rxSummary<span>(</span>~ cnt_Resid<span>,</span>
                      <a target="_blank" href="http://inside-r.org/r-doc/utils/data"><span>data</span></a> = testData<span>,</span>
                      summaryStats = <span>&quot;Mean&quot;</span><span>,</span>
                      transforms = <a target="_blank" href="http://inside-r.org/r-doc/base/list"><span>list</span></a><span>(</span>cnt_Resid = cnt_Resid^<span>2</span><span>)</span>
  <span>)</span>$sDataFrame
  <span># Return lists of number of trees, maximum depth and RMSE.</span>
  <a target="_blank" href="http://inside-r.org/r-doc/base/return"><span>return</span></a><span>(</span><a target="_blank" href="http://inside-r.org/r-doc/base/c"><span>c</span></a><span>(</span>numTrees<span>,</span> maxD<span>,</span> <a target="_blank" href="http://inside-r.org/r-doc/base/sqrt"><span>sqrt</span></a><span>(</span>result<span>[</span><span>1</span><span>,</span><span>2</span><span>]</span><span>)</span><span>)</span><span>)</span>
<span>}</span></pre>
</div>
</div>
<p>The following is another helper function to sweep and select the optimal parameter combination. Under local parallel compute context (<code>rxSetComputeContext(RxLocalParallel())</code>), <code>rxExec()</code> executes multiple runs of model training and evaluation with different parameters in parallel, which significantly speeds up parameter sweeping. When used in a compute context with multiple nodes, e.g. high-performance computing clusters and Hadoop, <code>rxExec()</code> can be used to distribute a large number of tasks to the nodes and run the tasks in parallel.</p>
<div>
<div>
<pre><span># Define a function to sweep and select the optimal parameter combination.</span>
findOptimal &lt;- <a target="_blank" href="http://inside-r.org/r-doc/base/function"><span>function</span></a><span>(</span>DFfunction<span>,</span> train<span>,</span> test<span>,</span> form<span>,</span> nTreeArg<span>,</span> maxDepthArg<span>)</span> <span>{</span>
  <span># Sweep different combination of parameters.</span>
  sweepResults &lt;- rxExec<span>(</span>DFfunction<span>,</span> train<span>,</span> test<span>,</span> form<span>,</span> rxElemArg<span>(</span>nTreeArg<span>)</span><span>,</span> rxElemArg<span>(</span>maxDepthArg<span>)</span><span>)</span>
  <span># Sort the nested list by the third element (RMSE) in the list in ascending order.</span>
  sortResults &lt;- sweepResults<span>[</span><a target="_blank" href="http://inside-r.org/r-doc/base/order"><span>order</span></a><span>(</span><a target="_blank" href="http://inside-r.org/r-doc/base/unlist"><span>unlist</span></a><span>(</span><a target="_blank" href="http://inside-r.org/r-doc/base/lapply"><span>lapply</span></a><span>(</span>sweepResults<span>,</span> <span>`[[`</span><span>,</span> <span>3</span><span>)</span><span>)</span><span>)</span><span>]</span>
  <span># Select the optimal parameter combination.</span>
  nTreeOptimal &lt;- sortResults<span>[</span><span>[</span><span>1</span><span>]</span><span>]</span><span>[</span><span>1</span><span>]</span>
  maxDepthOptimal &lt;- sortResults<span>[</span><span>[</span><span>1</span><span>]</span><span>]</span><span>[</span><span>2</span><span>]</span>
  <span># Return the optimal values.</span>
  <a target="_blank" href="http://inside-r.org/r-doc/base/return"><span>return</span></a><span>(</span><a target="_blank" href="http://inside-r.org/r-doc/base/c"><span>c</span></a><span>(</span>nTreeOptimal<span>,</span> maxDepthOptimal<span>)</span><span>)</span>
<span>}</span></pre>
</div>
</div>
<p>A large number of parameter combinations are usually swept through in modeling process. For demonstration purpose, we use 9 combinations of parameters in this example.</p>
<div>
<div>
<pre><span># Define a list of parameters to sweep through.</span>
<span># To save time, we only sweep 9 combinations of number of trees and max tree depth.</span>
numTreesToSweep &lt;- <a target="_blank" href="http://inside-r.org/r-doc/base/rep"><span>rep</span></a><span>(</span><a target="_blank" href="http://inside-r.org/r-doc/base/seq"><span>seq</span></a><span>(</span><span>20</span><span>,</span> <span>60</span><span>,</span> <span>20</span><span>)</span><span>,</span> times = <span>3</span><span>)</span>
maxDepthToSweep &lt;- <a target="_blank" href="http://inside-r.org/r-doc/base/rep"><span>rep</span></a><span>(</span><a target="_blank" href="http://inside-r.org/r-doc/base/seq"><span>seq</span></a><span>(</span><span>10</span><span>,</span> <span>30</span><span>,</span> <span>10</span><span>)</span><span>,</span> each = <span>3</span><span>)</span></pre>
</div>
</div>
<p>Next, we find the best parameter combination and get the optimal regression model for each training dataset. For simplicity, we only present the process for Set A.</p>
<div>
<div>
<pre><span># Set A = weather + holiday + weekday + weekend features for the predicted day.</span>
<span># Build a formula for the regression model and remove the &quot;yr&quot;,</span>
<span># which is used to split the training and test data.</span>
newHourFeatures &lt;- <a target="_blank" href="http://inside-r.org/r-doc/base/paste"><span>paste</span></a><span>(</span><span>&quot;cnt_&quot;</span><span>,</span> <a target="_blank" href="http://inside-r.org/r-doc/base/seq"><span>seq</span></a><span>(</span><span>12</span><span>)</span><span>,</span> <span>&quot;hour&quot;</span><span>,</span> sep = <span>&quot;&quot;</span><span>)</span>  <span># Define the hourly lags.</span>
formA &lt;- <a target="_blank" href="http://inside-r.org/r-doc/stats/formula"><span>formula</span></a><span>(</span>train<span>,</span> depVars = <span>&quot;cnt&quot;</span><span>,</span> varsToDrop = <a target="_blank" href="http://inside-r.org/r-doc/base/c"><span>c</span></a><span>(</span><span>&quot;splitVar&quot;</span><span>,</span> newHourFeatures<span>)</span><span>)</span>
 
<span># Find the optimal parameters for Set A.</span>
optimalResultsA &lt;- findOptimal<span>(</span>TrainTestDForestfunction<span>,</span>
                               train<span>,</span> test<span>,</span> formA<span>,</span>
                               numTreesToSweep<span>,</span>
                               maxDepthToSweep<span>)</span>
 
<span># Use the optimal parameters to fit a model for feature Set A.</span>
nTreeOptimalA &lt;- optimalResultsA<span>[</span><span>[</span><span>1</span><span>]</span><span>]</span>
maxDepthOptimalA &lt;- optimalResultsA<span>[</span><span>[</span><span>2</span><span>]</span><span>]</span>
dForestA &lt;- rxDForest<span>(</span>formA<span>,</span> <a target="_blank" href="http://inside-r.org/r-doc/utils/data"><span>data</span></a> = trainTest<span>,</span>
                      method = <span>&quot;anova&quot;</span><span>,</span>
                      maxDepth = maxDepthOptimalA<span>,</span>
                      nTree = nTreeOptimalA<span>,</span>
                      importance = <span>TRUE</span><span>,</span> seed = <span>123</span><span>)</span></pre>
</div>
</div>
<p> </p>
<p>Finally, we plot the dot charts of the variable importance and the out-of-bag error rates for the two optimal decision forest models.</p>
<p><a target="_blank" href="http://revolution-computing.typepad.com/.a/6a010534b1db25970b01b7c85726f0970b-pi"><img title="1" alt="1" src="http://revolution-computing.typepad.com/.a/6a010534b1db25970b01b7c85726f0970b-800wi" border="0"></a></p>
<p><a target="_blank" href="http://revolution-computing.typepad.com/.a/6a010534b1db25970b01b7c85726fe970b-pi"><img title="2" alt="2" src="http://revolution-computing.typepad.com/.a/6a010534b1db25970b01b7c85726fe970b-800wi" border="0"></a></p>
<h3><a name="step-5"></a>Step 5: Test, Evaluate, and Compare Models</h3>
<p>In this step, we use the <code>rxPredict()</code> function to predict the bike rental demand on the score dataset, and compare the two regression models over three performance metrics – <em>Mean Absolute Error (MAE)</em>, <em>Root Mean Squared Error (RMSE)</em>, and <em>Relative Absolute Error (RAE)</em>.</p>
<div>
<div>
<pre><span># Set A: Predict the probability on the test dataset.</span>
rxPredict<span>(</span>dForestA<span>,</span> <a target="_blank" href="http://inside-r.org/r-doc/utils/data"><span>data</span></a> = score<span>,</span>
          predVarNames = <span>&quot;cnt_Pred_A&quot;</span><span>,</span>
          residVarNames = <span>&quot;cnt_Resid_A&quot;</span><span>,</span>
          overwrite = <span>TRUE</span><span>,</span> computeResiduals = <span>TRUE</span><span>)</span>
 
<span># Set B: Predict the probability on the test dataset.</span>
rxPredict<span>(</span>dForestB<span>,</span> <a target="_blank" href="http://inside-r.org/r-doc/utils/data"><span>data</span></a> = score<span>,</span>
          predVarNames = <span>&quot;cnt_Pred_B&quot;</span><span>,</span>
          residVarNames = <span>&quot;cnt_Resid_B&quot;</span><span>,</span>
          overwrite = <span>TRUE</span><span>,</span> computeResiduals = <span>TRUE</span><span>)</span>
 
<span># Calculate three statistical metrics:</span>
<span># Mean Absolute Error (MAE),</span>
<span># Root Mean Squared Error (RMSE), and</span>
<span># Relative Absolute Error (RAE).</span>
sumResults &lt;- rxSummary<span>(</span>~ cnt_Resid_A_abs + cnt_Resid_A_2 + cnt_rel_A +
                   cnt_Resid_B_abs + cnt_Resid_B_2 + cnt_rel_B<span>,</span>
                 <a target="_blank" href="http://inside-r.org/r-doc/utils/data"><span>data</span></a> = score<span>,</span>
                 summaryStats = <span>&quot;Mean&quot;</span><span>,</span>
                 transforms = <a target="_blank" href="http://inside-r.org/r-doc/base/list"><span>list</span></a><span>(</span>cnt_Resid_A_abs = <a target="_blank" href="http://inside-r.org/r-doc/base/abs"><span>abs</span></a><span>(</span>cnt_Resid_A<span>)</span><span>,</span>
                                   cnt_Resid_A_2 = cnt_Resid_A^<span>2</span><span>,</span>
                                   cnt_rel_A = <a target="_blank" href="http://inside-r.org/r-doc/base/abs"><span>abs</span></a><span>(</span>cnt_Resid_A<span>)</span>/cnt<span>,</span>
                                   cnt_Resid_B_abs = <a target="_blank" href="http://inside-r.org/r-doc/base/abs"><span>abs</span></a><span>(</span>cnt_Resid_B<span>)</span><span>,</span>
                                   cnt_Resid_B_2 = cnt_Resid_B^<span>2</span><span>,</span>
                                   cnt_rel_B = <a target="_blank" href="http://inside-r.org/r-doc/base/abs"><span>abs</span></a><span>(</span>cnt_Resid_B<span>)</span>/cnt<span>)</span>
<span>)</span>$sDataFrame
 
<span># Add row names.</span>
features &lt;- <a target="_blank" href="http://inside-r.org/r-doc/base/c"><span>c</span></a><span>(</span><span>&quot;baseline: weather + holiday + weekday + weekend features for the predicted day&quot;</span><span>,</span>
              <span>&quot;baseline + previous 12 hours demand&quot;</span><span>)</span>
 
<span># List all metrics in a data frame.</span>
metrics &lt;- <a target="_blank" href="http://inside-r.org/r-doc/base/data.frame"><span>data.frame</span></a><span>(</span>Features = features<span>,</span>
                       MAE = <a target="_blank" href="http://inside-r.org/r-doc/base/c"><span>c</span></a><span>(</span>sumResults<span>[</span><span>1</span><span>,</span> <span>2</span><span>]</span><span>,</span> sumResults<span>[</span><span>4</span><span>,</span> <span>2</span><span>]</span><span>)</span><span>,</span>
                       RMSE = <a target="_blank" href="http://inside-r.org/r-doc/base/c"><span>c</span></a><span>(</span><a target="_blank" href="http://inside-r.org/r-doc/base/sqrt"><span>sqrt</span></a><span>(</span>sumResults<span>[</span><span>2</span><span>,</span> <span>2</span><span>]</span><span>)</span><span>,</span> <a target="_blank" href="http://inside-r.org/r-doc/base/sqrt"><span>sqrt</span></a><span>(</span>sumResults<span>[</span><span>5</span><span>,</span> <span>2</span><span>]</span><span>)</span><span>)</span><span>,</span>
                       RAE = <a target="_blank" href="http://inside-r.org/r-doc/base/c"><span>c</span></a><span>(</span>sumResults<span>[</span><span>3</span><span>,</span> <span>2</span><span>]</span><span>,</span> sumResults<span>[</span><span>6</span><span>,</span> <span>2</span><span>]</span><span>)</span><span>)</span></pre>
</div>
</div>
<div> </div>
<p>Based on all three metrics listed below, the regression model built on feature set B outperforms the one built on feature set A. This result is not surprising, since from the variable importance chart we can see, the lag features play a critical part in the regression model. Adding this set of features can lead to better performance.</p>
<table>
<thead>
<tr>
<th>Feature Set</th>
<th>MAE</th>
<th>RMSE</th>
<th>RAE</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>101.34848</td>
<td>146.9973</td>
<td>0.9454142</td>
</tr>
<tr>
<td>B</td>
<td>62.48245</td>
<td>105.6198</td>
<td>0.3737669</td>
</tr>
</tbody>
</table>
<p>Follow this link for source code and datasets: <a target="_blank" href="https://github.com/mezmicrosoft/Microsoft_R_Server/tree/master/Bike_Rental_Estimation">Bike Rental Demand Estimation with Microsoft R Server</a></p>
</div>
<p><div><div><div><div data-width="55" data-show-faces="false" data-send="true" data-layout="box_count" data-height="62" data-href="http://www.r-bloggers.com/bike-rental-demand-estimation-with-microsoft-r-server/"></div></div><div><a data-url="http://www.r-bloggers.com/bike-rental-demand-estimation-with-microsoft-r-server/" data-counturl="http://www.r-bloggers.com/bike-rental-demand-estimation-with-microsoft-r-server/" data-count="vertical" data-text="Bike Rental Demand Estimation with Microsoft R Server" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://blog.revolutionanalytics.com/2016/05/bike-rental-demand.html"> Revolutions</a></strong>.</div>
<hr>
<a rel="nofollow" href="http://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="http://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="http://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="http://www.r-bloggers.com/?s=tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="http://www.r-bloggers.com/?s=data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="http://www.r-bloggers.com/?s=Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="http://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="http://www.r-bloggers.com/?s=ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="http://www.r-bloggers.com/?s=boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="http://www.r-bloggers.com/?s=map">maps</a>, <a title="Animation in R" rel="nofollow" href="http://www.r-bloggers.com/?s=animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="http://www.r-bloggers.com/?s=RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="http://www.r-bloggers.com/?s=sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="http://www.r-bloggers.com/?s=LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="http://www.r-bloggers.com/?s=SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="http://www.r-bloggers.com/?s=eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="http://www.r-bloggers.com/?s=git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="http://www.r-bloggers.com/?s=hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="http://www.r-bloggers.com/?s=Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="http://www.r-bloggers.com/?s=regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="http://www.r-bloggers.com/?s=PCA">PCA</a>, <a title="Time series" rel="nofollow" href="http://www.r-bloggers.com/?s=time+series">time series</a>, <a title="finance trading" rel="nofollow" href="http://www.r-bloggers.com/?s=trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/nMZ01mFJnEY"></a></div>