R中真正快速的单词ngram矢量化

标签 r vectorization text-mining n-gram text2vec

编辑:新包 text2vec 非常好,并且很好地解决了这个问题(以及许多其他问题)。

text2vec on CRAN
text2vec on github
vignette that illustrates ngram tokenization

我在 R 中有一个非常大的文本数据集,我已将其作为字符向量导入:

#Takes about 15 seconds
system.time({
  set.seed(1)
  samplefun <- function(n, x, collapse){
    paste(sample(x, n, replace=TRUE), collapse=collapse)
  }
  words <- sapply(rpois(10000, 3) + 1, samplefun, letters, '')
  sents1 <- sapply(rpois(1000000, 5) + 1, samplefun, words, ' ')
})

我可以将此字符数据转换为词袋表示,如下所示:
library(stringi)
library(Matrix)
tokens <- stri_split_fixed(sents1, ' ')
token_vector <- unlist(tokens)
bagofwords <- unique(token_vector)
n.ids <- sapply(tokens, length)
i <- rep(seq_along(n.ids), n.ids)
j <- match(token_vector, bagofwords)
M <- sparseMatrix(i=i, j=j, x=1L)
colnames(M) <- bagofwords

因此,R 可以在大约 3 秒内将 1,000,000 百万个短句子向量化为词袋表示(不错!):
> M[1:3, 1:7]
10 x 7 sparse Matrix of class "dgCMatrix"
      fqt hqhkl sls lzo xrnh zkuqc mqh
 [1,]   1     1   1   1    .     .   .
 [2,]   .     .   .   .    1     1   1
 [3,]   .     .   .   .    .     .   .

我可以把这个稀疏矩阵扔进 glmnetirlba并对文本数据进行一些非常棒的定量分析。万岁!

现在我想将此分析扩展到 ngrams 袋矩阵,而不是词袋矩阵。到目前为止,我发现的最快方法如下(我可以在 CRAN 上找到的所有 ngram 函数都阻塞在这个数据集上,所以 I got a little help from SO ):
find_ngrams <- function(dat, n, verbose=FALSE){
  library(pbapply)
  stopifnot(is.list(dat))
  stopifnot(is.numeric(n))
  stopifnot(n>0)
  if(n == 1) return(dat)
  pblapply(dat, function(y) {
    if(length(y)<=1) return(y)
    c(y, unlist(lapply(2:n, function(n_i) {
      if(n_i > length(y)) return(NULL)
      do.call(paste, unname(as.data.frame(embed(rev(y), n_i), stringsAsFactors=FALSE)), quote=FALSE)
    })))
  })
}

text_to_ngrams <- function(sents, n=2){
  library(stringi)
  library(Matrix)
  tokens <- stri_split_fixed(sents, ' ')
  tokens <- find_ngrams(tokens, n=n, verbose=TRUE)
  token_vector <- unlist(tokens)
  bagofwords <- unique(token_vector)
  n.ids <- sapply(tokens, length)
  i <- rep(seq_along(n.ids), n.ids)
  j <- match(token_vector, bagofwords)
  M <- sparseMatrix(i=i, j=j, x=1L)
  colnames(M) <- bagofwords
  return(M)
}

test1 <- text_to_ngrams(sents1)

这大约需要 150 秒(对于纯 r 函数来说还不错),但我想更快并扩展到更大的数据集。

有没有真快 R中的函数用于文本的n-gram向量化?理想情况下,我正在寻找 Rcpp函数将字符向量作为输入,并返回文档 x ngrams 的稀疏矩阵作为输出,但也很乐意为自己编写 Rcpp 函数提供一些指导。

甚至更快版本的 find_ngrams函数会有所帮助,因为这是主要瓶颈。 R 在标记化方面出奇地快。

编辑 1
这是另一个示例数据集:
sents2 <- sapply(rpois(100000, 500) + 1, samplefun, words, ' ')

在这种情况下,我创建词袋矩阵的函数大约需要 30 秒,而我创建词袋矩阵的函数大约需要 500 秒。同样,R 中现有的 n-gram 向量化器似乎在这个数据集上窒息(尽管我很想被证明是错误的!)

编辑 2
时间 vs tau:
zach_t1 <- system.time(zach_ng1 <- text_to_ngrams(sents1))
tau_t1 <- system.time(tau_ng1 <- tau::textcnt(as.list(sents1), n = 2L, method = "string", recursive = TRUE))
tau_t1 / zach_t1 #1.598655

zach_t2 <- system.time(zach_ng2 <- text_to_ngrams(sents2))
tau_t2 <- system.time(tau_ng2 <- tau::textcnt(as.list(sents2), n = 2L, method = "string", recursive = TRUE))
tau_t2 / zach_t2 #1.9295619

最佳答案

