r-tidymodels recipes:我可以使用step_dummy()对分类变量进行一次热编码吗



如果一个分类变量有两个以上的值(比如婚姻状况=单身/已婚/丧偶/分居/离婚(,那么我需要创建N个假人,每个可能的级别一个。这是使用step_dummy(one_hot=TRUE(完成的。

然而,如果类别是二进制的(pokemon_fan="yes"/"no"(,那么我只需要创建一个名为"yes"的单个伪对象;pokemon_fan_yes";。这是使用step_dummy(one_hot=FALSE(完成的。

step_dummy是否可以计算级别的数量,并根据该数量进行不同的处理?

谢谢。

在食谱本身中没有自动的方法来做到这一点,但我认为你可以创建一个函数来为你处理这个问题,比如:

library(recipes)
#> Loading required package: dplyr
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
#> 
#> Attaching package: 'recipes'
#> The following object is masked from 'package:stats':
#> 
#>     step
data(crickets, package = "modeldata")
levels_more_than <- function(vec, num = 2) {
n_distinct(levels(vec)) > num
}
recipe(~ ., data = crickets) %>%
step_dummy(species, one_hot = !! levels_more_than(crickets$species)) %>%
prep() %>%
bake(new_data = NULL)
#> # A tibble: 31 × 3
#>     temp  rate species_O..niveus
#>    <dbl> <dbl>             <dbl>
#>  1  20.8  67.9                 0
#>  2  20.8  65.1                 0
#>  3  24    77.3                 0
#>  4  24    78.7                 0
#>  5  24    79.4                 0
#>  6  24    80.4                 0
#>  7  26.2  85.8                 0
#>  8  26.2  86.6                 0
#>  9  26.2  87.5                 0
#> 10  26.2  89.1                 0
#> # … with 21 more rows
recipe(~ ., data = iris) %>%
step_dummy(Species, one_hot = !! levels_more_than(iris$Species)) %>%
prep() %>%
bake(new_data = NULL)
#> # A tibble: 150 × 7
#>    Sepal.Length Sepal.Width Petal.Length Petal.Width Species_setosa
#>           <dbl>       <dbl>        <dbl>       <dbl>          <dbl>
#>  1          5.1         3.5          1.4         0.2              1
#>  2          4.9         3            1.4         0.2              1
#>  3          4.7         3.2          1.3         0.2              1
#>  4          4.6         3.1          1.5         0.2              1
#>  5          5           3.6          1.4         0.2              1
#>  6          5.4         3.9          1.7         0.4              1
#>  7          4.6         3.4          1.4         0.3              1
#>  8          5           3.4          1.5         0.2              1
#>  9          4.4         2.9          1.4         0.2              1
#> 10          4.9         3.1          1.5         0.1              1
#> # … with 140 more rows, and 2 more variables: Species_versicolor <dbl>,
#> #   Species_virginica <dbl>

创建于2022-02-23由reprex包(v2.0.1(

以下是一些在食谱中使用不太标准选择器的提示。

最新更新