<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/building-online-interactive-simulators-for-predictive-models-in-r/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://www.displayr.com/building-online-interactive-simulators-for-predictive-models-in-r/?utm_medium=Feed&utm_source=Syndication"> R – Displayr</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p><strong><span>Correctly interpreting predictive models can be tricky. One solution to this problem is to create <em>interactive</em> <em>simulators</em>, where users can manipulate the predictor variables and see how the predictions change. This post describes a simple approach for creating online interactive simulators. It works for any model where there is a <span>predict</span> method. Better yet, if the model’s not top secret, you can build and share the model for no cost, using the free version of Displayr!</span></strong></p>
<p>In this post I show how to describe the very simple simulator shown below. Click the image to interact with it, or click the button below to explore and edit the code.</p>
<p><a rel="nofollow" href="https://app.displayr.com/Dashboard?id=81f9bf66-f475-40a9-8e9c-1c557f80c709" target="_blank"><img sizes="(max-width: 270px) 100vw, 270px" src="https://i0.wp.com/www.displayr.com/wp-content/uploads/2018/09/Simulator1.png?resize=270%2C180&ssl=1" alt="" width="270" class="wp-image-10210" data-recalc-dims="1" height="180"></a></p>
<p><a rel="nofollow" href="https://app.displayr.com/Dashboard?id=81f9bf66-f475-40a9-8e9c-1c557f80c709" target="_blank"><strong><a rel="nofollow" href="https://app.displayr.com/try/Simulator%20Predict" target="_blank"><span>Explore and edit this simulator</span></a></strong></a></p>
<h2>Step 1: Create the model</h2>
<p>The first step is to create a model. There are lots of ways to do this, including:</p>
<ul>
<li>Creating the model using R code from within Displayr. I illustrate this below.</li>
<li>Pasting in estimates that you have already computed <strong>(Insert > Paste</strong> <strong>Table</strong>)<strong>.</strong></li>
<li>Using Displayr’s graphical user interface.</li>
<li>Creating an R model somewhere else, saving it somewhere on the web (e.g., Dropbox), and then reading it into Displayr using <span>readRDS</span>. (See <a rel="nofollow" href="https://www.displayr.com/how-to-copy-an-r-object-across-documents/" target="_blank">How to Link Documents in Displayr</a> for a discussion of some utilities we have created for reading from Dropbox.)</li>
</ul>
<p>In this post I will illustrate by using one of my all-time favorite models – a generalized additive model – via the <span>gam</span> function in the <span>mgcv</span> package. The process for creating this in Displayr is:</p>
<ul>
<li>Log in to <a rel="nofollow" href="https://www.displayr.com/" target="_blank">Displayr</a> (if you don’t already have an account, click the <span><a rel="nofollow" href="https://app.displayr.com/SignUp?plan_id=0" target="_blank"> GET DISPLAYR FREE</a> </span> button at the top-right of the screen).</li>
<li>Press <strong>Insert > R Output (Analysis).</strong></li>
<li>Enter your code into the R Output and press the <span> </span><strong><span>CALCULATE </span> </strong>button at the top of the <a rel="nofollow" href="https://docs.displayr.com/wiki/Object_Inspector" target="_blank">Object Inspector</a>. In the example below I have fitted a GAM using some of <a rel="nofollow" href="https://community.watsonanalytics.com/wp-content/uploads/2015/03/WA_Fn-UseC_-Telco-Customer-Churn.csv" target="_blank">IBM’s telco churn example data</a>.</li>
</ul>
<p><iframe width="450" src="https://embedded.azureedge.net/75668/296837/9d14958d-71a0-439a-82a3-4cdc7a899447.html?v=32413;-d3b24494c8;;-582611177"></iframe>
</p>
<h2>Step 2: Add controls for each of the predictors</h2>
<ul>
<li>Press <strong>Insert > Control (More) </strong>(this option is on the far right of the <a rel="nofollow" href="https://docs.displayr.com/wiki/Ribbon" target="_blank">ribbon</a>).</li>
<li>In the <a rel="nofollow" href="https://docs.displayr.com/wiki/Object_Inspector" target="_blank">Object Inspector</a> > <strong>Properties > GENERAL</strong>, set the <strong>Name</strong> to <span>cSeniorCitizen</span>. You can give it any name you wish, but it is usually helpful to have a clear naming standard. In this example, I am using <span>c</span> so that whenever I refer to the control in code it is obvious to me that it is a control.</li>
<li>Click on the <strong>Control </strong>tab of the <a rel="nofollow" href="https://docs.displayr.com/wiki/Object_Inspector" target="_blank">Object Inspector</a> and set the <strong>Item list</strong> to <span>No; Yes</span>, which means that the user will have a choice between <strong>No </strong>and <strong>Yes </strong>when using the control.</li>
<li>Press <strong>Insert > Text box</strong> and click and drag to draw a text box to the left of the control. Type <span>Senior Citizen</span> into the text box, set it to be right-aligned (in the <strong>Appearance</strong> tab of the ribbon), with a font size of 10. You can micro-control layout by selecting the textbox, holding down your control key, and clicking the arrow keys on your keyboard.</li>
<li>Click on the control and select <strong>No</strong>. It should look as shown below.</li>
</ul>
<p><img sizes="(max-width: 256px) 100vw, 256px" src="https://i2.wp.com/www.displayr.com/wp-content/uploads/2018/09/Controls.png?resize=256%2C137&ssl=1" alt="" width="256" class="wp-image-10214" data-recalc-dims="1" height="137"></p>
<ul>
<li>Now, using shift and your mouse, select the text box and the control and press <strong>Home > Duplicate</strong>, and drag the copies to be neatly arranged underneath. Repeat this until you have four sets of labels and controls, one under each other.</li>
<li>Update the textboxes, and each control’s <strong>Name</strong>, and <strong>Item list</strong>, as follows:
<ul>
<li><span>Tenure (months)</span>, <span>cTenure</span>: <span>0; 1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12; 13; 14; 15; 16; 17; 18; 19; 20; 21; 22; 23; 24; 25; 26; 27; 28; 29; 30; 31; 32; 33; 34; 35; 36; 37; 38; 39; 40; 41; 42; 43; 44; 45; 46; 47; 48; 49; 50; 51; 52; 53; 54; 55; 56; 57; 58; 59; 60; 61; 62; 63; 64; 65; 66; 67; 68; 69; 70; 71; 72<span> </span></span></li>
<li><span>Internet service</span>, <span>cInternetService:</span> <span>No; DSL; Fiber optic</span></li>
<li><span>Monthly charges</span>, <span>cMonthlyCharges:</span> <span>$</span><span>0; $10; $20; $30; $40; $50; $60; $70; $80; $90; $100; $110; $120</span></li>
</ul>
</li>
<li>Select any option from each of the controls (it does not matter which you choose).</li>
</ul>
<h2>Step 3: Computing the prediction</h2>
<p>Press <strong>Insert > R Output (Analysis) </strong>and then enter the code below, modifying it as per your needs. For example, with the code <span>SeniorCitizen = cSeniorCitizen</span>, the variable name used in the model is <span>SeniorCitizen</span> and <span>cSeniorCitizen</span> is the name of the control.</p>
<p>The item names in the control must exactly match the values of the variables in the data set. It is for this reason that the <span>MonthlyCharges</span> code is a bit more complicated, as it needs to strip out the <span>$</span> from the control and convert it into a number (as the variable in the data set just contains numbers).</p>
<pre>   
predict(my.gam,
        type = &quot;response&quot;,
        newdata = data.frame(SeniorCitizen = cSeniorCitizen, 
                    Tenure = as.numeric(cTenure),
                    InternetService = cInternetService,
                    MonthlyCharges = as.numeric(gsub(&quot;\\$&quot;, &quot;&quot;, cMonthlyCharges))))[1] * 100
