diff --git a/DESCRIPTION b/DESCRIPTION index a38a75f..7c81e79 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,7 @@ Package: funcml Type: Package Title: Functional Machine Learning Framework -Version: 0.9.10 +Version: 0.9.11 Depends: R (>= 3.5.0) Authors@R: c( person(given = "Imad", family = "El Badisy", role = c("aut", "cre"), email = "elbadisyimad@gmail.com") diff --git a/NAMESPACE b/NAMESPACE index 4128cb0..aa16e3d 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -100,6 +100,7 @@ export(roc_curve) export(roccurve) export(rsq) export(specificity) +export(splits) export(theme_funcml) export(themefuncml) export(time_cv) diff --git a/NEWS.md b/NEWS.md index c39aa71..fbdc8e9 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,11 @@ +# funcml 0.9.11 + +* New `splits()` draws the train/test row indices of any resampling scheme + (`cv()`, `holdout()`, `groupcv()`, `timecv()`) outside `evaluate()`. For a + holdout split the indices are returned directly as `$train` and `$test`. + The result is frozen: passing it back to `evaluate()`, `compare()` or + `tune()` on the same data reuses the same folds. + # funcml 0.9.10 * `brier()` and `logloss()` given a plain probability vector for a binary diff --git a/R/cv.R b/R/cv.R index aef3131..c9e78db 100644 --- a/R/cv.R +++ b/R/cv.R @@ -287,3 +287,60 @@ generate_folds <- function(n, y = NULL, resampling = cv(), data = NULL) { resampling$n <- n resampling } + +#' Draw the train/test row indices of a resampling scheme. +#' +#' `evaluate()` and `compare()` draw their folds internally. `splits()` draws +#' them up front so the row indices can be used outside funcml (for example to +#' fit a model on the training rows of a `holdout()` split by hand). The +#' result is a frozen resampling object: passing it back to `evaluate()`, +#' `compare()` or `tune()` on the same data reuses exactly these folds. +#' +#' @param resampling A resampling object from [cv()], [holdout()], [groupcv()] +#' or [timecv()]. +#' @param data Data frame the folds refer to. +#' @param formula Optional model formula. When given (or when `outcome` is), +#' classification outcomes are stratified as in `evaluate()`, so the folds +#' are identical to those `evaluate()` draws with the same seed. +#' @param outcome Optional outcome column name, an alternative to `formula` +#' for stratification. +#' @return A `funcml_cv` object whose `folds` element is a list of splits, +#' each with `train` and `test` row indices, `repeat_id` and `fold`. For a +#' holdout split the indices are also returned directly as `train` and +#' `test`. +#' @examples +#' s <- splits(holdout(prop = 0.75, seed = 1), mtcars) +#' length(s$train) +#' fit_train <- fit(mpg ~ wt, mtcars[s$train, ], model = "glm") +#' s5 <- splits(cv(5, seed = 1), mtcars) +#' lengths(lapply(s5$folds, `[[`, "test")) +#' @export +splits <- function(resampling, data, formula = NULL, outcome = NULL) { + if (!inherits(resampling, "funcml_cv")) { + stop("`resampling` must be created by cv(), holdout(), groupcv() or timecv().", call. = FALSE) + } + if (!is.data.frame(data)) { + stop("`data` must be a data frame.", call. = FALSE) + } + y <- NULL + if (!is.null(formula)) { + y <- stats::model.response(stats::model.frame(formula, data, na.action = stats::na.pass)) + } else if (!is.null(outcome)) { + if (!is.character(outcome) || length(outcome) != 1L || !outcome %in% names(data)) { + stop("`outcome` must be the name of a column of `data`.", call. = FALSE) + } + y <- data[[outcome]] + } + if (!is.null(y) && infer_task(y) == "classification") { + y <- factor(y) + } + resampling$folds <- NULL + resampling$fixed <- NULL + out <- generate_folds(nrow(data), y, resampling, data = data) + out$fixed <- TRUE + if (identical(out$method, "holdout")) { + out$train <- out$folds[[1L]]$train + out$test <- out$folds[[1L]]$test + } + out +} diff --git a/man/splits.Rd b/man/splits.Rd new file mode 100644 index 0000000..9a5582b --- /dev/null +++ b/man/splits.Rd @@ -0,0 +1,41 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/cv.R +\name{splits} +\alias{splits} +\title{Draw the train/test row indices of a resampling scheme.} +\usage{ +splits(resampling, data, formula = NULL, outcome = NULL) +} +\arguments{ +\item{resampling}{A resampling object from \code{\link[=cv]{cv()}}, \code{\link[=holdout]{holdout()}}, \code{\link[=groupcv]{groupcv()}} +or \code{\link[=timecv]{timecv()}}.} + +\item{data}{Data frame the folds refer to.} + +\item{formula}{Optional model formula. When given (or when \code{outcome} is), +classification outcomes are stratified as in \code{evaluate()}, so the folds +are identical to those \code{evaluate()} draws with the same seed.} + +\item{outcome}{Optional outcome column name, an alternative to \code{formula} +for stratification.} +} +\value{ +A \code{funcml_cv} object whose \code{folds} element is a list of splits, +each with \code{train} and \code{test} row indices, \code{repeat_id} and \code{fold}. For a +holdout split the indices are also returned directly as \code{train} and +\code{test}. +} +\description{ +\code{evaluate()} and \code{compare()} draw their folds internally. \code{splits()} draws +them up front so the row indices can be used outside funcml (for example to +fit a model on the training rows of a \code{holdout()} split by hand). The +result is a frozen resampling object: passing it back to \code{evaluate()}, +\code{compare()} or \code{tune()} on the same data reuses exactly these folds. +} +\examples{ +s <- splits(holdout(prop = 0.75, seed = 1), mtcars) +length(s$train) +fit_train <- fit(mpg ~ wt, mtcars[s$train, ], model = "glm") +s5 <- splits(cv(5, seed = 1), mtcars) +lengths(lapply(s5$folds, `[[`, "test")) +} diff --git a/tests/testthat/test-splits.R b/tests/testthat/test-splits.R new file mode 100644 index 0000000..fdd74e2 --- /dev/null +++ b/tests/testthat/test-splits.R @@ -0,0 +1,32 @@ +test_that("splits() returns holdout indices that partition the rows", { + s <- splits(holdout(prop = 0.75, seed = 1), mtcars) + expect_s3_class(s, "funcml_cv") + expect_length(s$train, floor(0.75 * nrow(mtcars))) + expect_setequal(c(s$train, s$test), seq_len(nrow(mtcars))) + expect_length(intersect(s$train, s$test), 0L) + expect_identical(s$train, s$folds[[1]]$train) +}) + +test_that("splits() matches the folds evaluate() draws and is reused", { + d <- iris + d$Species <- factor(d$Species == "setosa") + rs <- cv(4, seed = 11) + s <- splits(rs, d, formula = Species ~ Sepal.Length) + ev <- evaluate(d, Species ~ Sepal.Length, model = "glm", resampling = rs, + metrics = "accuracy") + expect_identical( + lapply(s$folds, `[[`, "test"), + lapply(ev$resampling$folds, `[[`, "test") + ) + ev2 <- evaluate(d, Species ~ Sepal.Length, model = "glm", resampling = s, + metrics = "accuracy") + expect_identical(ev2$resampling$folds, s$folds) + # stratified: each test fold keeps the class balance + props <- vapply(s$folds, function(f) mean(d$Species[f$test] == "TRUE"), numeric(1)) + expect_true(all(abs(props - 1 / 3) < 0.05)) +}) + +test_that("splits() checks its inputs", { + expect_error(splits(list(), mtcars), "resampling") + expect_error(splits(cv(3), mtcars, outcome = "nope"), "outcome") +})