How To Predict Values From A Custom R Model in Power BI
By: Luca Zavarella
Tags: Rstats, Machine Learning, Power Bi, Data Science

If you usually develop predictive models in R for your customers, you might need to provide them with a practical GUI to test their model. A really simple and convenient way would be to provide the users with as many sliders and/or combo boxes as the input features of the model, and a simple label showing the predicted value. The first obvious choice for a R developer would be a Shiny App. But if your customer IT infrastructure is Microsoft-centric, a Power BI report could be the best choice.

Our Test Predictive Model

First of all, let’s create an R model to test with the Power BI report. We’ll use the mtcars dataset, which is a dataset that was extracted from the 1974 Motor Trend US magazine, and comprises fuel consumption and 10 aspects of automobile design and performance for 32 automobiles (1973–74 models). After an in-depth analysis you can find here, the final model to fit will be the following:

finalfit <- lm(mpg ~ wt+qsec+factor(am), data = mtcars)

We could load the training data into the Power BI model to do the training phase into the report. But in this way every time an input parameter is changed, a model training is needed, losing the real-time effect of the prediction. The best thing to do is using the already trained model into the Power BI report. So, let’s serialize it on the file system:

Let’s Set The Power BI Report

In order to execute the R code from Power BI Desktop, you need to have an R engine installation. If you already use RStudio with CRAN R, your Power BI Desktop options for R scripting would be something like this:

fig. 1 — Power BI Options for R Scripting

If you want to use the Microsoft R Open engine, make sure to have it installed on your machine and then change the R home directory properly.

The integration of the R language into Power BI Desktop is really effective. You can use an R script to:

Import Data

Transform Data

Create Visualizations

You can also import R-based Custom Visuals. For more information, you can read this blog post.

For our goal we will surely need an R Script Visualization to predict the target value from the model and then show it as text. Numerical feature can be entered via What-If parameters. Categorical ones can be entered via the OK Viz Smart Filter (just download the pbiviz file and import it).

Load the R model

Since we serialized our model in a RDS file, we need to load it first and then unserialize it into our report. If we did both these steps into the R Script Visualization, we would have an I/O operation (the load step) every time we modify an input value through a slicer or a combo box. In order to minimize the I/O operations and therefore have better prediction performance, it is better to load our predictive model from disk once (in an import data phase at the opening of the Power BI report) and then make just our predictions into the R Script Visualization.

Power BI can load data via R scripts only if it is of data.frame or data.table types (look at here for details). So, how can we load a serialized model into Power BI?

The trick is to serialize the model in a string of bytes and then store it in a dataframe.

So, after clicking on Get Data → More…, just search for “script”, select “R script” and click on “Connect”:

fig. 2 — Get data from an R script

Now just enter the following code into the popped-out R script window (thanks to Danny Shah for addressing an error due to the truncation of long strings in Power BI):

Notice that an absolute path is needed for the project_folder variable.

After clicking “OK” in the previous window, you have to select the model_df data frame and then click “Load”:

fig. 3 — Load the R dataframe into Power BI

That’s it! The R model is now into our Power BI report.

Adding Slicers and Combo boxes

Now it’s the time to add the visuals to our report. Since the input features are numerical (wt and qsec) and categorical (am), let’s add two What If Parameters and one Smart Filter. After clicking on New Parameter in the Modeling tab:

fig. 4 — Create a new What If Parameter

a new dialog window pops up, asking for parameter details. After checking the min, mean and max values for wt, here the entered values:

fig. 5 — Details for the Weight What If Parameter

When OK is clicked, a new calculated table is added. Rename its objects as it appears in the following picture:

fig. 6 — Calculated table added with the Weight What If Parameter

The associated slicer will be as following:

fig. 7 — The slicer for the new What If Parameter

Do the same for the qsec parameter:

fig. 8 — Details for the qsec What If Parameter

fig. 9 — Calculated table added with the qsec What If Parameter

In order to create the filter for the am categorical value, first of all we need to create a new table entering manual data:

fig. 10 — Create a manual table

fig. 11 — Entering manual data in a table

We can then add a Smart Filter choosing the Transmission value as field:

fig. 12 — Adding the Smart Filter

fig. 13 — The Transmission Smart Filter

Now we have all the controls needed to enter the input parameters. We just miss the “core” R code to predict values from the model.

Adding the R Script Visual

We can use the R Script Visual to unserialize the model and then show the predicted value as a string in a label. Let’s add it, dragging the following values in the component:

model_id

model_str

weight

qsec

am

The custom visual will be as following:

fig. 14 — Adding the R Script Visual

The code to add to the associated R script editor is the following (thanks to Danny Shah for fixing the missing trailing space issue):

The resulting label with the prediction is the following:

fig. 15 — The predicted value shown in the visual

That’s it! Here the complete report shown during few interactions with it:

fig. 16 — Interacting with the report

A complete pbix file and the model saved as a rds file are available at this link.

Publishing the Report

What if this tool has to be shared between stakeholders? One solution could be sharing the two files (pbix and model rds files) so that the users could use them in their laptop. The main issue of this solution is that the path pointing to the rds file has to be manually changed according to the new position where the user has downloaded it. So the user has to edit the pbix file (not so obvious for a common user).

A simpler solution is to publish the report to the Power BI service. The predictive model is already serialized in the Power BI model, so the dependency with the external file is removed. The only foresight is to make sure the R packages used in the report are already installed on the Power BI service. The supported R packages on the service are the ones at this link.

Since we used CRAN standard packages, our report can be easily published. Just a couple of clicks (pushing the Publish button on the Home tab and selecting the report destination) and that’s it:

fig. 17 — Interacting with the report published on the Power BI service

Obviously, if we try to refresh the underlying report dataset:

fig. 18 — Trying to refresh the dataset

we’ll get an error, since there is no gateway connected to the model file to retrieve the serialized model:

fig. 19 — Error after trying to refresh the dataset

You could bypass the error installing a Personal Gateway on the machine where the RDS file is located and where R is installed.

Just keep in mind that still today (April 2019) R visuals aren’t supported by the Publish to web feature:

fig. 20 — R Visuals are not allowed by Publish to Web

If you want Microsoft will take into account this feature in future releases, you could vote this feature request.

Conclusion

After a Data Scientist has trained a predictive model to solve a business problem, he has to provide stakeholders the tools to test it. The best tool to do that is a dynamic one that let them drag sliders and choose categorical values through filters to see the predicted value in real-time. Power BI reports can manage all this requirements and they can be easily shared through the Power BI service too.