Predicting the target values for new observations is implemented the same way as most of the other predict methods in R. In general, all you need to do is call predict (predict.WrappedModel()) on the object returned by train() and pass the data you want predictions for.

There are two ways to pass the data:

  • Either pass the Task() via the task argument or
  • pass a data.frame via the newdata argument.

The first way is preferable if you want predictions for data already included in a Task().

Just as train(), the predict (predict.WrappedModel()) function has a subset argument, so you can set aside different portions of the data in Task() for training and prediction (more advanced methods for splitting the data in train and test set are described in the section on resampling).

In the following example we fit a gradient boosting machine (gbm::gbm()) to every second observation of the BostonHousing (mlbench::BostonHousing()) data set and make predictions on the remaining data in bh.task().

The second way is useful if you want to predict data not included in the Task().

Here we cluster the iris data set without the target variable. All observations with an odd index are included in the Task() and used for training. Predictions are made for the remaining observations.

Note that for supervised learning you do not have to remove the target columns from the data. These columns are automatically removed prior to calling the underlying predict method of the learner.

Accessing the prediction

Function predict() returns a named list of class Prediction(). Its most important element is $data which is a data.frame that contains columns with the true values of the target variable (in case of supervised learning problems) and the predictions. Use (Prediction()) for direct access.

In the following the predictions on the BostonHousing (mlbench::BostonHousing()) and the iris (datasets::iris()) data sets are shown. As you may recall, the predictions in the first case were made from a Task() and in the second case from a data.frame.

As you can see when predicting from a Task(), the resulting data.frame contains an additional column, called id, which tells us which element in the original data set the prediction corresponds to.

A direct way to access the true and predicted values of the target variable(s) is provided by functions getPredictionTruth (getPredictionResponse()) and [getPredictionResponse()].

Regression: Extracting standard errors

Some learners provide standard errors for predictions, which can be accessed in mlr. An overview is given by calling the function listLearners() and setting properties = "se". By assigning FALSE to check.packages learners from packages which are not installed will be included in the overview.

In this example we train a linear regression model (stats::lm()) on the BostonHousing (bh.task()) dataset. In order to calculate standard errors set the predict.type to "se":

The standard errors can then be extracted using getPredictionSE().

Classification and clustering: Extracting probabilities

The predicted probabilities can be extracted from the Prediction() using function getPredictionProbabilities(). Here is another cluster analysis example. We use fuzzy c-means clustering (e1071::cmeans()) on the mtcars (datasets::mtcars()) data set.

For classification problems there are some more things worth mentioning. By default, class labels are predicted.

In order to get predicted posterior probabilities we have to create a Learner (makeLearner()) with the appropriate predict.type.

In addition to the probabilities, class labels are predicted by choosing the class with the maximum probability and breaking ties at random.

As mentioned above, the predicted posterior probabilities can be accessed via the getPredictionProbabilities() function.

Classification: Confusion matrix

A confusion matrix can be obtained by calling calculateConfusionMatrix(). The columns represent predicted and the rows true class labels.

You can see the number of correctly classified observations on the diagonal of the matrix. Misclassified observations are on the off-diagonal. The total number of errors for single (true and predicted) classes is shown in the -err.- row and column, respectively.

To get relative frequencies additional to the absolute numbers we can set relative = TRUE.

It is possible to normalize by either row or column, therefore every element of the above relative confusion matrix contains two values. The first is the relative frequency grouped by row (the true label) and the second value grouped by column (the predicted label).

If you want to access the relative values directly you can do this through the $relative.row and $relative.col members of the returned object conf.matrix. For more details see the ConfusionMatrix() documentation page.

Finally, we can also add the absolute number of observations for each predicted and true class label to the matrix (both absolute and relative) by setting sums = TRUE.

Classification: Adjusting the decision threshold

We can set the threshold value that is used to map the predicted posterior probabilities to class labels. Note that for this purpose we need to create a Learner (makeLearner()) that predicts probabilities. For binary classification, the threshold determines when the positive class is predicted. The default is 0.5. Now, we set the threshold for the positive class to 0.9 (that is, an example is assigned to the positive class if its posterior probability exceeds 0.9). Which of the two classes is the positive one can be seen by accessing the Task(). To illustrate binary classification, we use the Sonar (mlbench::Sonar()) data set from the mlbench package.

Note that in the binary case getPredictionProbabilities() by default extracts the posterior probabilities of the positive class only.

It works similarly for multiclass classification. The threshold has to be given by a named vector specifying the values by which each probability will be divided. The class with the maximum resulting value is then selected.

If you are interested in tuning the threshold (vector) have a look at the section about performance curves and threshold tuning.

Visualizing the prediction

The function plotLearnerPrediction() allows to visualize predictions, e.g., for teaching purposes or exploring models. It trains the chosen learning method for 1 or 2 selected features and then displays the predictions with ggplot2::ggplot().

For classification, we get a scatter plot of 2 features (by default the first 2 in the data set). The type of symbol shows the true class labels of the data points. Symbols with white border indicate misclassified observations. The posterior probabilities (if the learner under consideration supports this) are represented by the background color where higher saturation means larger probabilities.

The plot title displays the ID of the Learner (makeLearner()) (in the following example CART), its parameters, its training performance and its cross-validation performance. mmce stands for mean misclassification error, i.e., the error rate. See the sections on performance and resampling for further explanations.

lrn = makeLearner("classif.rpart", id = "CART")
plotLearnerPrediction(lrn, task = iris.task)

For clustering we also get a scatter plot of two selected features. The color of the points indicates the predicted cluster.

For regression, there are two types of plots. The 1D plot shows the target values in relation to a single feature, the regression curve and, if the chosen learner supports this, the estimated standard error.

plotLearnerPrediction("regr.lm", features = "lstat", task = bh.task)

The 2D variant, as in the classification case, generates a scatter plot of 2 features. The fill color of the dots illustrates the value of the target variable "medv", the background colors show the estimated mean. The plot does not represent the estimated standard error.

plotLearnerPrediction("regr.lm", features = c("lstat", "rm"), task = bh.task)