Как для «хороших фильмов» получается 0,707107, по-моему, должно быть: 1/1*ln(5/2) = 0,91629.
from sklearn.feature_extraction.text import TfidfVectorizer
import pandas as pd
texts = [
"good movie", "not a good movie", "did not like",
"i like it", "good one"
]
# using default tokenizer in TfidfVectorizer
tfidf = TfidfVectorizer(min_df=2, max_df=0.5, ngram_range=(1, 2))
features = tfidf.fit_transform(texts)
pd.DataFrame(
features.todense(),
columns=tfidf.get_feature_names()
)
Из-за параметра norm
и smooth_idf
. По умолчанию оба верны.
from sklearn.feature_extraction.text import TfidfVectorizer
import pandas as pd
texts = [
"good movie", "not a good movie", "did not like",
"i like it", "good one"
]
# using default tokenizer in TfidfVectorizer
tfidf = TfidfVectorizer(min_df=2, max_df=0.5,norm=None,smooth_idf=False, ngram_range=(1, 2))
features = tfidf.fit_transform(texts)
pd.DataFrame(
features.todense(),
columns=tfidf.get_feature_names()
)
Выход:
good movie like movie not
0 1.916291 0.000000 1.916291 0.000000
1 1.916291 0.000000 1.916291 1.916291
2 0.000000 1.916291 0.000000 1.916291
3 0.000000 1.916291 0.000000 0.000000
4 0.000000 0.000000 0.000000 0.000000
По умолчанию sklearn использует формулу для расчета idf: log [ n / df(t) ] + 1
. Итак, 0,91621 по вашему расчету и прибавьте к нему 1.
Если вы сделаете smooth_idf=True
(по умолчанию), то формула станет log [ (1 + n) / (1 + df(d, t)) ] + 1
Выход tfidf = TfidfVectorizer(min_df=2, max_df=0.5,norm=None,smooth_idf=True, ngram_range=(1, 2))
good movie like movie not
0 1.693147 0.000000 1.693147 0.000000
1 1.693147 0.000000 1.693147 1.693147
2 0.000000 1.693147 0.000000 1.693147
3 0.000000 1.693147 0.000000 0.000000
4 0.000000 0.000000 0.000000 0.000000
How 0.707107??
Прочитать это Документация