【问题标题】:Why tf-idf truncates words?为什么 tf-idf 会截断单词?
【发布时间】:2021-08-19 21:44:23
【问题描述】:

我有一个数据框x,即:

> str(x)
'data.frame':   117654 obs. of  2 variables:
$ text  : chr  "more about " ...
$ doc_id: chr  "Text 1" "Text 2" "Text 3" "Text 4" ...

我不能在这里报告它,dput,因为它太大了。我正在尝试估计 TF-IDF,并编写了代码:

library(dplyr)
library(janeaustenr)
library(tidytext)
book_words <- x %>%
  mutate(text = as.character(text)) %>% 
  unnest_tokens(output = word, input = text) %>%
  count(doc_id, word, sort = TRUE)

book_words <- book_words %>%
  bind_tf_idf(term = word, document = doc_id, n)

book_words<-book_words[order(book_words$tf_idf,decreasing=FALSE),]
book_words = book_words[!duplicated(book_words$word),]

无论如何,我注意到book_words 中的某些单词似乎被截断了。例如:

             doc_id          word n  tf      idf    tf_idf
 792727  Text 33268     disposabl 1 1.0 11.67321 11.673214

我确定这是一个被截断的术语,因为如果我运行:

x[grepl("^disposabl$",x$text),]

我没有获得任何行。

这种事发生在你身上吗?

【问题讨论】:

  • 我怀疑有前导空格(通常data.frame 列不会像没有一些前导空格那样不均匀分布)。 x[grepl("disposabl$",x$text),](没有前导^)找到什么了吗?
  • @r2evans:谢谢!你说的对!我只获得了 1 行!

标签: r tf-idf


【解决方案1】:

根据您的输出,名称中似乎有前导空格。如果它只是 "dispoabl" 没有前导/尾随空格,我希望

            doc_id      word n tf      idf   tf_idf
 792727 Text 33268 disposabl 1  1 11.67321 11.67321
 ###              ^         ^   one space each

但你的输出显示

             doc_id          word n  tf      idf    tf_idf
 792727  Text 33268     disposabl 1 1.0 11.67321 11.673214
                    ^^^^  four extra blanks

这意味着您的"^dispoabl$" 过于严格。尝试过滤(此处):

x[grepl("disposabl$",x$text),]

删除领先的^,因此允许d 之前的某些内容。替代方案:

  • "\\bdisposabl$" 添加了一个单词边界,所以 "adisposabl" 不会匹配,但 "a disposabl" 仍然会匹配;
  • "^\\s*disposabl$" 要求前面的任何内容都是空格;
  • x[grepl("^disposabl$",trimws(x$text))] 修剪空白处,原来的模式可以在这里工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    • 2018-08-05
    • 2018-03-23
    • 2018-05-27
    • 2019-11-01
    • 2019-04-17
    • 2019-06-12
    相关资源
    最近更新 更多