library("parallelMap") library("ParamHelpers") library("mlr") library("mlrCPO") library("ecr") library("mosmafs") library("magrittr") library("ggplot2") set.seed(8008135) options(width = 80) cores <- parallel::detectCores() if (Sys.getenv("FASTVIGNETTE") != "true") { cores <- min(cores, 2) } if (.Platform$OS.type == "windows") { parallelStartSocket(cores, show.info = FALSE) parallelLibrary("mlr") } else { parallelStartMulticore(cores, show.info = FALSE, mc.set.seed = FALSE) } print.list <- function(x) { if (all(vlapply(x, is.atomic))) { x <- sapply(x, function(x) if (is.numeric(x)) round(x, 3) else x) catf("list(%s)", collapse(sprintf("%s = %s", names(x), vcapply(x, deparse, width.cutoff = 500, nlines = 1)), ", ")) } else { NextMethod(x) } } # mock runtime output getStatistics <- function(log) { stats <- ecr::getStatistics(log) if ("runtime.mean" %in% colnames(stats)) { if ("fidelity.sum" %in% colnames(stats)) { fid <- stats$fidelity.sum / stats$size } else { fid <- rep(5, nrow(stats)) } stats$runtime.mean <- rnorm(nrow(stats), 0.034, 0.002) * (fid + 2) stats$runtime.sum <- stats$runtime.mean * stats$size } stats } getPopulations <- function(log) { pop <- ecr::getPopulations(log) for (i in seq_along(pop)) { pop[[i]]$population <- lapply(pop[[i]]$population, function(ind) { fid <- attr(ind, "fidelity") if (is.null(fid)) { fid <- 5 } attr(ind, "runtime")[1] <- rnorm(1, 0.034, 0.002) * (fid + 2) ind }) } pop } slickEcr <- function(fidelity = NULL, ...) { if (!is.null(fidelity)) { fidelity[[2]] = fidelity[[2]] * 0 + seq_along(fidelity[[2]]) if (length(fidelity) > 2) { fidelity[[3]] = fidelity[[3]] * 0 + 1 } } mosmafs::slickEcr(fidelity = fidelity, ...) } knitr::opts_chunk$set( cache = FALSE, collapse = TRUE, comment = "#>" )

An introduction to multi-fidelity is given in J. E. Fieldsend and R. M. Everson, The Rolling Tide Evolutionary Algorithm: A Multiobjective Optimizer for Noisy Optimization Problems.
In its current state, `mosmafs`

supports two ways of performing multi-fidelity optimization: Selected by generation, and selected by dominance. Multi-fidelity by generation is simply performed by changing the fidelity of the objective function after a given number of generations. Multi-fidelity by dominance is performed by evaluating a point with low fidelity first, and then enabling high fidelity if the first evaluation suggests that the point is not dominated by any previous result.

This vignette starts where the previous vignette leaves off and expects the following preparation:

devtools::install_github("jakobbossek/ecr2") library("ecr") library("magrittr") library("ggplot2") library("ParamHelpers") library("mlr") library("mlrCPO") library("mosmafs")

task.whole <- create.hypersphere.data(3, 2000) %>% create.classif.task(id = "sphere") %>% task.add.permuted.cols(10) rows.whole <- sample(2000) task <- subsetTask(task.whole, rows.whole[1:500]) task.hout <- subsetTask(task.whole, rows.whole[501:2000]) lrn <- makeLearner("classif.rpart", maxsurrogate = 0) ps.simple <- pSS( maxdepth: integer[1, 30], minsplit: integer[2, 30], cp: numeric[0.001, 0.999]) fitness.fun.simple <- makeObjective(lrn, task, ps.simple, cv5, holdout.data = task.hout) ps.objective <- getParamSet(fitness.fun.simple) mutator.simple <- combine.operators(ps.objective, numeric = ecr::setup(mutGauss, sdev = 0.1), integer = ecr::setup(mutGaussInt, sdev = 3), selector.selection = mutBitflipCHW) crossover.simple <- combine.operators(ps.objective, numeric = recPCrossover, integer = recPCrossover, selector.selection = recPCrossover) initials <- sampleValues(ps.objective, 32, discrete.names = TRUE)

An objective function optimized with `slickEcr()`

may have a `fidelity`

argument which should choose the fidelity at which the function is evaluated. It can take any numeric value chosen (at another point) by the user, but it should make sense to take a weighted mean of results by this fidelity:

(obj(x, fidelity = a) * a + obj(x, fidelity = b) * b) / (a + b)

