Cross-validation and hyperparameter search
tuning.Rdcross_validate() fits a model to each split's training rows and scores
it on the test rows. grid_search() does that for each candidate and
picks the lowest mean score; random_search() draws the candidates.
Models are built by your own fit function, so any of glm_fit(),
elastic_net_fit() or gam_fit() (or anything else) can be tuned.
Usage
cross_validate(data, splits, fit, score, map = NULL, seed = NULL)
grid_search(candidates, data, splits, fit, score, map = NULL, seed = NULL)
random_search(n, draw, data, splits, fit, score, seed = NULL)Arguments
- data
A data frame.
- splits
Splits from
k_fold(),group_k_fold()ortime_ordered().- fit
fit(train)forcross_validate(),fit(candidate, train)for the searches: returns a fitted model.- score
score(model, test): a loss on the test rows (lower is better), such as a meanfamily_deviance().- map
NULL(the default) fits serially. Otherwise a function shaped likelapply(X, FUN)that runs the fits, for instance in worker processes:function(x, f) parallel::parLapply(cl, x, f),future.apply::future_lapplyor amiraimap. See "Parallel fits".- seed
For
random_search(), the seed for R's generator before drawing. Forcross_validate()andgrid_search(),NULL(the default) leaves R's generator alone; a number gives each fit its own seed, drawn from it in the caller, so afitorscorethat draws random numbers gives the same scores whatevermapruns them.- candidates
A list (or vector) of hyperparameter values.
- n
Number of random candidates.
- draw
draw(): one random candidate, using R's generator.
Value
cross_validate(): one score per split. The searches: a data
frame with a candidate list column and the score, and attribute
best, the row of the lowest score.
Parallel fits
fit and score are R functions, which only R's main thread can call,
so the fits run in parallel only in worker processes, through map.
grid_search() makes one task per candidate and split. The scores come
back in the order of the splits and candidates, whatever order the
workers finish in, and with a seed they are the same as a serial
run's.
Models stay in the worker. A fitted model holds a pointer to Rust memory that cannot be sent between processes, so each task fits and scores its model where it runs and returns only the score.
fitandscoremust not rely on objects that only the main process has: load the package in each worker. A function made at the top level reaches a worker without the global objects it calls (R sends the global environment by name, not its contents), so export those (parallel::clusterExport()) or make the function insidelocal().One thread per worker. Each worker process has a thread pool of its own, so set
RAYON_NUM_THREADS=1in the workers before they first load the package, or the workers' threads oversubscribe the cores.Use fresh processes. A forked worker (
parallel::mclapply) can hang if the main process has already run a parallel computation of the package, since a fork does not copy its threads. A PSOCK cluster,future's multisession plan ormiraistart new processes.
Examples
d <- data.frame(x = 1:40 / 10)
d$y <- 1 + 2 * d$x + sin(1:40)
folds <- k_fold(nrow(d), 4, seed = 1)
mse <- function(m, test) mean((test$y - predict(m, test))^2)
cross_validate(d, folds, function(train) glm_fit(y ~ x, train, family = "gaussian"), mse)
#> [1] 0.6624610 0.7921088 0.4019159 0.5704141
g <- grid_search(c(0, 0.1, 1), d, folds,
function(lam, train) elastic_net_fit(y ~ x, train, family = "gaussian",
lambda = lam),
mse)
g[attr(g, "best"), ]
#> candidate score
#> 1 0 0.606725