</pre>
<h3>Confidence bands</h3>
<p>Provided that the predict method supports them, the same approach easily extends to computing confidence intervals and other quantities from models. This code snippet computes the confidence intervals for the GAM used above.</p>
<pre> 
pred &lt;- predict(my.gam,
        se.fit = TRUE,
        newdata = data.frame(SeniorCitizen = cSeniorCitizen, 
                    Tenure = as.numeric(cTenure),
                    InternetService = cInternetService,
                    MonthlyCharges = as.numeric(gsub(&quot;\\$&quot;, &quot;&quot;, cMonthlyCharges))))
bounds = plogis(pred$fit + c(-1.96, 0, 1.96) * pred$se.fit) * 100
names(bounds) = c(&quot;Lower 95% CI&quot;, &quot;Predicted&quot;, &quot;Upper 95% CI&quot;)
bounds
</pre>
<h3>Computing predictions from coefficients</h3>
<p>And, of course, you can also make predictions directly from coefficients, rather than from model objects. For example, the following code makes a prediction for a logistic regression:</p>
<pre> 
coefs = my.logistic.regression$coef
XB = coefs[&quot;(Intercept)&quot;] + 
        switch(cSeniorCitizen, 
               No = 0, 
               Yes = coefs[&quot;SeniorCitizenYes&quot;]) +
        as.numeric(cTenure) * coefs[&quot;Tenure&quot;] +
        switch(cInternetService, 
               No =  coefs[&quot;InternetServiceNo&quot;], 
               &quot;Fiber optic&quot; = coefs[&quot;InternetServiceFiber optic&quot;], 
               DSL = 0) +
        as.numeric(gsub(&quot;\\$&quot;, &quot;&quot;, cMonthlyCharges)) * coefs[&quot;MonthlyCharges&quot;]