A sensible usage of fidelity is to choose the number of resampling iterations through it.

The `makeObjective()`

function will create a multi-fidelity compatible objective function if its `resampling`

argument is a function, mapping from `numeric(1)`

to a resampling object. The results for different fidelities should usually not be subsets of one another, because the evaluation for different fidelities is sometimes averaged over, which can lead to over-emphasis of some resampling folds.

nRes <- function(n) { makeResampleDesc("Subsample", split = 0.9, iters = n) }

We can use this function to create a multi-fidelity fitness function:

fitness.fun <- makeObjective(lrn, task, ps.simple, nRes, holdout.data = task.hout) formals(fitness.fun)

The `slickEcr()`

function accepts the `fidelity`

argument, which must be a `data.frame`

with two or three columns. For generation-wise multi-fidelity, we give it a `data.frame`

with two columns, with the first column indicating the generation at which a certain fidelity should be used, and the second column containing the fidelity to use. To use fidelity `1`

for the first five generations, then fidelity `3`

, for another five generations, and finally `5`

for the last five, the `data.frame`

would be

fidelity <- data.frame( c(1, 6, 11), c(1, 3, 5)) print(fidelity)

This is given to `slickEcr()`

:

set.seed(3)

run.gen.mufi <- slickEcr( fitness.fun = fitness.fun, lambda = 16, population = initials, mutator = mutator.simple, recombinator = crossover.simple, generations = 15, fidelity = fidelity)

The plot of resulting pareto-fronts notably has later generation's pareto fronts seemingly dominated by individuals from earlier generations. This is because in the log-object, the fitness of the first generations was evaluated using the low fidelity of these generations. In later generations, these points were re-evaluated using the larger fidelity.

plot_fronts <- function(run) { fronts <- fitnesses(run, function(x) paretoEdges(x, c(1, 1))) ggplot(data = fronts, aes(x = perf, y = propfeat, color = ordered(gen))) + geom_line() + geom_point(data = fronts[fronts$point, ], shape = "x", size = 5) + xlim(0, 1) + ylim(0, 1) + coord_fixed() } plot_fronts(run.gen.mufi)

The fidelity that was used for each individuum can be extracted from its `"fidelity"`

attribute. It can be accessed using the `attr()`

method or the `popAggregate()`

utility function. The runtime will scale approximately linearly (with an added constant overhead) in this case. The sum of all fidelity options used for each generation can also be inspected using the `log.newinds`

logging object--it may represent a proxy for the computational ressources that were used. Note how the generations with changing fidelity are present twice: for re-evaluation with new fidelity, and for ordinary evaluation of new individuals.

populations <- getPopulations(run.gen.mufi$log) ind1.gen1 <- populations[[1]]$population[[1]] attr(ind1.gen1, "fidelity") attr(ind1.gen1, "runtime") ind1.gen7 <- populations[[7]]$population[[1]] attr(ind1.gen7, "fidelity") attr(ind1.gen7, "runtime") ind1.gen15 <- populations[[15]]$population[[1]] attr(ind1.gen15, "fidelity") attr(ind1.gen15, "runtime") getStatistics(run.gen.mufi$log.newinds)

The cumulative fidelity up to each generation can be computed using the `collectResult()`

function. This makes it possible to analyse progress up to a certain point of computational expenditure.

cres <- collectResult(run.gen.mufi) ggplot(cres, aes(x = cum.fid, y = eval.domHV, color = "Training")) + geom_line() + geom_point(size = 1) + geom_point(data = cres[cres$fid.reeval, ], shape = "x", size = 5) + geom_line(aes(x = cum.fid, y = true.hout.domHV, color = "Holdout")) + ylim(0, 1)

The "x" mark the points at which fidelity reevaluation occurred: There a jump downward in hypervolume is possible. Also, the plot shows a large jump in cumulative fidelity before each reevaluation, because the whole population is reevaluated at these points.

The `slickEcr()`

`fidelity`

argument accepts `data.frames`

with three columns in the case that different fidelity should be used for points that lie on the pareto-front than those that, in a first evaluation, are dominated. This can be combined with generation-wise multi-fidelity, but our first example will only have one row. It evaluates simple holdout-resampling for each point, and, if the result seems to be better than previous evaluations with the same number of features, re-does the resampling with ten-times repeated holdout resampling, which results in overall 11 evaluations for this point.

fidelity <- data.frame(1, 1, 10) print(fidelity)

set.seed(36)

