【问题标题】:How to set flag value based on data that use one-hot-encoding如何根据使用 one-hot-encoding 的数据设置标志值
【发布时间】:2020-04-13 01:27:00
【问题描述】:

我有一个由三个表组成的数据库,如下所示:

我想使用该数据库在 R 中制作机器学习模型,我需要的数据是这样的:

我可以使用一种热编码将分类变量从 t_pengolahan(例如“Pengupasan、Fermentasi 等”)转换为属性。但是,如何根据上面的“结果(使用 SQL 查询)”数据为数据值设置标志(是或否)?

【问题讨论】:

    标签: sql r machine-learning one-hot-encoding


    【解决方案1】:

    我们可以将前面相关问题的两个答案结合起来,每个答案都提供了一半的解决方案;这些答案在herehere 中找到:

    library(dplyr) ## dplyr and tidyr loaded for wrangling
    library(tidyr)
    options(dplyr.width = Inf) ## we want to show all columns of result
    yes_fun <- function(x) { ## helps with pivot_wider() below
        if ( length(x) > 0 ) {
            return("yes")
        }
    }
    sql_result %>%
        separate_rows(pengolahan) %>% ## add rows for unique words in pengolahan
        pivot_wider(names_from = pengolahan, ## spread to yes/no indicators
                    values_from = pengolahan,
                    values_fill = list(pengolahan = "no"),
                    values_fn = list(pengolahan = yes_fun))
    

    数据

    id_pangan  <- 1:3
    kategori   <- c("Daging", "Buah", "Susu")
    pengolahan <- c("Penggilingan, Perebusan", "Pengupasan",
                    "Fermentasi, Sterilisasi")
    batas      <- c(100, 50, 200)
    sql_result <- data.frame(id_pangan, kategori, pengolahan, batas)
    
    # A tibble: 3 x 8
      id_pangan kategori batas Penggilingan Perebusan Pengupasan
          <int> <fct>    <dbl> <chr>        <chr>     <chr>     
    1         1 Daging     100 yes          yes       no        
    2         2 Buah        50 no           no        yes       
    3         3 Susu       200 no           no        no        
      Fermentasi Sterilisasi
      <chr>      <chr>      
    1 no         no         
    2 no         no         
    3 yes        yes  
    

    【讨论】:

      【解决方案2】:

      这对我来说似乎不清楚。 “如何根据“结果(使用 SQL 查询)”数据为数据值设置标志(是或否)是什么意思?您想将其中一列转换为布尔值吗?如果是这样,您需要指定决策规则。 这可能如下所示:

      SELECT (... other columns),
      CASE case_expression
           WHEN when_expression_1 THEN 'yes'
           WHEN when_expression_2 THEN 'no'
           ELSE '' 
      END
      

      为了帮助别人帮助你: - 您使用哪种 SQL 变体? (例如,sqlite 解决方案是否适合您?) - 提供创建表的 sql 脚本,以及“使用一种热编码将分类变量从 t_pengolahan(例如“Pengupasan、Fermentasi 等”)转换为属性的脚本”

      【讨论】:

        猜你喜欢
        • 2019-10-03
        • 2019-12-11
        • 2021-11-02
        • 1970-01-01
        • 2023-03-17
        • 2017-05-11
        • 1970-01-01
        • 2022-01-15
        • 2018-03-18
        相关资源
        最近更新 更多