100 / (1 + exp(-XB))
</pre>
<h3>Making safe predictions</h3>
<p>Sometimes models perform “unsafe” transformations of the data in their internals. For example, some machine learning models standardize inputs (subtract the mean and divide by standard deviation). This can create a problem at prediction time, as the predict method may, in the background, attempt to repeat the standardization using the data for the prediction. This will cause an error (as the standard deviation of a single input observation is 0). Similarly, it is possible to create unsafe predictions from even the most well-written model (e.g., if using <span>poly</span> or <span>scale</span> in your model formula). There are a variety of ways of dealing with unsafe predictions, but a safe course of action is to perform any transformations outside of the model (i.e., not in the model formula).</p>
<h2>Step 4: Export the simulator</h2>
<p>If everything has gone to plan you can now use the simulator. To export it so that others can use it, click <strong>Export > Public Web Page</strong>, and you can then share the link with whoever you wish. The version that I have created here is very simple, but you can do a lot more if you want to make something pretty or more detailed (see the <a rel="nofollow" href="https://www.displayr.com/displayr-dashboard-showcase/" target="_blank">Displayr Dashboard Showcase</a> for more examples).<a rel="nofollow" href="https://app.displayr.com/Dashboard?id=81f9bf66-f475-40a9-8e9c-1c557f80c709" target="_blank"><img sizes="(max-width: 1024px) 100vw, 1024px" src="https://i1.wp.com/www.displayr.com/wp-content/uploads/2018/09/simulator-1024x708.png?w=450&ssl=1" alt="" class="wp-image-10449" data-recalc-dims="1"></a></p>
<p><strong><a rel="nofollow" href="https://app.displayr.com/try/Simulator%20Predict" target="_blank"><span>Explore and edit this simulator</span></a></strong></p>
<p><a rel="nofollow" href="https://app.displayr.com/Dashboard?id=81f9bf66-f475-40a9-8e9c-1c557f80c709" target="_blank">Click here</a> to interact with the published dashboard, or <a rel="nofollow" href="https://app.displayr.com/try/Simulator%20Predict" target="_blank">click here</a> to open a copy of the Displayr document that I created when writing this post. It is completely live, so you can interact with it. Click on any of the objects on the page to view the underlying R code, which will appear in the <a rel="nofollow" href="https://docs.displayr.com/wiki/Object_Inspector" target="_blank">Object Inspector</a> <strong>> Properties > R CODE</strong>.</p>
<p><strong>Ready to get started? Create your own simulator for free in <a rel="nofollow" href="https://app.displayr.com/SignUp?plan_id=0" target="_blank">Displayr</a>!</strong></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.displayr.com/building-online-interactive-simulators-for-predictive-models-in-r/?utm_medium=Feed&utm_source=Syndication"> R – Displayr</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/pPpjYgMU-nk" height="1"></a></div>