Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New param use_groups for PipeOpSubsample and rework for task_filter_ex() #834

Open
wants to merge 35 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
a1d8b95
added param use_groups for subsampling grouped data (changes behaviou…
advieser Oct 3, 2024
0206cc7
test for subsampling grouped data
advieser Oct 3, 2024
cd714cc
document
advieser Oct 3, 2024
af7244c
updated NEWS.mde
advieser Oct 3, 2024
a09779c
fixed error in examples
advieser Oct 3, 2024
d967849
fixed another bug in examples
advieser Oct 3, 2024
35b544a
changed logic for grouped data
advieser Oct 9, 2024
acf68fc
removed probs for sampling
advieser Oct 15, 2024
0d5fc84
reworked task_filter_ex to handle non-feature/non-target col_roles
advieser Oct 15, 2024
d46e9cd
typo, remove dev comment
advieser Oct 15, 2024
0283529
tests for grouped data (except optimal prop), tests for reworked task…
advieser Oct 15, 2024
d83135b
fixing subsampling for replace=TRUE and introducing new problems
advieser Oct 16, 2024
78dd63b
...
advieser Oct 16, 2024
e200f19
implement suggestions from code review
advieser Oct 17, 2024
ec5b81e
ugly WIP: let task_filter_ex rename groups for duplicated rows
advieser Oct 17, 2024
87e7812
WIP: task_factor_ex; can't change task in-place obvsly
advieser Oct 17, 2024
d0ca7a6
moved tests for task_filter_ex to own file
advieser Oct 17, 2024
32449cb
corrected test file name + WIP tests for task_filter_ex
advieser Oct 21, 2024
9198829
WIP task_filter_ex
advieser Oct 21, 2024
d4dc63a
WIP tests pipeopsubsample
advieser Oct 21, 2024
6fc245d
reworked task_filter_ex, this could actually work
advieser Oct 21, 2024
b28e070
updated test task_filter_ex
advieser Oct 21, 2024
5292f5c
improved task_filter_ex
advieser Oct 22, 2024
9096aca
typo
advieser Nov 2, 2024
8701d9d
fix + restructure comments
advieser Nov 2, 2024
27d883c
task_filter_ex tests
advieser Nov 2, 2024
05c54d3
handling for duplicates in used rows in task_filter_ex
advieser Nov 2, 2024
53879fc
simplified data.table expression
advieser Nov 3, 2024
be3e77c
reworked tests
advieser Nov 3, 2024
cf7bca8
Merge branch 'master' of https://github.com/mlr-org/mlr3pipelines int…
advieser Nov 3, 2024
4f540ae
docs: more detail for use_groups
advieser Nov 5, 2024
ce7cd6d
removed test that relies on POFU
advieser Nov 5, 2024
f2d6952
replace J with list for global function definition
advieser Nov 6, 2024
0de1054
replaced J with list for global function definition
advieser Nov 6, 2024
daecb54
tests for group renaming given duplicates in row_roles use
advieser Nov 6, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# mlr3pipelines 0.7.0-9000

* New down-sampling PipeOps for inbalanced data: `PipeOpTomek` / `po("tomek")` and `PipeOpNearmiss` / `po("nearmiss")`
* New parameter `use_groups` (default `TRUE`) for `PipeOpSubsampling` to respect grouping (changed default behaviour for grouped data)

# mlr3pipelines 0.7.0

Expand Down
58 changes: 46 additions & 12 deletions R/PipeOpSubsample.R
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,10 @@
#' * `frac` :: `numeric(1)`\cr
#' Fraction of rows in the [`Task`][mlr3::Task] to keep. May only be greater than 1 if `replace` is `TRUE`. Initialized to `(1 - exp(-1)) == 0.6321`.
#' * `stratify` :: `logical(1)`\cr
#' Should the subsamples be stratified by target? Initialized to `FALSE`. May only be `TRUE` for [`TaskClassif`][mlr3::TaskClassif] input.
#' Should the subsamples be stratified by target? Initialized to `FALSE`. May only be `TRUE` for [`TaskClassif`][mlr3::TaskClassif] input and if `use_groups = FALSE`.
#' * `use_groups` :: `logical(1)`\cr
#' If `TRUE` and if the [`Task`][mlr3::Task] has a column with role `group`, grouped observations are kept together during subsampling. May only be `TRUE` if `strafiy = FALSE`.
#' Initialized to `TRUE`.
#' * `replace` :: `logical(1)`\cr
#' Sample with replacement? Initialized to `FALSE`.
#'
Expand All @@ -52,9 +55,22 @@
#' @examples
#' library("mlr3")
#'
#' pos = mlr_pipeops$get("subsample", param_vals = list(frac = 0.7, stratify = TRUE))
#' # Subsample with stratification
#' pop = po("subsample", frac = 0.7, stratify = TRUE, use_groups = FALSE)
#' pop$train(list(tsk("iris")))
#'
#' pos$train(list(tsk("iris")))
#' # Subsample, respecting grouping
#' df = data.frame(
#' target = runif(3000),
#' x1 = runif(3000),
#' x2 = runif(3000),
#' grp = sample(paste0("g", 1:100), 3000, replace = TRUE)
#' )
#' task = TaskRegr$new(id = "example", backend = df, target = "target")
#' task$set_col_roles("grp", "group")
#'
#' pop = po("subsample", frac = 0.7, use_groups = TRUE)
#' pop$train(list(task))
#'
#' @family PipeOps
#' @template seealso_pipeopslist
Expand All @@ -67,31 +83,49 @@ PipeOpSubsample = R6Class("PipeOpSubsample",
ps = ps(
frac = p_dbl(lower = 0, upper = Inf, tags = "train"),
stratify = p_lgl(tags = "train"),
use_groups = p_lgl(tags = "train"),
replace = p_lgl(tags = "train")
)
ps$values = list(frac = 1 - exp(-1), stratify = FALSE, replace = FALSE)
ps$values = list(frac = 1 - exp(-1), stratify = FALSE, use_groups = TRUE, replace = FALSE)
super$initialize(id, param_set = ps, param_vals = param_vals, can_subset_cols = FALSE)
}
),
private = list(

.train_task = function(task) {
if (!self$param_set$values$stratify) {
keep = shuffle(task$row_roles$use,
ceiling(self$param_set$values$frac * task$nrow),
replace = self$param_set$values$replace)
} else {
pv = self$param_set$get_values(tags = "train")

if (pv$stratify && pv$use_groups) {
stop("Cannot combine stratification with grouping")
} else if (pv$use_groups && !is.null(task$groups)) {
# task$groups automatically removes rows not in task$row_roles$use and allows rows to be included multiple times
grp_sizes = table(task$groups$group)

# If we sample with replacement, drawing groups of larger sizes should be less probable
probs = if (pv$replace) 1 / grp_sizes else NULL

# We randomly shuffle the groups and keep all up to the group for
# which the fraction of rows is closest to the desired fraction.
shuffled = shuffle(grp_sizes, prob = probs, replace = pv$replace)
advieser marked this conversation as resolved.
Show resolved Hide resolved
cutoff_index = which.min(abs(cumsum(shuffled) / sum(shuffled) - frac))
advieser marked this conversation as resolved.
Show resolved Hide resolved
keep_grps = names(shuffled[seq_len(cutoff_index)])

group = NULL # for binding
keep = task$groups[group %in% keep_grps]$row_id
} else if (pv$stratify) {
if (!inherits(task, "TaskClassif")) {
stopf("Stratification not supported for %s", class(task))
}
splt = split(task$row_roles$use, task$data(cols = task$target_names))
keep = unlist(map(splt, function(x) {
shuffle(x,
ceiling(self$param_set$values$frac * length(x)),
replace = self$param_set$values$replace)
shuffle(x, ceiling(pv$frac * length(x)), replace = pv$replace)
}))
} else {
keep = shuffle(task$row_roles$use, ceiling(pv$frac * task$nrow), replace = pv$replace)
}

self$state = list()
# doesn't work for groups??
task_filter_ex(task, keep)
},

Expand Down
24 changes: 20 additions & 4 deletions man/mlr_pipeops_subsample.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

39 changes: 36 additions & 3 deletions tests/testthat/test_pipeop_subsample.R
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ test_that("PipeOpSubsample works stratified", {
task = mlr_tasks$get("iris")

po = PipeOpSubsample$new()
po$param_set$values = list(stratify = TRUE, frac = 0.6, replace = FALSE)
po$param_set$values = list(stratify = TRUE, use_groups = FALSE, frac = 0.6, replace = FALSE)
expect_class(po, "PipeOpSubsample")

tnew = train_pipeop(po, list(task))
Expand All @@ -53,7 +53,7 @@ test_that("PipeOpSubsample works stratified", {
table(list(Species = rep(c("setosa", "versicolor", "virginica"), 30))))

po = PipeOpSubsample$new()
po$param_set$values = list(stratify = TRUE, frac = 0.6, replace = TRUE)
po$param_set$values = list(stratify = TRUE, use_groups = FALSE, frac = 0.6, replace = TRUE)
expect_class(po, "PipeOpSubsample")

tnew = train_pipeop(po, list(task))
Expand All @@ -63,7 +63,7 @@ test_that("PipeOpSubsample works stratified", {
table(list(Species = rep(c("setosa", "versicolor", "virginica"), 30))))

po = PipeOpSubsample$new()
po$param_set$values = list(stratify = TRUE, frac = 2, replace = TRUE)
po$param_set$values = list(stratify = TRUE, use_groups = FALSE, frac = 2, replace = TRUE)
expect_class(po, "PipeOpSubsample")

tnew = train_pipeop(po, list(task))
Expand All @@ -73,7 +73,40 @@ test_that("PipeOpSubsample works stratified", {
table(list(Species = rep(c("setosa", "versicolor", "virginica"), 100))))
})

test_that("PipeOpSubsample works for grouped data", {
op = PipeOpSubsample$new()

test_df = data.frame(
target = runif(3000),
x1 = runif(3000),
x2 = runif(3000),
grp = sample(paste0("g", 1:100), 3000, replace = TRUE)
)
task = TaskRegr$new(id = "test", backend = test_df, target = "target")
task$set_col_roles("grp", "group")

train_out = op$train(list(task))[[1L]]
# grouped data are kept together
grps_out = table(train_out$groups$group)
expect_equal(
grps_out,
table(task$groups$group)[names(grps_out)]
)

op$param_set$set_values(frac = 2, replace = TRUE)
train_out = op$train(list(task))[[1L]]
# grouped data are kept together
grps_out = table(train_out$groups$group)
expect_equal(
grps_out,
table(task$groups$group)[names(grps_out)]
)

advieser marked this conversation as resolved.
Show resolved Hide resolved
# use_groups = TRUE and stratify = TRUE should throw an error
op$param_set$set_values(stratify = TRUE, use_groups = TRUE)
expect_error(op$train(list(task)))

})

test_that("task filter utility function", {
task = mlr_tasks$get("iris")
Expand Down
Loading