【问题标题】:RegEx in vocabulary not working in sklearn TfidfVectorizer词汇表中的正则表达式在 sklearn TfidfVectorizer 中不起作用
【发布时间】:2019-04-18 22:12:34
【问题描述】:

我正在尝试计算语料库中所选单词的 tf-idf,但是当我对所选单词使用正则表达式时它不起作用。

以下是我从 stackoverflow 中的另一个问题中复制的示例,并进行了一些小改动以反映我的问题。

代码粘贴在下面。如果我分别编写“chocolate”和“chocolates”,则该代码有效,但如果我编写“chocolate|chocolates”,则该代码无效。

有人可以帮助我了解原因并提出解决此问题的可能方法吗?

keywords = ['tim tam', 'jam', 'fresh milk', 'chocolate|chocolates', 'biscuit pudding']
corpus = {1: "making chocolate biscuit pudding easy first get your favourite biscuit chocolates", 2: "tim tam drink new recipe that yummy and tasty more thicker than typical milkshake that uses normal chocolates", 3: "making chocolates drink different way using fresh milk egg"}
tfidf = TfidfVectorizer(vocabulary = keywords, stop_words = 'english', ngram_range=(1,3))
tfs = tfidf.fit_transform(corpus.values())
feature_names = tfidf.get_feature_names()
corpus_index = [n for n in corpus]
rows, cols = tfs.nonzero()
for row, col in zip(rows, cols):
    print((feature_names[col], corpus_index[row]), tfs[row, col])
tfidf_results = pd.DataFrame(tfs.T.todense(), index=feature_names, columns=corpus_index).T

我希望结果是:

('biscuit pudding', 1) 0.652490884512534
('chocolates', 1) 0.3853716274664007
('chocolate', 1) 0.652490884512534
('chocolates', 2) 0.5085423203783267
('tim tam', 2) 0.8610369959439764
('chocolates', 3) 0.5085423203783267
('fresh milk', 3) 0.8610369959439764

但是,现在它返回了:

('biscuit pudding', 1) 1.0
('tim tam', 2) 1.0
('fresh milk', 3) 1.0

【问题讨论】:

  • 应该是'chocolates|chocolate'。正则表达式从左到右匹配,因此根词的较短 forms 应该在最后。
  • 我想我的问题有点令人困惑。让我稍微改变一下。如果我的目标词汇是“pri”(我编的一个词),但如果我将其保留为字符串“pri”并且文档包含“private”、“price”等词,那么它们将被标记,但我只想要“pri”这个特定的词,所以我想把它写成“\bpri\b”,这就是为什么我在我的问题中指的是正则表达式。我并不是要将多个术语组合在一起。
  • 所以啊,这个\b(?:pri|private|chocolate|chocolates)\b

标签: python regex nlp tf-idf tfidfvectorizer


【解决方案1】:

我猜你正在使用来自 scikit-learn 的TfidfVectorizer。如果你仔细阅读documentation,它没有说你可以在你的词汇表中使用正则表达式,你能指出你提到的你复制的问题吗?

如果您想手动将多个术语组合在一起,您可以在词汇表中指定映射而不是迭代。例如:

keywords = {'tim tam':0, 'jam':1, 'fresh milk':2, 'chocolate':3, 'chocolates':3, 'biscuit pudding':4]

注意chocolate 和chocolates 如何映射到同一个索引。

【讨论】:

  • 感谢您回答 Josep,我想我的问题有点令人困惑。让我稍微改变一下。如果我的目标词汇是“pri”(我编的一个词),但如果我将其保留为字符串“pri”并且文档包含“private”、“price”等词,那么它们将被标记,但我只想要“pri”这个特定的词,所以我想把它写成“\bpri\b”,这就是为什么我在我的问题中指的是正则表达式。我并不是要将多个术语组合在一起。
猜你喜欢
  • 2020-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-05
  • 2020-10-15
  • 2019-03-14
  • 2012-12-18
相关资源
最近更新 更多