【问题标题】:grouped filter process really slow分组过滤过程真的很慢
【发布时间】:2021-11-05 22:11:36
【问题描述】:

所以我有这个带有标记的大量 tibble,我正在尝试对其进行一些过滤,然后转换为文档术语矩阵。

我的问题是分组过滤过程运行得很慢。

是否有人对我如何加快处理速度或删除出现在多于/少于 n% 的文档中的单词有什么好的建议? (我不喜欢TM包,我是初学者)。

代码:

dtm <-
  token %>% 
  count(document,word) %>%
  filter(nchar(word)>2,
         nchar(word)<30) %>% #Keep words with 2-30 characters
  group_by(word) %>%
  filter((n()/length(unique(dtm$document))) < 0.8,       # Remove words that occurs in more <br>than n% documents
         (n()/length(unique(dtm$document))) > 0.00001) %>%   # Remove words that occurs in <br>less than n% documents
  tidytext::cast_dtm(document = document, term = word, value = n)

【问题讨论】:

    标签: r text dplyr tidytext


    【解决方案1】:

    在我看来,过滤不需要在分组内发生,也不需要计算你有多少文档:

    library(tidyverse)
    library(tidytext)
    data(tate_text, package = "modeldata")
    
    tidy_tate <- tate_text %>% unnest_tokens(word, title)
    
    tate_ids <- n_distinct(tate_text$id)
    
    bench::mark(
        original = tidy_tate %>% 
            count(id, word) %>%
            filter(nchar(word) > 2,
                   nchar(word) < 30) %>%
            group_by(word) %>%
            filter((n()/length(unique(tate_text$id))) < 0.8,       
                   (n()/length(unique(tate_text$id))) > 0.00001) %>%  
            tidytext::cast_dtm(document = id, term = word, value = n),
        new = tidy_tate %>% 
            count(id, word) %>%
            filter(nchar(word) > 2,
                   nchar(word) < 30) %>%
            group_by(word) %>%
            mutate(uses = n()) %>%
            ungroup() %>%
            filter(uses/tate_ids < 0.8, uses/tate_ids > 0.00001) %>%  
            tidytext::cast_dtm(document = id, term = word, value = n)
    )
    
    #> # A tibble: 2 × 6
    #>   expression      min   median `itr/sec` mem_alloc `gc/sec`
    #>   <bch:expr> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
    #> 1 original      669ms    669ms      1.49  976.87MB     61.3
    #> 2 new           110ms    112ms      8.70    8.54MB     13.9
    

    reprex package (v2.0.1) 于 2021-11-15 创建

    新方法的速度提高了大约 7 倍,但结果相同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-22
      • 1970-01-01
      • 1970-01-01
      • 2012-02-05
      • 2013-06-10
      • 1970-01-01
      • 2016-07-07
      • 2015-03-11
      相关资源
      最近更新 更多