run.dom.mufi <- slickEcr( fitness.fun = fitness.fun, lambda = 16, population = initials, mutator = mutator.simple, recombinator = crossover.simple, generations = 15, fidelity = fidelity)

```
plot_fronts(run.dom.mufi)
```

The `log.newinds`

object will again provide information about the aggregated runtime and fidelity used. Some generations perform more high-fidelity evaluations than others (and consequently have longer runtime).

getStatistics(run.dom.mufi$log.newinds)

Use the `popAggregate()`

function to get collected information about fidelity in individuals in a generation. The following shows the fidelities used in generation 2:

popAggregate(run.dom.mufi$log, "fidelity")[[2]]

Note that, the fidelity is 11 for some candidates, as they were promising after one holdout resampling and were additionally reevaluated with ten-times repeated holdout resampling.

Individual evaluation fidelity can be retrieved, again, from a logged individual's attributes. The following plots the pareto-front of generation 3, and the individuals sampled for generation 4. All individuals sampled with high fidelity lie close to the pareto-front, but some may, after high-fidelity evaluation, have turned out to actually be dominated by the old generation.

gen.i <- 3 logobj <- run.dom.mufi$log.newinds stat <- getStatistics(logobj) pop <- popAggregate(logobj, c("fidelity", "fitness"), data.frame = TRUE) ngen.info <- pop[[which(stat$gen == gen.i + 1)]] front <- fitnesses(run.dom.mufi, function(x) paretoEdges(x, c(1, 1))) %>% subset(gen == gen.i) new.front <- fitnesses(run.dom.mufi, function(x) paretoEdges(x, c(1, 1))) %>% subset(gen == gen.i + 1) ggplot() + geom_line(data = front, aes(x = perf, y = propfeat, linetype = "Gen3 Front")) + geom_line(data = new.front, aes(x = perf, y = propfeat, linetype = "Gen4 Front")) + geom_point(data = ngen.info, aes(x = fitness.perf, y = fitness.propfeat, shape = as.factor(fidelity), color = as.factor(fidelity), size = 3)) + scale_size_identity() + guides(colour = guide_legend(override.aes = list(size=3))) + xlim(0, 1) + ylim(0, 1) + coord_fixed()

The two approaches can, of course, be combined. It should be noted that the initial generation, as well as each generation after a fidelity-jump, is evaluated with the "high" fidelity column number. The following, for example, evaluates generation 1 with fidelity 6, generation 6 with fidelity 11, and generation 11 with fidelity 15. In between, new points are evaluated with low fidelity first and then re-evaluated on high-fidelity if they seem to not be dominated by the previous generation. Because of this, fidelity-jumps tend to be relatively computationally expensive and should be done sparingly if at all. If `unbiased.fidelity`

is set (the default), only an upward step in total fidelity of pareto set elements (i.e. sum of 2nd and 3rd column if three columns are given, otherwise just value in 2nd column) leads to a re-evaluation of all fidelity. It should be set whenever the expectation value of evaluated fitness does not change with changing fidelity between generations (note that it is strongly recommended that evaluations with the two fidelities in each row have the same or very close expectation values).

fidelity <- data.frame( c(1, 3, 6, 11), c(1, 2, 3, 5), c(5, 4, 8, 10)) print(fidelity)

set.seed(5)

run.all.mufi <- slickEcr( fitness.fun = fitness.fun, lambda = 16, population = initials, mutator = mutator.simple, recombinator = crossover.simple, generations = 15, fidelity = fidelity)

getStatistics(run.all.mufi$log.newinds)

```
plot_fronts(run.all.mufi)
```

When continuing finished runs using the `continueEcr()`

functionality, it is possible to submit a new `fidelity`

`data.frame`

to change fidelity behaviour. Note that generations continue to count from where previous evaluations left off. Therefore, in the following example, the entry for generation 1 is ignored, the fidelity used for all new offspring is 20 and rises to 25.

fidelity.new <- data.frame( c(1, 10, 17, 19), c(11, 20, 23, 25)) print(fidelity.new)

set.seed(2)

run.all.mufi.20 <- continueEcr(run.all.mufi, 5, lambda = 8, fidelity = fidelity.new)

getStatistics(run.all.mufi.20$log.newinds)

```
plot_fronts(run.all.mufi.20)
```

```
parallelStop()
```

**Any scripts or data that you put into this service are public.**

Embedding an R snippet on your website

Add the following code to your website.

For more information on customizing the embed code, read Embedding Snippets.