【问题标题】:tfidf algorithm for pythonpython的tfidf算法
【发布时间】:2013-08-25 18:30:35
【问题描述】:

我有这段代码可以用 tf-idf 计算文本相似度。

from sklearn.feature_extraction.text import TfidfVectorizer

documents = [doc1,doc2]
tfidf = TfidfVectorizer().fit_transform(documents)
pairwise_similarity = tfidf * tfidf.T
print pairwise_similarity.A

问题是这段代码将纯字符串作为输入,我想通过删除停用词、词干提取和标记化来准备文档。所以输入将是一个列表。如果我用标记化的文档调用documents = [doc1,doc2],错误是:

    Traceback (most recent call last):
  File "C:\Users\tasos\Desktop\my thesis\beta\similarity.py", line 18, in <module>
    tfidf = TfidfVectorizer().fit_transform(documents)
  File "C:\Python27\lib\site-packages\scikit_learn-0.14.1-py2.7-win32.egg\sklearn\feature_extraction\text.py", line 1219, in fit_transform
    X = super(TfidfVectorizer, self).fit_transform(raw_documents)
  File "C:\Python27\lib\site-packages\scikit_learn-0.14.1-py2.7-win32.egg\sklearn\feature_extraction\text.py", line 780, in fit_transform
    vocabulary, X = self._count_vocab(raw_documents, self.fixed_vocabulary)
  File "C:\Python27\lib\site-packages\scikit_learn-0.14.1-py2.7-win32.egg\sklearn\feature_extraction\text.py", line 715, in _count_vocab
    for feature in analyze(doc):
  File "C:\Python27\lib\site-packages\scikit_learn-0.14.1-py2.7-win32.egg\sklearn\feature_extraction\text.py", line 229, in <lambda>
    tokenize(preprocess(self.decode(doc))), stop_words)
  File "C:\Python27\lib\site-packages\scikit_learn-0.14.1-py2.7-win32.egg\sklearn\feature_extraction\text.py", line 195, in <lambda>
    return lambda x: strip_accents(x.lower())
AttributeError: 'unicode' object has no attribute 'apply_freq_filter'

有什么方法可以更改代码并使其接受列表,还是让我再次将标记化的文档更改为字符串?

【问题讨论】:

  • 看起来您缺少实际的错误消息(您已包含回溯,但未包含引发的错误)。
  • @Tasos 我的回答有用吗,还是您还有问题?如果我的解决方案不起作用,您能否举一个doc1/doc2 的最小示例?

标签: python scikit-learn tf-idf


【解决方案1】:

尝试将预处理跳过为小写并提供您自己的“nop”标记器:

tfidf = TfidfVectorizer(tokenizer=lambda doc: doc, lowercase=False).fit_transform(documents)

您还应该检查其他参数,例如 stop_words,以避免重复您的预处理。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-03
    • 2013-05-14
    • 2021-01-03
    • 2017-06-13
    • 1970-01-01
    • 2014-09-26
    • 2016-02-08
    • 2012-05-08
    相关资源
    最近更新 更多