How To Predict Values From A Custom R Model in Power BI | by Luca Zavarella | Towards 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.
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:
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:
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).
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”:
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”:
That’s it! The R model is now into our Power BI report.
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:
a new dialog window pops up, asking for parameter details. After checking the min, mean and max values for wt, here the entered values:
When OK is clicked, a new calculated table is added. Rename its objects as it appears in the following picture:
The associated slicer will be as following:
Do the same for the qsec 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:
We can then add a Smart Filter choosing the Transmission value as field:
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.
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:
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:
That’s it! Here the complete report shown during few interactions with it:
A complete pbix file and the model saved as a rds file are available at this link.
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:
Obviously, if we try to refresh the underlying report dataset:
we’ll get an error, since there is no gateway connected to the model file to retrieve the serialized model:
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:
If you want Microsoft will take into account this feature in future releases, you could vote this feature request.
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.
You can find more details about the technique used in this post, both for models developed in R and Python, in my book “Extending Power BI with Python and R”:
It is available worldwide on Amazon. Here few links:
📕 Amazon US📗 Amazon IT📘 Amazon JP📙 Amazon AU
Hope you’ll find it interesting! 🙂