-
-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathsolutions.qmd
2369 lines (1826 loc) · 83.9 KB
/
solutions.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
aliases:
- "/solutions.html"
---
# Solutions to exercises {#sec-solutions}
::: {.content-visible when-format="html"}
{{< include ../../common/_setup.qmd >}}
<!-- ENSURE ONLINE ONLY AND REFERENCE IN PREFACE -->
## Solutions to @sec-basics
1. Train a classification model with the `classif.rpart` learner on the "Pima Indians Diabetes" dataset.
Do this without using `tsk("pima")`, and instead by constructing a task from the dataset in the `mlbench`-package: `data(PimaIndiansDiabetes2, package = "mlbench")`.
Make sure to define the `pos` outcome as positive class.
Train the model on a random 80% subset of the given data and evaluate its performance with the classification error measure on the remaining data.
(Note that the data set has NAs in its features.
You can either rely on `rpart`'s capability to handle them internally ('surrogate splits') or remove them from the initial `data.frame` by using `na.omit`).
```{r}
set.seed(1)
data(PimaIndiansDiabetes2, package = "mlbench")
task = as_task_classif(PimaIndiansDiabetes2, target = "diabetes", positive = "pos")
splits = partition(task, ratio = 0.8)
splits
learner = lrn("classif.rpart" , predict_type = "prob")
learner
learner$train(task, row_ids = splits$train)
learner$model
prediction = learner$predict(task, row_ids = splits$test)
as.data.table(prediction)
measure = msr("classif.ce")
prediction$score(measure)
```
2. Calculate the true positive, false positive, true negative, and false negative rates of the predictions made by the model in Exercise 1.
Try to solve this in two ways: (a) Using `mlr3measures`-predefined measure objects, and (b) without using `mlr3` tools by directly working on the ground truth and prediction vectors.
Compare the results.
```{r}
# true positive rate
prediction$score(msr("classif.tpr"))
# false positive rate
prediction$score(msr("classif.fpr"))
# true negative rate
prediction$score(msr("classif.tnr"))
# false negative rate
prediction$score(msr("classif.fnr"))
```
```{r}
# true positives
TP = sum(prediction$truth == "pos" & prediction$response == "pos")
# false positives
FP = sum(prediction$truth == "neg" & prediction$response == "pos")
# true negatives
TN = sum(prediction$truth == "neg" & prediction$response == "neg")
# false negatives
FN = sum(prediction$truth == "pos" & prediction$response == "neg")
# true positive rate
TP / (TP + FN)
# false positive rate
FP / (FP + TN)
# true negative rate
TN / (TN + FP)
# false negative rate
FN / (FN + TP)
```
The results are the same.
3. Change the threshold of the model from Exercise 1 such that the false negative rate is lower.
What is one reason you might do this in practice?
```{r}
# confusion matrix with threshold 0.5
prediction$confusion
prediction$set_threshold(0.3)
# confusion matrix with threshold 0.3
prediction$confusion
# false positive rate
prediction$score(msr("classif.fpr"))
# false negative rate
prediction$score(msr("classif.fnr"))
```
With a false negative rate of 0.38, we miss a lot of people who have diabetes but are predicted to not have it.
This could give a false sense of security.
By lowering the threshold, we can reduce the false negative rate.
## Solutions to @sec-performance
1. Apply a repeated cross-validation resampling strategy on `tsk("mtcars")` and evaluate the performance of `lrn("regr.rpart")`.
Use five repeats of three folds each.
Calculate the MSE for each iteration and visualize the result.
Finally, calculate the aggregated performance score.
We start by instantiating our task and learner as usual:
```{r}
set.seed(3)
task = tsk("mtcars")
learner = lrn("regr.rpart")
```
We can instantiate a temporary resampling on the task to illustrate how it assigns observations across the 5 repeats (column `rep`) and 3 folds:
```{r}
resampling = rsmp("repeated_cv", repeats = 5, folds = 3)
resampling$instantiate(task)
resampling$instance
```
Note instantiating manually is not necessary when using `resample()`, as it automatically instantiates the resampling for us, so we pass it a new resampling which has not been instantiated:
```{r}
resampling = rsmp("repeated_cv", repeats = 5, folds = 3)
rr = resample(task, learner, resampling)
```
Now we can `$score()` the resampling with the MSE measure across each of the 5x3 resampling iterations:
```{r}
scores = rr$score(msr("regr.mse"))
scores
```
We can manually calculate these scores since `rr` contains all the individual predictions.
The `$predictions()` method returns a list of predictions for each iteration, which we can use to calculate the MSE for the first iteration:
```{r}
preds = rr$predictions()
pred_1 = as.data.table(preds[[1]])
pred_1[, list(rmse = mean((truth - response)^2))]
```
To visualize the results, we can use `ggplot2` directly on the `scores` object, which behaves like any other `data.table`:
```{r}
library(ggplot2)
# Barchart of the per-iteration scores
ggplot(scores, aes(x = iteration, y = regr.mse)) +
geom_col() +
theme_minimal()
# Boxplot of the scores
ggplot(scores, aes(x = regr.mse)) +
geom_boxplot() +
scale_y_continuous(breaks = 0, labels = NULL) +
theme_minimal()
```
Alternatively, the `autoplot()` function provides defaults for the `ResampleResult` object.
Note that it internally scores the resampling using the MSE for regression tasks per default.
```{r}
autoplot(rr)
autoplot(rr, type = "histogram")
```
The aggregate score is the mean of the MSE scores across all iterations, which we can calculate using `$aggregate()` or by manually averaging the scores we stored before:
```{r}
mean(scores$regr.mse)
rr$aggregate(msr("regr.mse"))
```
2. Use `tsk("spam")` and five-fold CV to benchmark `lrn("classif.ranger")`, `lrn("classif.log_reg")`, and `lrn("classif.xgboost", nrounds = 100)` with respect to AUC.
Which learner appears to perform best? How confident are you in your conclusion?
Think about the stability of results and investigate this by re-rerunning the experiment with different seeds.
What can be done to improve this?
First we instantiate our learners with their initial parameters, setting the `predict_type = "prob"` once for all of them using `lrns()`.
We then set the `nrounds` parameter for XGBoost to 100 and construct a resampling object for 5-fold CV:
```{r}
set.seed(3)
task = tsk("spam")
learners = lrns(c("classif.ranger", "classif.log_reg", "classif.xgboost"),
predict_type = "prob")
learners$classif.xgboost$param_set$values$nrounds = 100
resampling = rsmp("cv", folds = 5)
```
We could have alternatively instantiated the learners like this, but would have needed to repeat the `predict_type = "prob"` argument multiple times.
```{r, eva=FALSE}
learners = list(
lrn("classif.ranger", predict_type = "prob"),
lrn("classif.log_reg", predict_type = "prob"),
lrn("classif.xgboost", nrounds = 100, predict_type = "prob")
)
```
Next we can construct a benchmark design grid with the instantiated objects using `benchmark_grid()`:
```{r}
design = benchmark_grid(
tasks = task,
learners = learners,
resamplings = resampling
)
design
```
To perform the benchmark, we use the aptly named `benchmark()` function:
```{r, warning=FALSE}
bmr = benchmark(design)
bmr
```
And visualize the results as a boxplot:
```{r}
autoplot(bmr, measure = msr("classif.auc"))
```
In this example,`lrn("classif.xgboost")` outperforms `lrn("classif.ranger")`, and both outperform `lrn("classif.log_reg")`.
Naturally this is only a visual inspection of the results --- proper statistical testing of benchmark results can be conducted using the `mlr3benchmark` package, but for the purposes of this exercise a plot suffices.
When we re-run the same experiment with a different seed, we get a slightly different result.
```{r, warning=FALSE}
set.seed(3235)
resampling = rsmp("cv", folds = 5)
design = benchmark_grid(
tasks = task,
learners = learners,
resamplings = resampling
)
bmr = benchmark(design)
autoplot(bmr, measure = msr("classif.auc"))
```
The overall trend remains about the same, but do we trust these results?
Note that we applied both `lrn("classif.log_reg")` and `lrn("classif.ranger")` with their initial parameters.
While `lrn("classif.log_reg")` does not have any hyperparameters to tune, `lrn("classif.ranger")` does have several, at least one of which is usually tuned (`mtry`).
In case of `lrn("classif.xgboost")` however, we arbitrarily chose `nrounds = 100` rather than using the learner with its initial value of `nrounds = 1`, which would be equivalent to a single tree decision tree.
To make any generalizations based on this experiment, we need to properly tune all relevant hyperparmeters in a systematic way.
We cover this and more in @sec-optimization.
3. A colleague reports a 93.1% classification accuracy using `lrn("classif.rpart")` on `tsk("penguins_simple")`.
You want to reproduce their results and ask them about their resampling strategy.
They said they used a custom three-fold CV with folds assigned as `factor(task$row_ids %% 3)`.
See if you can reproduce their results.
We make use of the `custom_cv` resampling strategy here:
```{r}
task = tsk("penguins_simple")
rsmp_cv = rsmp("custom_cv")
```
We apply the rule to assign resampling folds we were provided with: Every third observation is assigned to the same fold:
```{r}
rsmp_cv$instantiate(task = task, f = factor(task$row_ids %% 3))
str(rsmp_cv$instance)
```
We are now ready to conduct the resampling and aggregate results:
```{r}
rr = resample(
task = task,
learner = lrn("classif.rpart"),
resampling = rsmp_cv
)
rr$aggregate(msr("classif.acc"))
```
Converting to percentages and rounding to one decimal place, we get the same result as our colleague!
Luckily they kept track of their resampling to ensure their results were reproducible.
4. (*) Program your own ROC plotting function without using `mlr3`'s `autoplot()` function. The signature of your function should be `my_roc_plot(task, learner, train_indices, test_indices)`.
Your function should use the `$set_threshold()` method of `Prediction`, as well as `mlr3measures`.
Here is a function to calculate the true positive rate (TPR, *Sensitivity*) and false positive rate (FPR, *1 - Specificity*) in a loop across a grid of probabilities.
These are set as thresholds with the `$set_threshold()` method of the `PredictionClassif` object.
This way we construct the ROC curve by iteratively calculating its x and y values, after which we can use `geom_step()` to draw a step function.
Note that we do not need to re-train the learner, we merely adjust the threshold applied to the predictions we made at the top of the function
```{r}
my_roc_plot = function(task, learner, train_indices, test_indices) {
# Train learner, predict once.
learner$train(task, train_indices)
pred = learner$predict(task, test_indices)
# Positive class predictions from prediction matrix
pos_pred = pred$prob[, which(colnames(pred$prob) == task$positive)]
# Set a grid of probabilities to evaluate at.
prob_grid = seq(0, 1, 0.001)
# For each possible threshold, calculate TPR,
# FPR + aggregate to data.table
grid = data.table::rbindlist(lapply(prob_grid, \(thresh) {
pred$set_threshold(thresh)
data.table::data.table(
thresh = thresh,
# y axis == sensitivity == TPR
tpr = mlr3measures::tpr(
truth = pred$truth, response = pred$response,
positive = task$positive),
# x axis == 1 - specificity == 1 - TNR == FPR
fpr = mlr3measures::fpr(
truth = pred$truth, response = pred$response,
positive = task$positive)
)
}))
# Order descending by threshold to use ggplot2::geom_step
data.table::setorderv(grid, cols = "thresh", order = -1)
ggplot2::ggplot(grid, ggplot2::aes(x = fpr, y = tpr)) +
# Step function starting with (h)orizontal, then (v)ertical
ggplot2::geom_step(direction = "hv") +
ggplot2::coord_equal() +
ggplot2::geom_abline(linetype = "dashed") +
ggplot2::theme_minimal() +
ggplot2::labs(
title = "My Custom ROC Curve",
subtitle = sprintf("%s on %s", learner$id, task$id),
x = "1 - Specificity", y = "Sensitivity",
caption = sprintf("n = %i. Test set: %i", task$nrow, length(test_indices))
)
}
```
We try our function using `tsk("sonar")` and `lrn("classif.ranger")` learner with 100 trees.
We set `predict_type = "prob"` since we need probability predictions to apply thresholds, rather than hard class predictions.
```{r}
set.seed(3)
# Setting up example task and learner for testing
task = tsk("sonar")
learner = lrn("classif.ranger", num.trees = 100, predict_type = "prob")
split = partition(task)
my_roc_plot(task, learner, split$train, split$test)
```
We can compare it with the pre-built plot function in `mlr3viz`:
```{r}
learner$train(task, split$train)
pred = learner$predict(task, split$test)
autoplot(pred, type = "roc")
```
Note the slight discrepancy between the two curves.
This is caused by some implementation differences used by the `precrec` which is used for this functionality in `mlr3viz`.
There are different approaches to drawing ROC curves, and our implementation above is one of the simpler ones!
## Solutions to @sec-optimization
1. Tune the `mtry`, `sample.fraction`, and `num.trees` hyperparameters of `lrn("regr.ranger")` on `tsk("mtcars")`.
Use a simple random search with 50 evaluations.
Evaluate with a three-fold CV and the root mean squared error.
Visualize the effects that each hyperparameter has on the performance via simple marginal plots, which plot a single hyperparameter versus the cross-validated MSE.
```{r}
set.seed(1)
task = tsk("mtcars")
learner = lrn("regr.ranger",
mtry = to_tune(1, 10),
sample.fraction = to_tune(0.5, 1),
num.trees = to_tune(100, 500)
)
instance = ti(
learner = learner,
task = task,
resampling = rsmp("cv", folds = 3),
measure = msr("regr.rmse"),
terminator = trm("evals", n_evals = 50)
)
tuner = tnr("random_search", batch_size = 10)
tuner$optimize(instance)
# all evaluations
as.data.table(instance$archive)
# best configuration
instance$result
# incumbent plot
autoplot(instance, type = "incumbent")
# marginal plots
autoplot(instance, type = "marginal", cols_x = "mtry")
autoplot(instance, type = "marginal", cols_x = "sample.fraction")
autoplot(instance, type = "marginal", cols_x = "num.trees")
```
2. Evaluate the performance of the model created in Exercise 1 with nested resampling.
Use a holdout validation for the inner resampling and a three-fold CV for the outer resampling.
```{r}
set.seed(1)
task = tsk("mtcars")
learner = lrn("regr.ranger",
mtry = to_tune(1, 10),
sample.fraction = to_tune(0.5, 1),
num.trees = to_tune(100, 500)
)
at = auto_tuner(
tuner = tnr("random_search", batch_size = 50),
learner = learner,
resampling = rsmp("holdout"),
measure = msr("regr.rmse"),
terminator = trm("evals", n_evals = 50)
)
rr = resample(task, at, rsmp("cv", folds = 3))
rr$aggregate(msr("regr.rmse"))
```
The `"rmse"` is slightly higher than the one we obtained in Exercise 1.
We see that the performance estimated while tuning overestimates the true performance
3. Tune and benchmark an XGBoost model against a logistic regression (without tuning the latter) and determine which has the best Brier score.
Use `mlr3tuningspaces` and nested resampling, try to pick appropriate inner and outer resampling strategies that balance computational efficiency vs. stability of the results.
```{r}
#| warning: false
set.seed(1)
task = tsk("sonar")
lrn_log_reg = lrn("classif.log_reg", predict_type = "prob")
# load xgboost learner with search space
lrn_xgboost = lts(lrn("classif.xgboost", predict_type = "prob"))
# search space for xgboost
lrn_xgboost$param_set$search_space()
at_xgboost = auto_tuner(
tuner = tnr("random_search", batch_size = 50),
learner = lrn_xgboost,
resampling = rsmp("cv", folds = 3),
measure = msr("classif.bbrier"),
terminator = trm("evals", n_evals = 50)
)
design = benchmark_grid(
tasks = task,
learners = list(lrn_log_reg, at_xgboost),
resamplings = rsmp("cv", folds = 5)
)
bmr = benchmark(design)
bmr$aggregate(msr("classif.bbrier"))
```
We use the `r ref("lts()")` function from the `r mlr3tuningspaces` package to load the `lrn("classif.xgboost")` with a search space.
The learner is wrapped in an `r ref("auto_tuner()")`, which is then benchmarked against the `lrn("classif.log_reg")`.
4. (*) Write a function that implements an iterated random search procedure that drills down on the optimal configuration by applying random search to iteratively smaller search spaces.
Your function should have seven inputs: `task`, `learner`, `search_space`, `resampling`, `measure`, `random_search_stages`, and `random_search_size`.
You should only worry about programming this for fully numeric and bounded search spaces that have no dependencies.
In pseudo-code:
(1) Create a random design of size `random_search_size` from the given search space and evaluate the learner on it.
(2) Identify the best configuration.
(3) Create a smaller search space around this best config, where you define the new range for each parameter as: `new_range[i] = (best_conf[i] - 0.25 * current_range[i], best_conf[i] + 0.25*current_range[i])`.
Ensure that this `new_range` respects the initial bound of the original `search_space` by taking the `max()` of the new and old lower bound, and the `min()` of the new and the old upper bound ("clipping").
(4) Iterate the previous steps `random_search_stages` times and at the end return the best configuration you have ever evaluated.
```{r}
library(mlr3misc)
focus_search = function(task, learner, search_space, resampling, measure, random_search_stages, random_search_size) {
repeat {
# tune learner on random design
instance = tune(
tuner = tnr("random_search", batch_size = random_search_size),
learner = learner,
task = task,
resampling = resampling,
measure = measure,
search_space = search_space,
terminator = trm("evals", n_evals = random_search_size),
)
# identify the best configuration
best_config = instance$result_x_search_space
# narrow search space
params = map(search_space$subspaces(), function(subspace) {
best = best_config[[subspace$ids()]]
lower = subspace$lower
upper = subspace$upper
new_lower = best - 0.25 * lower
new_upper = best + 0.25 * upper
if ("ParamInt" %in% subspace$class) {
new_lower = round(new_lower)
new_upper = round(new_upper)
p_int(max(new_lower, lower), min(new_upper, upper), tags = subspace$tags[[1]])
} else {
p_dbl(max(new_lower, lower), min(new_upper, upper), tags = subspace$tags[[1]])
}
})
search_space = invoke(ps, .args = params)
random_search_stages = random_search_stages - 1
if (!random_search_stages) return(best_config)
}
}
focus_search(
task = tsk("mtcars"),
learner = lrn("regr.xgboost"),
search_space = ps(
eta = p_dbl(lower = 0.01, upper = 0.5),
max_depth = p_int(lower = 1, upper = 10),
nrounds = p_int(lower = 10, upper = 100)
),
resampling = rsmp("cv", folds = 3),
measure = msr("regr.rmse"),
random_search_stages = 2,
random_search_size = 50
)
```
As a stretch goal, look into `mlr3tuning`'s internal source code and turn your function into an R6 class inheriting from the `TunerBatch` class -- test it out on a learner of your choice.
```{r}
library(R6)
library(mlr3tuning)
TunerBatchFocusSearch = R6Class("TunerFocusSearch",
inherit = TunerBatch,
public = list(
initialize = function() {
param_set = ps(
random_search_stages = p_int(lower = 1L, tags = "required"),
random_search_size = p_int(lower = 1L, tags = "required")
)
param_set$values = list(random_search_stages = 10L, random_search_size = 50L)
super$initialize(
id = "focus_search",
param_set = param_set,
param_classes = c("ParamLgl", "ParamInt", "ParamDbl", "ParamFct"),
properties = c("dependencies", "single-crit", "multi-crit"),
label = "Focus Search",
man = "mlr3tuning::mlr_tuners_focus_search"
)
}
),
private = list(
.optimize = function(inst) {
pv = self$param_set$values
search_space = inst$search_space
for (i in seq(pv$random_search_stages)) {
# evaluate random design
xdt = generate_design_random(search_space, pv$random_search_size)$data
inst$eval_batch(xdt)
# identify the best configuration
best_config = inst$archive$best(batch = i)
# narrow search space
params = map(search_space$subspaces(), function(subspace) {
best = best_config[[subspace$ids()]]
lower = subspace$lower
upper = subspace$upper
new_lower = best - 0.25 * lower
new_upper = best + 0.25 * upper
if ("ParamInt" %in% subspace$class) {
new_lower = round(new_lower)
new_upper = round(new_upper)
p_int(max(new_lower, lower), min(new_upper, upper), tags = subspace$tags[[1]])
} else {
p_dbl(max(new_lower, lower), min(new_upper, upper), tags = subspace$tags[[1]])
}
})
search_space = invoke(ps, .args = params)
xdt = generate_design_random(search_space, pv$random_search_size)$data
inst$eval_batch(xdt)
}
}
)
)
mlr_tuners$add("focus_search", TunerBatchFocusSearch)
instance = ti(
task = tsk("mtcars"),
learner = lrn("regr.xgboost"),
search_space = ps(
eta = p_dbl(lower = 0.01, upper = 0.5),
max_depth = p_int(lower = 1, upper = 10),
nrounds = p_int(lower = 10, upper = 100)
),
resampling = rsmp("cv", folds = 3),
measure = msr("regr.rmse"),
terminator = trm("none")
)
tuner = tnr("focus_search", random_search_stages = 2, random_search_size = 50)
tuner$optimize(instance)
```
## Solutions to @sec-optimization-advanced
1. Tune the `mtry`, `sample.fraction`, and `num.trees` hyperparameters of `lrn("regr.ranger")` on `tsk("mtcars")` and evaluate this with a three-fold CV and the root mean squared error (same as @sec-optimization, Exercise 1).
Use `tnr("mbo")` with 50 evaluations.
Compare this with the performance progress of a random search run from @sec-optimization, Exercise 1.
Plot the progress of performance over iterations and visualize the spatial distribution of the evaluated hyperparameter configurations for both algorithms.
We first construct the learner, task, resampling, measure and terminator and then the instance.
```{r}
library(mlr3mbo)
library(bbotk)
library(data.table)
library(ggplot2)
library(viridisLite)
set.seed(5)
learner = lrn("regr.ranger",
mtry = to_tune(1, 10),
sample.fraction = to_tune(0.5, 1),
num.trees = to_tune(100, 500)
)
task = tsk("mtcars")
resampling = rsmp("cv", folds = 3)
measure = msr("regr.rmse")
terminator = trm("evals", n_evals = 50)
instance_rs = ti(
learner = learner,
task = task,
resampling = resampling,
measure = measure,
terminator = terminator
)
```
Using a random search results in the following final performance:
```{r, warning = FALSE}
tuner = tnr("random_search", batch_size = 50)
tuner$optimize(instance_rs)
```
We then construct a new instance and optimize it via Bayesian Optimization (BO) using `tnr("mbo")` in its default configuration (see also `r ref("mbo_defaults")`):
```{r, warning = FALSE}
instance_bo = ti(
learner = learner,
task = task,
resampling = resampling,
measure = measure,
terminator = terminator
)
tuner = tnr("mbo")
tuner$optimize(instance_bo)
```
We then add relevant information to the archives of the instances so that we can combine their data and use this data for generating the desired plots.
```{r}
instance_rs$archive$data[, iteration := seq_len(.N)]
instance_rs$archive$data[, best_rmse := cummin(regr.rmse)]
instance_rs$archive$data[, method := "Random Search"]
instance_bo$archive$data[, iteration := seq_len(.N)]
instance_bo$archive$data[, best_rmse := cummin(regr.rmse)]
instance_bo$archive$data[, method := "BO"]
plot_data = rbind(instance_rs$archive$data[, c("iteration", "best_rmse", "method")],
instance_bo$archive$data[, c("iteration", "best_rmse", "method")])
ggplot(aes(x = iteration, y = best_rmse, colour = method), data = plot_data) +
geom_step() +
scale_colour_manual(values = viridis(2, end = 0.8)) +
labs(x = "Number of Configurations", y = "Best regr.rmse", colour = "Method") +
theme_minimal() +
theme(legend.position = "bottom")
```
We see that BO manages to slightly outperform the random search.
Ideally, we would replicate running both optimizers multiple times with different random seeds and visualize their average performance along with a dispersion measure to properly take randomness of the optimization process into account.
We could even use the same first few random samples as the initial design in BO to allow for a fairer comparison.
To visualize the spatial distribution of the evaluated hyperparameter configurations we will plot for each evaluated configuration the number of trees on the x-axis and the sample fraction on the y-axis.
The label of each point corresponds to the mtry parameter directly.
```{r}
relevant_columns = c("mtry", "sample.fraction", "num.trees", "iteration", "method")
plot_data_sampling = rbind(
instance_rs$archive$data[, ..relevant_columns, with = FALSE],
instance_bo$archive$data[, ..relevant_columns, with = FALSE])
ggplot(
aes(x = num.trees, y = sample.fraction, colour = method, label = mtry),
data = plot_data_sampling
) +
scale_colour_manual(values = viridis(2, end = 0.8)) +
geom_point(size = 0) +
geom_text() +
guides(colour = guide_legend(title = "Method", override.aes = aes(label = "", size = 2))) +
theme_minimal() +
theme(legend.position = "bottom")
```
We observe that the random search samples uniformly at random -- as expected.
BO, however, focuses on regions of the search space with a high number of trees between 350 and 400, a high sample fraction and mtry values of around 5 to 8.
This is also the region where the final result returned by BO is located.
Nevertheless, BO also explores the search space, i.e., along the line of a high sample fraction close to 1.
2. Minimize the 2D Rastrigin function $f: [-5.12, 5.12] \times [-5.12, 5.12] \rightarrow \mathbb{R}$, $\mathbf{x} \mapsto 10 D+\sum_{i=1}^D\left[x_i^2-10 \cos \left(2 \pi x_i\right)\right]$, $D = 2$ via BO (standard sequential single-objective BO via `bayesopt_ego()`) using the lower confidence bound with `lambda = 1` as acquisition function and `"NLOPT_GN_ORIG_DIRECT"` via `opt("nloptr")` as acquisition function optimizer.
Use a budget of 40 function evaluations.
Run this with both the "default" Gaussian process surrogate model with Matérn 5/2 kernel, and the "default" random forest surrogate model.
Compare their anytime performance (similarly as in @fig-bayesian-sinusoidal_bo_rs).
You can construct the surrogate models with default settings using:
```{r}
surrogate_gp = srlrn(default_gp())
surrogate_rf = srlrn(default_rf())
```
We first construct the function, making use of efficient evaluation operating on a `data.table` directly.
We then wrap this function in the corresponding `r ref("ObjectiveRFunDt")` objective class and construct the instance.
```{r}
rastrigin = function(xdt) {
D = ncol(xdt)
y = 10 * D + rowSums(xdt^2 - (10 * cos(2 * pi * xdt)))
data.table(y = y)
}
objective = ObjectiveRFunDt$new(
fun = rastrigin,
domain = ps(x1 = p_dbl(lower = -5.12, upper = 5.12),
x2 = p_dbl(lower = -5.12, upper = 5.12)),
codomain = ps(y = p_dbl(tags = "minimize")),
id = "rastrigin2D")
instance = OptimInstanceSingleCrit$new(
objective = objective,
terminator = trm("evals", n_evals = 40))
```
We then construct the surrogates as well as the acquisition function and acquisition function optimizer (we will terminate the acquisition function optimization once optimization process stagnates by `1e-5` over the last 100 iterations) and construct the two BO optimizers.
```{r}
surrogate_gp = srlrn(default_gp())
surrogate_rf = srlrn(default_rf())
acq_function = acqf("cb", lambda = 1)
acq_optimizer = acqo(opt("nloptr", algorithm = "NLOPT_GN_ORIG_DIRECT"),
terminator = trm("stagnation", iters = 100, threshold = 1e-5))
optimizer_gp = opt("mbo",
loop_function = bayesopt_ego,
surrogate = surrogate_gp,
acq_function = acq_function,
acq_optimizer = acq_optimizer)
optimizer_rf = opt("mbo",
loop_function = bayesopt_ego,
surrogate = surrogate_rf,
acq_function = acq_function,
acq_optimizer = acq_optimizer
)
```
We will use the following initial design for both optimizers:
```{r}
initial_design = data.table(
x1 = c(-3.95, 1.16, 3.72, -1.39, -0.11, 5.00, -2.67, 2.44),
x2 = c(1.18, -3.93, 3.74, -1.37, 5.02, -0.09, -2.65, 2.46)
)
instance$eval_batch(initial_design)
```
We then proceed to optimize the instance with each of the two optimizers and make sure to extract the relevant data from the archive of the instance.
```{r, warning = FALSE}
optimizer_gp$optimize(instance)
gp_data = instance$archive$data
gp_data[, y_min := cummin(y)]
gp_data[, iteration := seq_len(.N)]
gp_data[, surrogate := "Gaussian Process"]
```
```{r, warning = FALSE}
instance$archive$clear()
instance$eval_batch(initial_design)
optimizer_rf$optimize(instance)
rf_data = instance$archive$data
rf_data[, y_min := cummin(y)]
rf_data[, iteration := seq_len(.N)]
rf_data[, surrogate := "Random forest"]
```
We then combine the data and use it to generate the desired plot:
```{r}
plot_data = rbind(gp_data, rf_data)
ggplot(aes(x = iteration, y = y_min, colour = surrogate), data = plot_data) +
geom_step() +
scale_colour_manual(values = viridis(2, end = 0.8)) +
labs(y = "Best Observed Function Value", x = "Number of Function Evaluations",
colour = "Surrogate Model") +
theme_minimal() +
theme(legend.position = "bottom")
```
As expected, we observe that the BO algorithm with the Gaussian Process surrogate appears to outperform the random forest surrogate counterpart.
However, ideally we would replicate running each algorithm using different random seeds and visualize the average performance along with some dispersion measure to properly take randomness of the optimization process into account.
3. Minimize the following function: $f: [-10, 10] \rightarrow \mathbb{R}^2, x \mapsto \left(x^2, (x - 2)^2\right)$ with respect to both objectives.
Use the ParEGO algorithm.
Construct the objective function using the `r ref("ObjectiveRFunMany")` class.
Terminate the optimization after a runtime of 100 evals.
Plot the resulting Pareto front and compare it to the analytical solution, $y_2 = \left(\sqrt{y_1}-2\right)^2$ with $y_1$ ranging from $0$ to $4$.
We first construct the function, wrap it in the objective and then create the instance.
```{r}
fun = function(xss) {
evaluations = lapply(xss, FUN = function(xs) {
list(y1 = xs$x ^ 2, y2 = (xs$x - 2)^2)
})
rbindlist(evaluations)
}
objective = ObjectiveRFunMany$new(
fun = fun,
domain = ps(x = p_dbl(lower = -10, upper = 10)),
codomain = ps(y1 = p_dbl(tags = "minimize"), y2 = p_dbl(tags = "minimize")),
id = "schaffer1")
instance = OptimInstanceMultiCrit$new(
objective = objective,
terminator = trm("evals", n_evals = 100)
)
```
As a surrogate we will use a random forest.
ParEGO is a scalarization based multi-objective BO algorithm and therefore we use the Expected Improvement as acquisition function.
We will use the same acquisition functon optimizer as earlier.
```{r}
surrogate = srlrn(default_rf())
acq_function = acqf("ei")
acq_optimizer = acqo(opt("nloptr", algorithm = "NLOPT_GN_ORIG_DIRECT"),
terminator = trm("stagnation", iters = 100, threshold = 1e-5))
optimizer = opt("mbo",
loop_function = bayesopt_parego,
surrogate = surrogate,
acq_function = acq_function,
acq_optimizer = acq_optimizer
)
```
We then optimize the instance:
```{r, warning = FALSE}
optimizer$optimize(instance)
```
Finally, we visualize the resulting Pareto front (in black) and its analytical counterpart (in darkgrey).
```{r}
true_pareto = data.table(y1 = seq(from = 0, to = 4, length.out = 1001))
true_pareto[, y2 := (sqrt(y1) - 2) ^2]
ggplot(aes(x = y1, y = y2), data = instance$archive$best()) +
geom_point() +
geom_line(data = true_pareto, colour = "darkgrey") +
geom_step(direction = "hv") +
labs(x = expression(y[1]), y = expression(y[2])) +
theme_minimal()
```
## Solutions to @sec-feature-selection
1. Compute the correlation filter scores on `tsk("mtcars")` and use the filter to select the five features most strongly correlated with the target.
Resample `lrn("regr.kknn")` on both the full dataset and the reduced one, and compare both performances based on 10-fold CV with respect to MSE.
NB: Here, we have performed the feature filtering outside of CV, which is generally not a good idea as it biases the CV performance estimation.
To do this properly, filtering should be embedded inside the CV via pipelines -- try to come back to this exercise after you read @sec-pipelines-nonseq to implement this with less bias.
```{r}
set.seed(1)
task = tsk("mtcars")
filter = flt("correlation")
filter$calculate(task)
# sorted filter scores
filter$scores
# subset task to 5 most correlated features
task$select(names(head(filter$scores, 5)))
task
design = benchmark_grid(
tasks = list(task, tsk("mtcars")),
learners = lrn("regr.kknn"),
resamplings = rsmp("cv", folds = 10)
)
bmr = benchmark(design)
bmr$aggregate(msr("regr.mse"))
```
The `"mse"` is much lower on the filtered task.
2. Apply backward selection to `tsk("penguins")` with `lrn("classif.rpart")` and holdout resampling by the classification accuracy measure.
Compare the results with those in @sec-fs-wrapper-example by also running the forward selection from that section.
Do the selected features differ?
Which feature selection method reports a higher classification accuracy in its `$result`?
```{r}
set.seed(1)
fselector_sbs = fs("sequential", strategy = "sbs")
instance_sbs = fsi(
task = tsk("penguins"),
learner = lrn("classif.rpart"),
resampling = rsmp("holdout"),
measure = msr("classif.acc"),
terminator = trm("none")
)
fselector_sbs$optimize(instance_sbs)
# optimization path sbs
fselector_sbs$optimization_path(instance_sbs)
instance_sbs$result
fselector_sfs = fs("sequential", strategy = "sfs")
instance_sfs = fsi(