这是一个非常有趣的问题,我在 中花了很多时间来解决这个问题。量子达包裹。它涉及我将评论的三个方面,尽管只有第三个方面真正解决了您的问题。但是前两点解释了为什么我只关注 ngram 创建功能,因为 - 正如您所指出的 - 这是可以提高速度的地方。

  • 标记化。您在这里使用 string::str_split_fixed()在空格字符上,这是最快的,但不是最好的标记方法。我们在 quanteda::tokenize(x, what = "fastest word") 中实现的几乎完全相同.这不是最好的,因为 stringi 可以对空白分隔符进行更智能的实现。 (甚至字符类 \\s 更聪明,但速度稍慢——这被实现为 what = "fasterword" )。不过,您的问题与标记化无关,因此这一点只是上下文。
  • 制表文档特征矩阵。这里我们也使用 矩阵打包,并索引文档和功能(我称它们为功能,而不是术语),然后像在上面的代码中一样直接创建一个稀疏矩阵。但是你使用的match()比我们通过 使用的匹配/合并方法快得多数据表 .我要重新编码 quanteda::dfm()函数,因为您的方法更优雅、更快。真的,真的很高兴看到这个!
  • ngram 创建。在这里,我认为我实际上可以在性能方面提供帮助。我们在 中实现了这一点量子达通过对 quanteda::tokenize() 的论证,称为 grams = c(1)其中该值可以是任何整数集。我们对 unigrams 和 bigrams 的匹配是 ngrams = 1:2 , 例如。您可以在 https://github.com/kbenoit/quanteda/blob/master/R/tokenize.R 处检查代码,查看内部函数ngram() .我在下面复制了这个并制作了一个包装器,以便我们可以直接将它与您的 find_ngrams() 进行比较。功能。

  • 代码:
    # wrapper
    find_ngrams2 <- function(x, ngrams = 1, concatenator = " ") { 
        if (sum(1:length(ngrams)) == sum(ngrams)) {
            result <- lapply(x, ngram, n = length(ngrams), concatenator = concatenator, include.all = TRUE)
        } else {
            result <- lapply(x, function(x) {
                xnew <- c()
                for (n in ngrams) 
                    xnew <- c(xnew, ngram(x, n, concatenator = concatenator, include.all = FALSE))
                xnew
            })
        }
        result
    }
    
    # does the work
    ngram <- function(tokens, n = 2, concatenator = "_", include.all = FALSE) {
    
        if (length(tokens) < n) 
            return(NULL)
    
        # start with lower ngrams, or just the specified size if include.all = FALSE
        start <- ifelse(include.all, 
                        1, 
                        ifelse(length(tokens) < n, 1, n))
    
        # set max size of ngram at max length of tokens
        end <- ifelse(length(tokens) < n, length(tokens), n)
    
        all_ngrams <- c()
        # outer loop for all ngrams down to 1
        for (width in start:end) {
            new_ngrams <- tokens[1:(length(tokens) - width + 1)]
            # inner loop for ngrams of width > 1
            if (width > 1) {
                for (i in 1:(width - 1)) 
                    new_ngrams <- paste(new_ngrams, 
                                        tokens[(i + 1):(length(tokens) - width + 1 + i)], 
                                        sep = concatenator)
            }
            # paste onto previous results and continue
            all_ngrams <- c(all_ngrams, new_ngrams)
        }
    
        all_ngrams
    }
    

    这是一个简单文本的比较:
    txt <- c("The quick brown fox named Seamus jumps over the lazy dog.", 
             "The dog brings a newspaper from a boy named Seamus.")
    tokens <- tokenize(toLower(txt), removePunct = TRUE)
    tokens
    # [[1]]
    # [1] "the"    "quick"  "brown"  "fox"    "named"  "seamus" "jumps"  "over"   "the"    "lazy"   "dog"   
    # 
    # [[2]]
    # [1] "the"       "dog"       "brings"    "a"         "newspaper" "from"      "a"         "boy"       "named"     "seamus"   
    # 
    # attr(,"class")
    # [1] "tokenizedTexts" "list"     
    
    microbenchmark::microbenchmark(zach_ng <- find_ngrams(tokens, 2),
                                   ken_ng <- find_ngrams2(tokens, 1:2))
    # Unit: microseconds
    #                                expr     min       lq     mean   median       uq     max neval
    #   zach_ng <- find_ngrams(tokens, 2) 288.823 326.0925 433.5831 360.1815 542.9585 897.469   100
    # ken_ng <- find_ngrams2(tokens, 1:2)  74.216  87.5150 130.0471 100.4610 146.3005 464.794   100
    
    str(zach_ng)
    # List of 2
    # $ : chr [1:21] "the" "quick" "brown" "fox" ...
    # $ : chr [1:19] "the" "dog" "brings" "a" ...
    str(ken_ng)
    # List of 2
    # $ : chr [1:21] "the" "quick" "brown" "fox" ...
    # $ : chr [1:19] "the" "dog" "brings" "a" ...
    

    对于非常大的模拟文本,比较如下:
    tokens <- stri_split_fixed(sents1, ' ')
    zach_ng1_t1 <- system.time(zach_ng1 <- find_ngrams(tokens, 2))
    ken_ng1_t1 <- system.time(ken_ng1 <- find_ngrams2(tokens, 1:2))
    zach_ng1_t1
    #    user  system elapsed 
    # 230.176   5.243 246.389 
    ken_ng1_t1
    #   user  system elapsed 
    # 58.264   1.405  62.889 
    

    已经是一个改进,如果可以进一步改进,我会很高兴。我也应该能够实现更快的 dfm()方法进入量子达这样您就可以通过以下方式获得您想要的东西:
    dfm(sents1, ngrams = 1:2, what = "fastestword",
        toLower = FALSE, removePunct = FALSE, removeNumbers = FALSE, removeTwitter = TRUE)) 
    

    (这已经有效,但比你的整体结果慢,因为你创建最终稀疏矩阵对象的方式更快——但我很快就会改变这一点。)

    关于R中真正快速的单词ngram矢量化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31570437/

    相关文章:

    r - 使用R从PDF文件中提取字符字体大小

    nlp - 用于呈现文本挖掘结果的数据可视化技术

    r - 如何在 R 中编写带有非标准引号字符的 CSV?

    R lapply : check if data frame contains a column. 如果不是,则创建此列

    MATLAB:按特定行减去矩阵子集

    python - 在 Python 中向量化多维操作

    r - 与 R 的文本相关性

    r - purrr 列表评价陌生度

    r - Shiny(R GUI)用标记中的<和>替换<和>

    python - 对 Pandas 数据框应用/矢量化/加速按列清理功能