R中的Quanteda tf-idf变换函数

时间:2018-12-27 06:55:33

标签: r tf-idf quanteda

我使用了Quanteda软件包,并获得了两个巨大的dfm train Valid

火车有效列相同。

我知道使用dfm_tfidf可以在 tain 上很快获得 tfidf 体重, 但是我的问题是如何基于 tain idf 获取有效的tfidf

我尝试使用pblapply和for循环,但是运行时间确实很慢。

这是我的代码,如何基于Quanteda中的其他IDF转换tfidf,或者 任何其他加快速度的方法。

##
##
##  Idf
Idf <- function(x){
  n     <- nrow(x)
  check <- colSums(dfm_weight(x, "boolean"))
  sure  <- ifelse(check==0, n, check)
  idf   <- log10(n/sure)
  return(idf)
}


##
##
##  train document term matrix
##  Document-feature matrix of: 1,715,438 documents, 184,554 features (100% sparse).
TrainWcm
> head(TrainWcm[,1:4])
Document-feature matrix of: 6 documents, 4 features (70.8% sparse).
6 x 4 sparse Matrix of class "dfm"
       features
docs    what changes will you
  text1    1       1    1   2
  text2    0       0    0   0
  text3    1       0    0   0
  text4    1       0    0   0
  text5    0       0    0   0
  text6    1       0    0   0

##
##
##  valid document term matrix
##  Document-feature matrix of: 391,836 documents, 184,554 features (100% sparse).
ValidWcm
> head(ValidWcm[,1:4])
Document-feature matrix of: 6 documents, 4 features (87.5% sparse).
6 x 4 sparse Matrix of class "dfm"
       features
docs    what changes will you
  text1    1       0    0   0
  text2    0       0    0   0
  text3    1       0    0   1
  text4    0       0    0   0
  text5    0       0    0   0
  text6    0       0    0   0
##
##
##  Idf from train
WcmIdf <- Idf(TrainWcm)
##
##
##  First method
TrainTfdf <- TrainWcm
ValidTfdf <- ValidWcm
n <- seq(length(WcmIdf))
for( i in n ){
  TrainTfdf[,i] <- TrainWcm[,i]*WcmIdf[i]
  ValidTfdf[,i] <- ValidWcm[,i]*WcmIdf[i]
  cat("\r",i)
}
##
##
##  Second method
n <- seq(length(WcmIdf))
TrainTfidf <- pblapply(n, function(i) TrainWcm[,i] * WcmIdf[i]) %>% do.call("cbind", .)
ValidTfidf <- pblapply(n, function(i) ValidWcm[,i] * WcmIdf[i]) %>% do.call("cbind", .)

2 个答案:

答案 0 :(得分:1)

根据问题,据我了解,有效培训 dfm需要有共同点,因此可以尝试合并这两个文档集或他们各自的语料库,然后计算强大的TF-IDF矩阵。

并且由于“有效”和“训练”都有共同的列,因此可以很容易地将它们合并或附加到另一列。

稍后,在计算出TF-IDF矩阵之后,您可以将它们重新划分为 train Valid

答案 1 :(得分:0)

我使用debug和修改过的dfm_tfidf,并获得了解决方案。 参数idf是上述Idf函数的输出。

##
##
##  Tfidf
Tfidf <- function(dfm, idf = NULL){
  require(quanteda)
  if(is.null(idf)){
    output <- dfm_tfidf(dfm)
    return(output)
  }else{
    output <- dfm
    j      <- as(dfm, "dgTMatrix")@j + 1
    output@x <- dfm@x * idf[j]
    return(output)
  }
}