簡體   English   中英

在python中檢查sklearn的tf-idf分數

[英]Check the tf-idf scores of sklearn in python

我在這里按照示例使用sklearn計算TF-IDF值。

我的代碼如下。

from sklearn.feature_extraction.text import TfidfVectorizer
myvocabulary = ['life', 'learning']
corpus = {1: "The game of life is a game of everlasting learning", 2: "The unexamined life is not worth living", 3: "Never stop learning"}
tfidf = TfidfVectorizer(vocabulary = myvocabulary, ngram_range = (1,3))
tfs = tfidf.fit_transform(corpus.values())

我想為corpus的3個文檔計算lifelearning兩個單詞的tf-idf值。

根據我要引用的文章(請參見下表),我的示例應獲得以下值。
目標TF-IDF分數

但是,我從代碼中獲得的值完全不同。 請幫助我找到代碼中的錯誤以及如何解決。

要點是,在構建術語頻率矩陣之前,您不應將詞匯限制為僅兩個單詞(“生活”,“學習”)。 如果這樣做,所有其他單詞都會被忽略,並且會影響術語“頻率計數”。

如果要通過使用sklearn獲得與示例中完全相同的數字,還需要考慮其他幾個步驟:

  1. 示例中的功能是字母組合(單個單詞),因此我設置了ngram_range=(1,1)

  2. 該示例對術語頻率部分使用與sklearn不同的歸一化(示例中,術語計數通過文檔長度進行歸一化,而sklearn默認使用原始術語計數)。 因此,在計算idf部分之前,我已經分別對術語頻率進行了計數和歸一化。

  3. idf部分的示例中的規范化也不是sklearn的默認設置。 可以通過將smooth_idf設置為false來調整它以匹配示例。

  4. Sklearn的矢量化程序默認情況下只丟棄一個字符的單詞,但是這些單詞保留在示例中。 在下面的代碼中,我修改了token_pattern以允許同時包含1個字符的單詞。

最終的tfidf矩陣是通過將標准化計數乘以idf向量而獲得的。

from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.preprocessing import normalize
import pandas as pd

corpus = {1: "The game of life is a game of everlasting learning", 2: "The unexamined life is not worth living", 3: "Never stop learning"}

cvect = CountVectorizer(ngram_range=(1,1), token_pattern='(?u)\\b\\w+\\b')
counts = cvect.fit_transform(corpus.values())
normalized_counts = normalize(counts, norm='l1', axis=1)

tfidf = TfidfVectorizer(ngram_range=(1,1), token_pattern='(?u)\\b\\w+\\b', smooth_idf=False)
tfs = tfidf.fit_transform(corpus.values())
new_tfs = normalized_counts.multiply(tfidf.idf_)

feature_names = tfidf.get_feature_names()
corpus_index = [n for n in corpus]
df = pd.DataFrame(new_tfs.T.todense(), index=feature_names, columns=corpus_index)

print(df.loc[['life', 'learning']])

但是,實際上很少需要這種修改。 通常,僅直接使用TfidfVectorizer即可獲得良好的效果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM