Introduction to the DataRobot R Package

Ron Pearson, Peter Hurford

2022-05-05

The name DataRobot refers to three things: a Boston-based software company, the massively parallel modeling engine developed by the DataRobot company, and an open-source R package that allows interactive R users to connect to this modeling engine. This vignette provides a brief introduction to the datarobot R package, highlighting the following key details of its use:

To illustrate how the datarobot package is used, it is applied here to the Boston dataframe from the MASS package, providing simple demonstrations of all of the above steps.

library(datarobot)

The DataRobot modeling engine

The DataRobot modeling engine is a commercial product that supports massively parallel modeling applications, building and optimizing models of many different types, and evaluating and ranking their relative performance. This modeling engine exists in a variety of implementations, some cloud-based, accessed via the Internet, and others residing in customer-specific on-premises computing environments. The datarobot R package described here allows anyone with access to one of these implementations to interact with it from an interactive R session. Connection between the R session and the modeling engine is accomplished via HTTP requests, with an initial connection established in one of two ways described in the next section.

The DataRobot modeling engine is organized around modeling projects, each based on a single data source, a single target variable to be predicted, and a single metric to be optimized in fitting and ranking project models. This information is sufficient to create a project, identified by a unique alphanumeric projectId label, and start the DataRobot Autopilot, which builds, evaluates, and summarizes a collection of models. While the Autopilot is running, intermediate results are saved in a list that is updated until the project completes. The last stage of the modeling process constructs blender models, ensemble models that combine two or more of the best-performing individual models in various different ways. These models are ranked in the same way as the individual models and are included in the final project list. When the project is complete, the essential information about all project models may be obtained with the ListModels function described later in this note. This function returns an S3 object of class ‘listOfModels’, which is a list with one element for each project model. A plot method has been defined for this object class, providing a convenient way to visualize the relative performance of these project models.

Connecting to DataRobot

To access the DataRobot modeling engine, it is necessary to establish an authenticated connection, which can be done in one of two ways. In both cases, the necessary information is an endpoint - the URL address of the specific DataRobot server being used - and a token, a previously validated access token.

token is unique for each DataRobot modeling engine account and can be accessed using the DataRobot webapp in the account profile section. It looks like a string of letters and numbers.

endpoint depends on DataRobot modeling engine installation (cloud-based, on-prem…) you are using. Contact your DataRobot admin for endpoint to use. The endpoint for DataRobot cloud accounts is https://app.datarobot.com/api/v2

The first access method uses a YAML configuration file with these two elements - labeled token and endpoint - located at $HOME/.config/datarobot/drconfig.yaml. If this file exists when the datarobot package is loaded, a connection to the DataRobot modeling engine is automatically established. It is also possible to establish a connection using this YAML file via the ConnectToDataRobot function, by specifying the configPath parameter.

The second method of establishing a connection to the DataRobot modeling engine is to call the function ConnectToDataRobot with the endpoint and token parameters.

ConnectToDataRobot(endpoint = "YOUR-ENDPOINT-HERE", token = "YOUR-API_TOKEN-HERE")

DataRobot API can work behind a non-transparent HTTP proxy server. Please set environment variable http_proxy containing proxy URL to route all the DataRobot traffic through that proxy server, e.g. http_proxy="http://my-proxy.local:3128" R -f my_datarobot_script.r.

Creating a new project

One of the most common and important uses of the datarobot R package is the creation of a new modeling project. This task is supported by the following three functions:

The first step in creating a new DataRobot modeling project uses the StartProject function, which has one required parameter, dataSource, that can be a dataframe, an object whose class inherits from dataframe (e.g., a data.table), or a CSV file. Although it is not required, the optional parameter projectName can be extremely useful in managing projects, especially as their number grows; in particular, while every project has a unique alphanumeric identifier projectId associated with it, this string is not easy to remember. Another optional parameter is maxWait, which specifies the maximum time in seconds before the project creation task aborts; increasing this parameter from its default value can be useful when working with large datasets.

StartProject also starts the model-building process by specifying a target, a character string that names the response variable to be predicted by all models in the project. Of the optional parameters for the StartProjct function, the only one discussed here is metric, a character string that specifies the measure to be optimized in fitting project models. Admissible values for this parameter are determined by the DataRobot modeling engine based on the nature of the target variable. A list of these values can be obtained using the function GetValidMetrics. The required parameters for this function are project and target, but here there are no optional parameters. The default value for the optional metric parameter in the StartProject function call is NULL, which causes the default metric recommended by the DataRobot modeling engine to be adopted. For a complete discussion of the other optional parameters for the StartProject function, refer to the help files.

Offsets

DataRobot also supports using an offset parameter in StartProject. Offsets are commonly used in insurance modeling to include effects that are outside of the training data due to regulatory compliance or constraints. You can specify the names of several columns in the project dataset to be used as the offset columns.

Exposure

DataRobot also supports using an exposure parameter in StartProject. Exposure is often used to model insurance premiums where strict proportionality of premiums to duration is required. You can specify the name of the column in the project dataset to be used as an exposure column.

The Boston housing dataframe

To provide a specific illustration of how a new DataRobot project is created, the following discussion shows the creation of a project based on the Boston dataframe from the MASS package. This dataframe characterizes housing prices in Boston from a paper published in 1978 by Harrison and Rubinfeld (“Hedonic prices and the demand for clean air,” Journal of Environmental Economics and Management, vol. 5, 1978, pp. 81-102). The dataframe is described in more detail in the associated help file from the MASS package, but the head function shows its basic structure:

head(Boston)
##      crim zn indus chas   nox    rm  age    dis rad tax ptratio  black lstat
## 1 0.00632 18  2.31    0 0.538 6.575 65.2 4.0900   1 296    15.3 396.90  4.98
## 2 0.02731  0  7.07    0 0.469 6.421 78.9 4.9671   2 242    17.8 396.90  9.14
## 3 0.02729  0  7.07    0 0.469 7.185 61.1 4.9671   2 242    17.8 392.83  4.03
## 4 0.03237  0  2.18    0 0.458 6.998 45.8 6.0622   3 222    18.7 394.63  2.94
## 5 0.06905  0  2.18    0 0.458 7.147 54.2 6.0622   3 222    18.7 396.90  5.33
## 6 0.02985  0  2.18    0 0.458 6.430 58.7 6.0622   3 222    18.7 394.12  5.21
##   medv
## 1 24.0
## 2 21.6
## 3 34.7
## 4 33.4
## 5 36.2
## 6 28.7

To create the modeling project for this dataframe, we first use the StartProject function:

project <- StartProject(dataSource = Boston,
                        projectName = "BostonVignetteProject",
                        target = "medv",
                        wait = TRUE)

dataSource defines the data used for predictions, projectName defines the name of the project, target defines what to predict, and wait = TRUE tells the function to wait until all modeling is complete before executing other computations.

The list returned by this function gives the project name, the project identifier (projectId), the name of the temporary CSV file used to save and upload the Boston dataframe, and the time and date the project was created. Here, we specify medv (median value of owner-occupied homes) as the response variable and we elect to use the default metric value chosen by the DataRobot modeling engine:

## $projectName
## [1] "BostonVignetteProject"
## 
## $projectId
## [1] "56e86b47c80891539f2bc872"
## 
## $fileName
## [1] "file119e54e27aa4_autoSavedDF.csv"
## 
## $created
## [1] "2016-03-15T20:06:36.447729Z"

Retrieving project results

The DataRobot project created by the command described above fits 30 models to the Boston dataframe. Detailed information about all of these models can be obtained with the ListModels function, invoked with the project list returned by the StartProject function.

listOfBostonModels <- ListModels(project)

The ListModels function returns an S3 object of class ‘listOfModels’, with one element for each model in the project. A summary method has been implemented for this object class, and it provides the following view of the contents of this list:

summary(listOfBostonModels)
## $generalSummary
## [1] "First 6 of 30 models from: listOfBostonModels (S3 object of class listOfModels)"
## 
## $detailedSummary
##                                                      modelType
## 1 Gradient Boosted Greedy Trees Regressor (Least-Squares Loss)
## 2                                                 ENET Blender
## 3                                                 ENET Blender
## 4                                                  AVG Blender
## 5                                         Advanced AVG Blender
## 6                             Gradient Boosted Trees Regressor
##                                                                                          expandedModel
## 1 Gradient Boosted Greedy Trees Regressor (Least-Squares Loss)::Tree-based Algorithm Preprocessing v15
## 2                                                                                         ENET Blender
## 3                                                                                         ENET Blender
## 4                                                                                          AVG Blender
## 5                                                                                 Advanced AVG Blender
## 6                                                   Gradient Boosted Trees Regressor::Open-Source Task
##                    modelId                      blueprintId
## 1 56e86b561f0d8d20596f5b94 45e6a473a324351a7867af171fd22983
## 2 56e86bdccf45e520f264abb6 96237fa6b351cc75cc01ed159ea33b7f
## 3 56e86bddcf45e520f264abba 693d71ec2b9669980edf8846d023d518
## 4 56e86bdccf45e520f264abae 7b8909256865d36293a6a466ab4a2650
## 5 56e86bdccf45e520f264abb2 da1cea809b8330b5b07f777adf597e69
## 6 56e86b561f0d8d20596f5b86 2fe946efb7398f20e120b80362020a83
##        featurelistName            featurelistId samplePct validationMetric
## 1 Informative Features 56e86b4ef4737c20d2d6a4ac    63.834          2.91752
## 2 Informative Features 56e86b4ef4737c20d2d6a4ac    63.834          3.24622
## 3 Informative Features 56e86b4ef4737c20d2d6a4ac    63.834          3.29761
## 4 Informative Features 56e86b4ef4737c20d2d6a4ac    63.834          3.31239
## 5 Informative Features 56e86b4ef4737c20d2d6a4ac    63.834          3.41212
## 6 Informative Features 56e86b4ef4737c20d2d6a4ac    63.834          3.48692

The first element of this list is generalSummary, which lets us know that the project includes 30 models, and that the second list element describes the first 6 of these models. This number is determined by the optional parameter nList for the summary method, which has the default value 6. The second list element is detailedSummary, which gives the first nList rows of the dataframe created when the as.data.frame method is applied to listOfBostonModels. Methods for the as.data.frame generic function are included in the datarobot package for all four ‘list of’ S3 model object classes: listOfBlueprints, listOfFeaturelists, listOfModels, and projectSummaryList. (Use of this function is illustrated in the following discussion; see the help files for more complete details.) This dataframe has the following eight columns:

  1. modelType: character string; describes the structure of each model
  2. expandedModel: character string; modelType with short descriptions of any preprocessing steps appended
  3. modelId: unique alphanumeric model identifier
  4. blueprintId: unique alphanumeric identifier for the blueprint used to fit the model
  5. featurelistName: name of the featurelist defining the modeling variables
  6. featurelistId: unique alphanumeric featurelist identifier
  7. samplePct: fraction of the training dataset used in fitting the model
  8. validationMetric: the value of the metric optimized in fitting the model, evaluated for the validation dataset

It is possible to obtain a more complete dataframe from any object of class ‘listOfModels’ by using the function as.data.frame with the optional parameter simple = FALSE. Besides the eight characteristics listed above, this larger dataframe includes, for every model in the project, additional project information along with validation, cross-validation, and holdout values for all of the available metrics for the project. For the project considered in this note, the result is a dataframe with 30 rows and 48 columns.

In addition to the summary method, a plot method has also been provided for objects of class ‘listOfModels’:

plot(listOfBostonModels, orderDecreasing = TRUE)

Horizontal barplot of modelType and validation set RMSE values for all project models

This function generates a horizontal barplot that lists the name of each model (i.e., modelType) in the center of each bar, with the bar length corresponding to the value of the model fitting metric, evaluated for the validation dataset (i.e., the validationMetric value). The only required parameter for this function is the ‘listOfModels’ class S3 object to be plotted, but there are a number of optional parameters that allow the plot to be customized. In the plot shown above, the logical parameter orderDecreasing has been set to TRUE so that the plot - generated from the bottom up - shows the models in decreasing order of validationMetric. For a complete list of optional parameters for this function, refer to the help files.

Since smaller values of RMSE.validation are better, this plot shows the worst model at the bottom and the best model at the top. The identities of these models are most conveniently obtained by first converting listOfBostonModels into a dataframe, using the as.data.frame generic function mentioned above:

You can also coerce the list of models to a data.frame, which may make it easier to see specific things (such as model metrics):

modelFrame <- as.data.frame(listOfBostonModels)
head(modelFrame[, c("modelType", "validationMetric")])
##                                                      modelType validationMetric
## 1 Gradient Boosted Greedy Trees Regressor (Least-Squares Loss)          2.91752
## 2                                                 ENET Blender          3.24622
## 3                                                 ENET Blender          3.29761
## 4                                                  AVG Blender          3.31239
## 5                                         Advanced AVG Blender          3.41212
## 6                             Gradient Boosted Trees Regressor          3.48692

It is interesting to note that this single best model, which is fairly complex in structure, actually outperforms all of the blender models (the next four models in the barplot above), formed by combining the best individual project models in different ways. This behavior is unusual, since the blender models usually achieve at least a small performance advantage over the component models on which they are based. In fact, since the individual component models may be regarded as constrained versions of the blender models (e.g., as a weighted average with all of the weight concentrated on one component), the training set performance can never be worse for a blender than it is for its components, but this need not be true of validation set performance, as this example demonstrates.

Or you can see the worst models:

tail(modelFrame[, c("modelType", "validationMetric")])
##                                                        modelType
## 25                                               Ridge Regressor
## 26                                               Ridge Regressor
## 27 Auto-tuned K-Nearest Neighbors Regressor (Minkowski Distance)
## 28 Auto-tuned K-Nearest Neighbors Regressor (Minkowski Distance)
## 29                                       Decision Tree Regressor
## 30                                       Mean Response Regressor
##    validationMetric
## 25          5.25016
## 26          5.25016
## 27          5.30140
## 28          5.51113
## 29          5.56084
## 30          9.71177

The worst model is a trivial “intercept-only” model that assigns the mean medv value to every record as its predicted response. This model is included in the project as a benchmark against which to compare the other, more useful prediction models.

It is also important to note that several of the models appear to be identical, based on their modelType values, but they exhibit different performances. This is most obvious from the four models labelled “Ridge Regressor” but it is also true of six other modelType values, each of which appears two or three times in the plot, generally with different values for RMSE.validation. In fact, these models are not identical, but differ in the preprocessing applied to them, or in other details.

In most cases, these differences may be seen by examining the expandedModel values from `modelFrame. For example, lets get all the different models that use Ridge Regressor:

Filter(function(m) grepl("Ridge", m), modelFrame$expandedModel)
## [1] "Ridge Regressor::Regularized Linear Model Preprocessing v14"
## [2] "Ridge Regressor::Constant Splines"                          
## [3] "Ridge Regressor::Regularized Linear Model Preprocessing v1" 
## [4] "Ridge Regressor::Missing Values Imputed::Standardize"

In particular, note that the modelType value appears at the beginning of the expandedModel character string, which is then followed by any pre-processing applied in fitting the model. Thus, comparing elements from this list (see below), we can see that, while these are all ridge regression models, they differ in their preprocessing steps. In the case of the ENET blender models, the differences lie in the component models incorporated into the blend and are not evident from this list.

Generating model predictions

The generation of model predictions uses Predict:

bestModel <- GetRecommendedModel(project)
bestPredictions <- Predict(bestModel, Boston)

GetRecommendedModel gives us the best model without having to go through the metrics manually. We can see in this case what the model is:

bestModel$modelType
## [1] "Gradient Boosted Greedy Trees Regressor (Least-Squares Loss)"

How good are our predictions? The plot below shows predicted versus observed medv values for this model. If the predictions were perfect, all of these points would lie on the dashed red equality line. The relatively narrow scatter of most points around this reference line suggests that this model is performing reasonably well for most of the dataset, with a few significant exceptions.

Feature Impact

But which features most drive our predictions? Which features are most important to the model? For this, we turn to feature impact.

impact <- GetFeatureImpact(model)
head(impact)
##   redundantWith featureName impactNormalized impactUnnormalized
## 1            NA       lstat        1.0000000           5.027165
## 2            NA          rm        0.9193327           4.621637
## 3            NA         dis        0.5043161           2.535280
## 4            NA         tax        0.4378073           2.200930
## 5            NA         rad        0.4125917           2.074166
## 6            NA         nox        0.3615163           1.817402

We can now see that lstat (percent lower status of population) and rm (average number of rooms per dwelling) are the two best predictors of our target medv (median value of owner-occupied homes). Normalized impact gives us a ratio of the impact of the feature relative to the top feature, whereas unnormalized impact is the actual impact statistic.

Summary

This note has presented a general introduction to the datarobot R package, describing and illustrating its most important functions. To keep this summary to a manageable length, no attempt has been made to describe all of the package’s capabilities; for a more detailed discussion, refer to the help files.