【问题标题】:Elegant way to invert tranform recipes steps (normalize and log)?反转转换配方步骤(标准化和记录)的优雅方法?
【发布时间】:2021-01-17 14:18:59
【问题描述】:

将由配方转换的outcome(在本例中为mpg)列转换回最优雅的方法是什么? 解决方案可以是通用的(如果存在或仅适用于lognormalize 步骤(如下所示)。

可能有用的链接:
通用解决方案已在here 进行了讨论,但我认为它尚未实施。
here 提供了 R 函数 scale 的解决方案,但我不确定在这种情况下是否可以提供帮助。

library(recipes)

data <- tibble(mtcars) %>% 
    select(cyl, mpg)

rec <- recipe(mpg ~ ., data = data) %>%
    step_log(all_numeric()) %>%
    step_normalize(all_numeric()) %>%
    prep()

data_baked <- bake(rec, new_data = data)

# model fitting, predictions, etc...

# how to invert/transform back predictions (estimates) and true outcomes

【问题讨论】:

    标签: r tidymodels r-recipes


    【解决方案1】:

    从配方转换is to tidy() the recipe 中取出您需要的任何值,然后使用 dplyr 动词取出您需要的值的方法。

    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 <- tibble(mtcars) %>% 
      select(cyl, mpg)
    
    rec <- recipe(mpg ~ ., data = data) %>%
      step_log(all_numeric()) %>%
      step_normalize(all_numeric(), id = "normalize_num") %>%
      prep()
    

    两种方法可以退出配方步骤,然后你可以tidy()带参数:

    ## notice that you can identify steps by `number` or `id`
    tidy(rec)
    #> # A tibble: 2 x 6
    #>   number operation type      trained skip  id           
    #>    <int> <chr>     <chr>     <lgl>   <lgl> <chr>        
    #> 1      1 step      log       TRUE    FALSE log_LYuaY    
    #> 2      2 step      normalize TRUE    FALSE normalize_num
    
    ## choose by number
    tidy(rec, number = 1)
    #> # A tibble: 2 x 3
    #>   terms  base id       
    #>   <chr> <dbl> <chr>    
    #> 1 cyl    2.72 log_LYuaY
    #> 2 mpg    2.72 log_LYuaY
    ## choose by id, which we set above (otherwise it has random id like log)
    tidy(rec, id = "normalize_num")
    #> # A tibble: 4 x 4
    #>   terms statistic value id           
    #>   <chr> <chr>     <dbl> <chr>        
    #> 1 cyl   mean      1.78  normalize_num
    #> 2 mpg   mean      2.96  normalize_num
    #> 3 cyl   sd        0.309 normalize_num
    #> 4 mpg   sd        0.298 normalize_num
    

    一旦我们知道我们想要哪一步,我们就可以使用 dplyr 动词来准确得出我们想要转换回来的值,例如 mpg 的平均值。

    ## extract out value
    tidy(rec, id = "normalize_num") %>%
      filter(terms == "mpg", statistic == "mean") %>%
      pull(value)
    #>      mpg 
    #> 2.957514
    

    reprex package (v0.3.0) 于 2021-01-25 创建

    【讨论】:

      猜你喜欢
      • 2020-06-12
      • 1970-01-01
      • 2022-12-20
      • 2013-03-19
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 2013-06-03
      • 1970-01-01
      相关资源
      最近更新 更多