In order to obtain honest performance estimates for a learner all parts of the model building like preprocessing and model selection steps should be included in the resampling, i.e., repeated for every pair of training/test data. For steps that themselves require resampling like parameter tuning or feature selection (via the wrapper approach) this results in two nested resampling loops.

Nested Resampling Figure
The graphic above illustrates nested resampling for parameter tuning with 3-fold cross-validation in the outer and 4-fold cross-validation in the inner loop.
In the outer resampling loop, we have three pairs of training/test sets. On each of these outer training sets parameter tuning is done, thereby executing the inner resampling loop. This way, we get one set of selected hyperparameters for each outer training set. Then the learner is fitted on each outer training set using the corresponding selected hyperparameters and its performance is evaluated on the outer test sets.
In mlr, you can get nested resampling for free without programming any looping by using the wrapper functionality. This works as follows:
makeLearner()) via function makeTuneWrapper() or makeFeatSelWrapper(). Specify the inner resampling strategy using their resampling argument.resample() (see also the section about resampling and pass the outer resampling strategy to its resampling argument.You can freely combine different inner and outer resampling strategies.
The outer strategy can be a resample description ResampleDesc (makeResampleDesc())) or a resample instance (makeResampleInstance())). A common setup is prediction and performance evaluation on a fixed outer test set. This can be achieved by using function makeFixedHoldoutInstance() to generate the outer resample instance(makeResampleInstance()`).
The inner resampling strategy should preferably be a ResampleDesc (makeResampleDesc()), as the sizes of the outer training sets might differ. Per default, the inner resample description is instantiated once for every outer training set. This way during tuning/feature selection all parameter or feature sets are compared on the same inner training/test sets to reduce variance. You can also turn this off using the same.resampling.instance argument of makeTuneControl* (TuneControl()) or makeFeatSelControl* (FeatSelControl()).
Nested resampling is computationally expensive. For this reason in the examples shown below we use relatively small search spaces and a low number of resampling iterations. In practice, you normally have to increase both. As this is computationally intensive you might want to have a look at section parallelization.
As you might recall from the tutorial page about tuning, you need to define a search space by function ParamHelpers::makeParamSet(), a search strategy by makeTuneControl*(TuneControl()), and a method to evaluate hyperparameter settings (i.e., the inner resampling strategy and a performance measure).
Below is a classification example. We evaluate the performance of a support vector machine (kernlab::ksvm()) with tuned cost parameter C and RBF kernel parameter sigma. We use 3-fold cross-validation in the outer and subsampling with 2 iterations in the inner loop. For tuing a grid search is used to find the hyperparameters with lowest error rate (mmce is the default measure for classification). The wrapped Learner (makeLearner()) is generated by calling makeTuneWrapper().
Note that in practice the parameter set should be larger. A common recommendation is 2^(-12:12) for both C and sigma.
### Tuning in inner resampling loop
ps = makeParamSet(
makeDiscreteParam("C", values = 2^(-2:2)),
makeDiscreteParam("sigma", values = 2^(-2:2))
)
ctrl = makeTuneControlGrid()
inner = makeResampleDesc("Subsample", iters = 2)
lrn = makeTuneWrapper("classif.ksvm", resampling = inner, par.set = ps, control = ctrl, show.info = FALSE)
### Outer resampling loop
outer = makeResampleDesc("CV", iters = 3)
r = resample(lrn, iris.task, resampling = outer, extract = getTuneResult, show.info = FALSE)
r
## Resample Result
## Task: iris-example
## Learner: classif.ksvm.tuned
## Aggr perf: mmce.test.mean=0.0466667
## Runtime: 6.76304You can obtain the error rates on the 3 outer test sets by:
We have kept the results of the tuning for further evaluations. For example one might want to find out, if the best obtained configurations vary for the different outer splits. As storing entire models may be expensive (but possible by setting models = TRUE) we used the extract option of resample(). Function getTuneResult() returns, among other things, the optimal hyperparameter values and the optimization path (ParamHelpers::OptPath()) for each iteration of the outer resampling loop. Note that the performance values shown when printing r$extract are the aggregated performances resulting from inner resampling on the outer training set for the best hyperparameter configurations (not to be confused with r$measures.test shown above).
r$extract
## [[1]]
## Tune result:
## Op. pars: C=0.5; sigma=0.5
## mmce.test.mean=0.0147059
##
## [[2]]
## Tune result:
## Op. pars: C=4; sigma=0.25
## mmce.test.mean=0.0441176
##
## [[3]]
## Tune result:
## Op. pars: C=0.5; sigma=0.25
## mmce.test.mean=0.0441176
names(r$extract[[1]])
## [1] "learner" "control" "x" "y" "resampling"
## [6] "threshold" "opt.path"We can compare the optimal parameter settings obtained in the 3 resampling iterations. As you can see, the optimal configuration usually depends on the data. You may be able to identify a range of parameter settings that achieve good performance though, e.g., the values for C should be at least 1 and the values for sigma should be between 0 and 1.
With function getNestedTuneResultsOptPathDf() you can extract the optimization paths for the 3 outer cross-validation iterations for further inspection and analysis. These are stacked in one data.frame with column iter indicating the resampling iteration.
opt.paths = getNestedTuneResultsOptPathDf(r)
head(opt.paths, 10)
## C sigma mmce.test.mean dob eol error.message exec.time iter
## 1 0.25 0.25 0.04411765 1 NA <NA> 1.946 1
## 2 0.5 0.25 0.01470588 2 NA <NA> 0.054 1
## 3 1 0.25 0.02941176 3 NA <NA> 0.058 1
## 4 2 0.25 0.02941176 4 NA <NA> 0.052 1
## 5 4 0.25 0.02941176 5 NA <NA> 0.036 1
## 6 0.25 0.5 0.01470588 6 NA <NA> 0.078 1
## 7 0.5 0.5 0.01470588 7 NA <NA> 0.052 1
## 8 1 0.5 0.02941176 8 NA <NA> 0.049 1
## 9 2 0.5 0.02941176 9 NA <NA> 0.052 1
## 10 4 0.5 0.02941176 10 NA <NA> 0.051 1Below we visualize the opt.paths for the 3 outer resampling iterations.
g = ggplot(opt.paths, aes(x = C, y = sigma, fill = mmce.test.mean))
g + geom_tile() + facet_wrap(~ iter)
Another useful function is getNestedTuneResultsX(), which extracts the best found hyperparameter settings for each outer resampling iteration.
You can furthermore access the resampling indices of the inner level using getResamplingIndices() if you used either extract = getTuneResult or extract = getFeatSelResult in the resample() call:
getResamplingIndices(r, inner = TRUE)
## [[1]]
## [[1]]$train.inds
## [[1]]$train.inds[[1]]
## [1] 60 25 94 96 8 47 70 10 9 69 33 84 42 23 79 18 91
## [18] 35 31 12 50 5 89 11 93 59 77 64 73 82 67 22 58 49
## [35] 98 20 53 92 19 76 21 57 55 15 99 54 4 38 97 66 30
## [52] 46 90 88 28 48 61 3 100 56 40 32 51 74 36 68
##
## [[1]]$train.inds[[2]]
## [1] 1 29 27 90 22 99 60 33 49 43 5 7 6 64 26 86 63
## [18] 46 48 57 68 88 73 47 92 19 84 37 24 54 96 82 35 97
## [35] 18 76 12 34 20 45 56 14 51 98 100 32 78 72 10 75 77
## [52] 3 66 55 83 94 39 87 81 61 65 28 74 16 44 13
##
##
## [[1]]$test.inds
## [[1]]$test.inds[[1]]
## [1] 6 95 75 16 26 43 86 45 63 1 78 65 34 29 71 44 17 14 13 81 37 72 24
## [24] 83 85 41 27 7 87 52 80 2 62 39
##
## [[1]]$test.inds[[2]]
## [1] 95 69 50 58 21 89 67 91 93 9 79 4 38 71 59 25 8 15 53 17 42 40 85
## [24] 41 52 30 80 23 2 62 31 11 70 36
##
##
##
## [[2]]
## [[2]]$train.inds
## [[2]]$train.inds[[1]]
## [1] 70 62 98 86 72 32 13 68 36 21 83 46 95 19 39 74 58
## [18] 100 29 96 67 24 53 10 84 69 20 93 37 6 15 49 92 12
## [35] 44 43 87 9 91 77 80 64 27 48 1 7 38 23 59 54 35
## [52] 28 22 60 50 71 63 41 76 4 14 61 8 90 75 97
##
## [[2]]$train.inds[[2]]
## [1] 83 1 8 65 10 81 63 51 11 30 48 93 2 62 12 16 71
## [18] 53 26 58 18 69 55 99 4 79 86 64 73 22 59 29 92 13
## [35] 85 31 50 89 42 96 57 90 25 52 80 88 28 68 47 33 9
## [52] 91 43 21 27 45 78 32 100 6 34 40 49 56 36 41
##
##
## [[2]]$test.inds
## [[2]]$test.inds[[1]]
## [1] 42 17 40 2 66 89 26 88 81 16 47 85 55 99 33 78 5 31 18 3 30 57 65
## [24] 56 73 52 51 11 94 45 82 25 79 34
##
## [[2]]$test.inds[[2]]
## [1] 35 95 7 17 23 66 77 75 97 19 20 54 44 37 70 5 60 24 3 39 76 46 98
## [24] 15 67 74 38 87 14 72 61 94 82 84
##
##
##
## [[3]]
## [[3]]$train.inds
## [[3]]$train.inds[[1]]
## [1] 92 97 49 51 65 46 96 98 27 90 50 94 68 26 29 32 21
## [18] 1 93 61 85 48 41 79 63 95 89 78 43 14 86 71 34 54
## [35] 35 16 13 87 81 7 76 39 59 17 62 70 60 40 28 58 52
## [52] 44 75 56 33 38 100 64 19 67 77 99 5 31 12 91
##
## [[3]]$train.inds[[2]]
## [1] 81 56 8 25 79 18 71 52 27 84 92 88 11 61 44 16 91 38 62 31 57 41 63
## [24] 17 32 58 54 74 96 53 33 46 35 78 86 4 85 80 5 87 22 21 66 12 64 72
## [47] 23 67 98 47 13 82 34 42 77 55 65 37 28 50 60 68 36 9 49 70
##
##
## [[3]]$test.inds
## [[3]]$test.inds[[1]]
## [1] 6 82 2 80 20 45 88 83 55 30 72 69 23 24 11 53 42 9 73 15 84 18 10
## [24] 25 37 66 74 36 57 4 22 47 3 8
##
## [[3]]$test.inds[[2]]
## [1] 6 51 2 90 39 76 20 45 83 30 97 69 19 95 59 24 1
## [18] 99 93 73 15 29 40 100 94 14 10 89 7 48 43 75 3 26As you might recall from the section about feature selection, mlr supports the filter and the wrapper approach.
Wrapper methods use the performance of a learning algorithm to assess the usefulness of a feature set. In order to select a feature subset a learner is trained repeatedly on different feature subsets and the subset which leads to the best learner performance is chosen.
For feature selection in the inner resampling loop, you need to choose a search strategy (function makeFeatSelControl* (FeatSelControl())), a performance measure and the inner resampling strategy. Then use function makeFeatSelWrapper() to bind everything together.
Below we use sequential forward selection with linear regression on the BostonHousing (mlbench::BostonHousing() data set (bh.task()).
### Feature selection in inner resampling loop
inner = makeResampleDesc("CV", iters = 3)
lrn = makeFeatSelWrapper("regr.lm", resampling = inner,
control = makeFeatSelControlSequential(method = "sfs"), show.info = FALSE)
### Outer resampling loop
outer = makeResampleDesc("Subsample", iters = 2)
r = resample(learner = lrn, task = bh.task, resampling = outer, extract = getFeatSelResult,
show.info = FALSE)
r
## Resample Result
## Task: BostonHousing-example
## Learner: regr.lm.featsel
## Aggr perf: mse.test.mean=25.8675177
## Runtime: 9.94477
r$measures.test
## iter mse
## 1 1 26.85474
## 2 2 24.88030The result of the feature selection can be extracted by function getFeatSelResult(). It is also possible to keep whole models (makeWrappedModel()) by setting models = TRUE when calling resample().
r$extract
## [[1]]
## FeatSel result:
## Features (8): indus, chas, nox, rm, dis, ptratio, b, lstat
## mse.test.mean=23.3978581
##
## [[2]]
## FeatSel result:
## Features (12): crim, zn, chas, nox, rm, age, dis, rad, tax, ptratio, b, lstat
## mse.test.mean=23.9664267
### Selected features in the first outer resampling iteration
r$extract[[1]]$x
## [1] "indus" "chas" "nox" "rm" "dis" "ptratio" "b"
## [8] "lstat"
### Resampled performance of the selected feature subset on the first inner training set
r$extract[[1]]$y
## mse.test.mean
## 23.39786As for tuning, you can extract the optimization paths. The resulting data.frames contain, among others, binary columns for all features, indicating if they were included in the linear regression model, and the corresponding performances.
opt.paths = lapply(r$extract, function(x) as.data.frame(x$opt.path))
head(opt.paths[[1]])
## crim zn indus chas nox rm age dis rad tax ptratio b lstat mse.test.mean
## 1 0 0 0 0 0 0 0 0 0 0 0 0 0 86.34071
## 2 1 0 0 0 0 0 0 0 0 0 0 0 0 76.88138
## 3 0 1 0 0 0 0 0 0 0 0 0 0 0 77.13707
## 4 0 0 1 0 0 0 0 0 0 0 0 0 0 64.54927
## 5 0 0 0 1 0 0 0 0 0 0 0 0 0 85.08633
## 6 0 0 0 0 1 0 0 0 0 0 0 0 0 71.01646
## dob eol error.message exec.time
## 1 1 2 <NA> 0.034
## 2 2 2 <NA> 0.053
## 3 2 2 <NA> 0.042
## 4 2 2 <NA> 0.047
## 5 2 2 <NA> 0.044
## 6 2 2 <NA> 0.048An easy-to-read version of the optimization path for sequential feature selection can be obtained with function analyzeFeatSelResult().
analyzeFeatSelResult(r$extract[[1]])
## Features : 8
## Performance : mse.test.mean=23.3978581
## indus, chas, nox, rm, dis, ptratio, b, lstat
##
## Path to optimum:
## - Features: 0 Init : Perf = 86.341 Diff: NA *
## - Features: 1 Add : lstat Perf = 37.952 Diff: 48.389 *
## - Features: 2 Add : rm Perf = 30.049 Diff: 7.9024 *
## - Features: 3 Add : ptratio Perf = 25.543 Diff: 4.5065 *
## - Features: 4 Add : b Perf = 24.697 Diff: 0.84637 *
## - Features: 5 Add : dis Perf = 24.339 Diff: 0.35792 *
## - Features: 6 Add : nox Perf = 23.794 Diff: 0.54448 *
## - Features: 7 Add : chas Perf = 23.476 Diff: 0.31762 *
## - Features: 8 Add : indus Perf = 23.398 Diff: 0.078628 *
##
## Stopped, because no improving feature was found.Filter methods assign an importance value to each feature. Based on these values you can select a feature subset by either keeping all features with importance higher than a certain threshold or by keeping a fixed number or percentage of the highest ranking features. Often, neither the theshold nor the number or percentage of features is known in advance and thus tuning is necessary.
In the example below the threshold value (fw.threshold) is tuned in the inner resampling loop. For this purpose the base Learner (makeLearner()) "regr.lm" is wrapped two times. First, makeFilterWrapper() is used to fuse linear regression with a feature filtering preprocessing step. Then a tuning step is added by makeTuneWrapper().
### Tuning of the percentage of selected filters in the inner loop
lrn = makeFilterWrapper(learner = "regr.lm", fw.method = "chi.squared")
ps = makeParamSet(makeDiscreteParam("fw.threshold", values = seq(0, 1, 0.2)))
ctrl = makeTuneControlGrid()
inner = makeResampleDesc("CV", iters = 3)
lrn = makeTuneWrapper(lrn, resampling = inner, par.set = ps, control = ctrl, show.info = FALSE)
### Outer resampling loop
outer = makeResampleDesc("CV", iters = 3)
r = resample(learner = lrn, task = bh.task, resampling = outer, models = TRUE, show.info = FALSE)
r
## Resample Result
## Task: BostonHousing-example
## Learner: regr.lm.filtered.tuned
## Aggr perf: mse.test.mean=23.8779697
## Runtime: 8.34047In the above example we kept the complete model (makeWrappedModel())s.
Below are some examples that show how to extract information from the model (makeWrappedModel())s.
r$models
## [[1]]
## Model for learner.id=regr.lm.filtered.tuned; learner.class=TuneWrapper
## Trained on: task.id = BostonHousing-example; obs = 338; features = 13
## Hyperparameters: fw.method=chi.squared
##
## [[2]]
## Model for learner.id=regr.lm.filtered.tuned; learner.class=TuneWrapper
## Trained on: task.id = BostonHousing-example; obs = 337; features = 13
## Hyperparameters: fw.method=chi.squared
##
## [[3]]
## Model for learner.id=regr.lm.filtered.tuned; learner.class=TuneWrapper
## Trained on: task.id = BostonHousing-example; obs = 337; features = 13
## Hyperparameters: fw.method=chi.squaredThe result of the feature selection can be extracted by function getFilteredFeatures(). Almost always all 13 features are selected.
lapply(r$models, function(x) getFilteredFeatures(x$learner.model$next.model))
## [[1]]
## [1] "crim" "zn" "indus" "nox" "rm" "age" "dis"
## [8] "rad" "tax" "ptratio" "b" "lstat"
##
## [[2]]
## [1] "crim" "zn" "indus" "chas" "nox" "rm" "age"
## [8] "dis" "rad" "tax" "ptratio" "b" "lstat"
##
## [[3]]
## [1] "crim" "zn" "indus" "nox" "rm" "age" "dis"
## [8] "rad" "tax" "ptratio" "b" "lstat"Below the tune results (TuneResult()) and optimization paths (ParamHelpers::OptPath()) are accessed.
res = lapply(r$models, getTuneResult)
res
## [[1]]
## Tune result:
## Op. pars: fw.threshold=0.2
## mse.test.mean=28.6121092
##
## [[2]]
## Tune result:
## Op. pars: fw.threshold=0
## mse.test.mean=25.1181901
##
## [[3]]
## Tune result:
## Op. pars: fw.threshold=0.4
## mse.test.mean=20.1506771
opt.paths = lapply(res, function(x) as.data.frame(x$opt.path))
opt.paths[[1]]
## fw.threshold mse.test.mean dob eol error.message exec.time
## 1 0 28.65054 1 NA <NA> 0.536
## 2 0.2 28.61211 2 NA <NA> 0.379
## 3 0.4 28.61211 3 NA <NA> 0.338
## 4 0.6 50.60313 4 NA <NA> 0.368
## 5 0.8 87.10160 5 NA <NA> 0.319
## 6 1 87.10160 6 NA <NA> 0.306In a benchmark experiment multiple learners are compared on one or several tasks (see also the section about benchmarking. Nested resampling in benchmark experiments is achieved the same way as in resampling:
makeTuneWrapper() or makeFeatSelWrapper() to generate wrapped Learner (makeLearner())s with the inner resampling strategies of your choice.benchmark() and specify the outer resampling strategies for all tasks.The inner resampling strategies should be resample descriptions (makeResampleDesc()). You can use different inner resampling strategies for different wrapped learners. For example it might be practical to do fewer subsampling or bootstrap iterations for slower learners.
If you have larger benchmark experiments you might want to have a look at the section about parallelization.
As mentioned in the section about benchmark experiments you can also use different resampling strategies for different learning tasks by passing a list of resampling descriptions or instances to benchmark().
We will see three examples to show different benchmark settings:
Below is a benchmark experiment with two data sets, datasets::iris() and mlbench::sonar(), and two Learner (makeLearner())s, kernlab::ksvm() and kknn::kknn(), that are both tuned.
As inner resampling strategies we use holdout for kernlab::ksvm() and subsampling with 3 iterations for kknn::kknn(). As outer resampling strategies we take holdout for the datasets::iris() and bootstrap with 2 iterations for the mlbench::sonar() data (sonar.task()). We consider the accuracy (acc), which is used as tuning criterion, and also calculate the balanced error rate (ber).
### List of learning tasks
tasks = list(iris.task, sonar.task)
### Tune svm in the inner resampling loop
ps = makeParamSet(
makeDiscreteParam("C", 2^(-1:1)),
makeDiscreteParam("sigma", 2^(-1:1)))
ctrl = makeTuneControlGrid()
inner = makeResampleDesc("Holdout")
lrn1 = makeTuneWrapper("classif.ksvm", resampling = inner, par.set = ps, control = ctrl,
show.info = FALSE)
### Tune k-nearest neighbor in inner resampling loop
ps = makeParamSet(makeDiscreteParam("k", 3:5))
ctrl = makeTuneControlGrid()
inner = makeResampleDesc("Subsample", iters = 3)
lrn2 = makeTuneWrapper("classif.kknn", resampling = inner, par.set = ps, control = ctrl,
show.info = FALSE)
## Loading required package: kknn
### Learners
lrns = list(lrn1, lrn2)
### Outer resampling loop
outer = list(makeResampleDesc("Holdout"), makeResampleDesc("Bootstrap", iters = 2))
res = benchmark(lrns, tasks, outer, measures = list(acc, ber), show.info = FALSE)
res
## task.id learner.id acc.test.mean ber.test.mean
## 1 iris-example classif.ksvm.tuned 0.960000 0.0375000
## 2 iris-example classif.kknn.tuned 0.920000 0.0750000
## 3 Sonar-example classif.ksvm.tuned 0.527173 0.4924242
## 4 Sonar-example classif.kknn.tuned 0.811730 0.1908513The print method for the BenchmarkResult() shows the aggregated performances from the outer resampling loop.
As you might recall, mlr offers several accessor function to extract information from the benchmark result. These are listed on the help page of BenchmarkResult() and many examples are shown on the tutorial page about benchmark experiments.
The performance values in individual outer resampling runs can be obtained by getBMRPerformances(). Note that, since we used different outer resampling strategies for the two tasks, the number of rows per task differ.
getBMRPerformances(res, as.df = TRUE)
## task.id learner.id iter acc ber
## 1 iris-example classif.ksvm.tuned 1 0.9600000 0.0375000
## 2 iris-example classif.kknn.tuned 1 0.9200000 0.0750000
## 3 Sonar-example classif.ksvm.tuned 1 0.5733333 0.4848485
## 4 Sonar-example classif.ksvm.tuned 2 0.4810127 0.5000000
## 5 Sonar-example classif.kknn.tuned 1 0.8133333 0.1958874
## 6 Sonar-example classif.kknn.tuned 2 0.8101266 0.1858151The results from the parameter tuning can be obtained through function getBMRTuneResults().
getBMRTuneResults(res)
## $`iris-example`
## $`iris-example`$classif.ksvm.tuned
## $`iris-example`$classif.ksvm.tuned[[1]]
## Tune result:
## Op. pars: C=0.5; sigma=0.5
## mmce.test.mean=0.0294118
##
##
## $`iris-example`$classif.kknn.tuned
## $`iris-example`$classif.kknn.tuned[[1]]
## Tune result:
## Op. pars: k=5
## mmce.test.mean=0.0686275
##
##
##
## $`Sonar-example`
## $`Sonar-example`$classif.ksvm.tuned
## $`Sonar-example`$classif.ksvm.tuned[[1]]
## Tune result:
## Op. pars: C=2; sigma=0.5
## mmce.test.mean=0.2428571
##
## $`Sonar-example`$classif.ksvm.tuned[[2]]
## Tune result:
## Op. pars: C=1; sigma=1
## mmce.test.mean=0.2285714
##
##
## $`Sonar-example`$classif.kknn.tuned
## $`Sonar-example`$classif.kknn.tuned[[1]]
## Tune result:
## Op. pars: k=3
## mmce.test.mean=0.0619048
##
## $`Sonar-example`$classif.kknn.tuned[[2]]
## Tune result:
## Op. pars: k=5
## mmce.test.mean=0.0761905As for several other accessor functions a clearer representation as data.frame can be achieved by setting as.df = TRUE.
getBMRTuneResults(res, as.df = TRUE)
## task.id learner.id iter C sigma mmce.test.mean k
## 1 iris-example classif.ksvm.tuned 1 0.5 0.5 0.02941176 NA
## 2 iris-example classif.kknn.tuned 1 NA NA 0.06862745 5
## 3 Sonar-example classif.ksvm.tuned 1 2.0 0.5 0.24285714 NA
## 4 Sonar-example classif.ksvm.tuned 2 1.0 1.0 0.22857143 NA
## 5 Sonar-example classif.kknn.tuned 1 NA NA 0.06190476 3
## 6 Sonar-example classif.kknn.tuned 2 NA NA 0.07619048 5It is also possible to extract the tuning results for individual tasks and learners and, as shown in earlier examples, inspect the optimization path (ParamHelpers::OptPath()).
tune.res = getBMRTuneResults(res, task.ids = "Sonar-example", learner.ids = "classif.ksvm.tuned",
as.df = TRUE)
tune.res
## task.id learner.id iter C sigma mmce.test.mean
## 1 Sonar-example classif.ksvm.tuned 1 2 0.5 0.2428571
## 2 Sonar-example classif.ksvm.tuned 2 1 1.0 0.2285714
getNestedTuneResultsOptPathDf(res$results[["Sonar-example"]][["classif.ksvm.tuned"]])Let’s see how we can do feature selection in a benchmark experiment:
### Feature selection in inner resampling loop
ctrl = makeFeatSelControlSequential(method = "sfs")
inner = makeResampleDesc("Subsample", iters = 2)
lrn = makeFeatSelWrapper("regr.lm", resampling = inner, control = ctrl, show.info = FALSE)
### Learners
lrns = list("regr.rpart", lrn)
### Outer resampling loop
outer = makeResampleDesc("Subsample", iters = 2)
res = benchmark(tasks = bh.task, learners = lrns, resampling = outer, show.info = FALSE)
res
## task.id learner.id mse.test.mean
## 1 BostonHousing-example regr.rpart 24.49331
## 2 BostonHousing-example regr.lm.featsel 26.57058The selected features can be extracted by function getBMRFeatSelResults(). By default, a nested list, with the first level indicating the task and the second level indicating the learner, is returned. If only a single learner or, as in our case, a single task is considered, setting drop = TRUE simplifies the result to a flat list.
getBMRFeatSelResults(res)
## $`BostonHousing-example`
## $`BostonHousing-example`$regr.rpart
## NULL
##
## $`BostonHousing-example`$regr.lm.featsel
## $`BostonHousing-example`$regr.lm.featsel[[1]]
## FeatSel result:
## Features (6): chas, nox, rm, dis, ptratio, lstat
## mse.test.mean=26.1954851
##
## $`BostonHousing-example`$regr.lm.featsel[[2]]
## FeatSel result:
## Features (11): crim, zn, chas, nox, rm, dis, rad, tax, ptratio, b, lstat
## mse.test.mean=18.7037963
getBMRFeatSelResults(res, drop = TRUE)
## $regr.rpart
## NULL
##
## $regr.lm.featsel
## $regr.lm.featsel[[1]]
## FeatSel result:
## Features (6): chas, nox, rm, dis, ptratio, lstat
## mse.test.mean=26.1954851
##
## $regr.lm.featsel[[2]]
## FeatSel result:
## Features (11): crim, zn, chas, nox, rm, dis, rad, tax, ptratio, b, lstat
## mse.test.mean=18.7037963You can access results for individual learners and tasks and inspect them further.
feats = getBMRFeatSelResults(res, learner.id = "regr.lm.featsel", drop = TRUE)
### Selected features in the first outer resampling iteration
feats[[1]]$x
## [1] "chas" "nox" "rm" "dis" "ptratio" "lstat"
### Resampled performance of the selected feature subset on the first inner training set
feats[[1]]$y
## mse.test.mean
## 26.19549As for tuning, you can extract the optimization paths. The resulting data.frames contain, among others, binary columns for all features, indicating if they were included in the linear regression model, and the corresponding performances. analyzeFeatSelResult() gives a clearer overview.
opt.paths = lapply(feats, function(x) as.data.frame(x$opt.path))
head(opt.paths[[1]])
## crim zn indus chas nox rm age dis rad tax ptratio b lstat mse.test.mean
## 1 0 0 0 0 0 0 0 0 0 0 0 0 0 81.15880
## 2 1 0 0 0 0 0 0 0 0 0 0 0 0 74.84448
## 3 0 1 0 0 0 0 0 0 0 0 0 0 0 73.49838
## 4 0 0 1 0 0 0 0 0 0 0 0 0 0 64.07003
## 5 0 0 0 1 0 0 0 0 0 0 0 0 0 80.55822
## 6 0 0 0 0 1 0 0 0 0 0 0 0 0 64.94483
## dob eol error.message exec.time
## 1 1 2 <NA> 0.021
## 2 2 2 <NA> 0.029
## 3 2 2 <NA> 0.028
## 4 2 2 <NA> 0.029
## 5 2 2 <NA> 0.031
## 6 2 2 <NA> 0.033
analyzeFeatSelResult(feats[[1]])
## Features : 6
## Performance : mse.test.mean=26.1954851
## chas, nox, rm, dis, ptratio, lstat
##
## Path to optimum:
## - Features: 0 Init : Perf = 81.159 Diff: NA *
## - Features: 1 Add : lstat Perf = 37.622 Diff: 43.537 *
## - Features: 2 Add : rm Perf = 30.404 Diff: 7.2183 *
## - Features: 3 Add : ptratio Perf = 27.747 Diff: 2.6563 *
## - Features: 4 Add : dis Perf = 27.193 Diff: 0.55418 *
## - Features: 5 Add : nox Perf = 26.401 Diff: 0.79202 *
## - Features: 6 Add : chas Perf = 26.195 Diff: 0.20563 *
##
## Stopped, because no improving feature was found.Here is a minimal example for feature filtering with tuning of the feature subset size.
### Feature filtering with tuning in the inner resampling loop
lrn = makeFilterWrapper(learner = "regr.lm", fw.method = "chi.squared")
ps = makeParamSet(makeDiscreteParam("fw.abs", values = seq_len(getTaskNFeats(bh.task))))
ctrl = makeTuneControlGrid()
inner = makeResampleDesc("CV", iter = 2)
lrn = makeTuneWrapper(lrn, resampling = inner, par.set = ps, control = ctrl,
show.info = FALSE)
### Learners
lrns = list("regr.rpart", lrn)
### Outer resampling loop
outer = makeResampleDesc("Subsample", iter = 3)
res = benchmark(tasks = bh.task, learners = lrns, resampling = outer, show.info = FALSE)
res
## task.id learner.id mse.test.mean
## 1 BostonHousing-example regr.rpart 22.44007
## 2 BostonHousing-example regr.lm.filtered.tuned 23.84994### Performances on individual outer test data sets
getBMRPerformances(res, as.df = TRUE)
## task.id learner.id iter mse
## 1 BostonHousing-example regr.rpart 1 23.08789
## 2 BostonHousing-example regr.rpart 2 24.43105
## 3 BostonHousing-example regr.rpart 3 19.80127
## 4 BostonHousing-example regr.lm.filtered.tuned 1 25.78723
## 5 BostonHousing-example regr.lm.filtered.tuned 2 26.03608
## 6 BostonHousing-example regr.lm.filtered.tuned 3 19.72651