Reputation: 157
I want to transform my features for a machine learning model using a custom transformation. my function is :
step_customFunc <- function(x){ 1/(max(x+1) -x)}
Is there a way to add this in the pipeline of transformation using recipe and tidymodels like this way:
model_rec <- recipe(target ~ ., data) %>%
step_customFunc(all_predictors)
Upvotes: 3
Views: 681
Reputation: 3185
If your custom function is fairly simple, i.e. without arguments, you could also use step_mutate_at()
to apply the function. This would be considerably less work than creating a new step.
library(recipes)
step_customFunc <- function(x){ 1 / (max(x + 1) - x)}
recipe(mpg ~ ., data = mtcars) %>%
step_mutate_at(all_predictors(), fn = step_customFunc) %>%
prep() %>%
bake(new_data = NULL)
#> # A tibble: 32 x 11
#> cyl disp hp drat wt qsec vs am gear carb mpg
#> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 0.333 0.00319 0.00442 0.493 0.263 0.134 0.5 1 0.5 0.2 21
#> 2 0.333 0.00319 0.00442 0.493 0.282 0.145 0.5 1 0.5 0.2 21
#> 3 0.2 0.00274 0.00412 0.481 0.244 0.189 1 1 0.5 0.125 22.8
#> 4 0.333 0.00465 0.00442 0.351 0.312 0.224 1 0.5 0.333 0.125 21.4
#> 5 1 0.00885 0.00621 0.360 0.335 0.145 0.5 0.5 0.333 0.143 18.7
#> 6 0.333 0.00403 0.00433 0.315 0.337 0.272 1 0.5 0.333 0.125 18.1
#> 7 1 0.00885 0.0110 0.368 0.350 0.124 0.5 0.5 0.333 0.2 14.3
#> 8 0.2 0.00306 0.00365 0.446 0.309 0.256 1 0.5 0.5 0.143 24.4
#> 9 0.2 0.00301 0.00415 0.498 0.305 1 1 0.5 0.5 0.143 22.8
#> 10 0.333 0.00327 0.00469 0.498 0.335 0.179 1 0.5 0.5 0.2 19.2
#> # … with 22 more rows
Created on 2021-03-18 by the reprex package (v0.3.0)
Upvotes: 4
Reputation: 520
I think you'll find some docs here: https://www.tidymodels.org/learn/develop/recipes/ under "A New Step Definition"
Upvotes: 2