给出3个文档的语料库,例如:
sentences = ["This car is fast",
"This car is pretty",
"Very fast truck"]
我正在手动执行tf-idf的计算。
对于文档1和“汽车”一词,我可以找到:
TF = 1/4
IDF = log(3/2)
TF-IDF = 1/4 * log(3/2)
相同的结果应适用于文档2,因为它有4个单词,其中一个是“ car”。
我尝试使用以下代码在sklearn中应用此代码:
from sklearn.feature_extraction.text import TfidfVectorizer
import pandas as pd
data = {'text': sentences}
df = pd.DataFrame(data)
tv = TfidfVectorizer()
tfvector = tv.fit_transform(df.text)
print(pd.DataFrame(tfvector.toarray(), columns=tv.get_feature_names()))
我得到的结果是:
car fast is pretty this truck very
0 0.500000 0.50000 0.500000 0.000000 0.500000 0.000000 0.000000
1 0.459854 0.00000 0.459854 0.604652 0.459854 0.000000 0.000000
2 0.000000 0.47363 0.000000 0.000000 0.000000 0.622766 0.622766
我可以理解sklearn使用L2归一化,但是前两个文档中“ car”的tf-idf分数不应该相同吗?谁能帮助我了解结果?
答案 0 :(得分:0)
这是由于标准化。如果将参数norm=None
添加到TfIdfVectorizer(norm=None)
,将得到以下结果,该结果的值与car
car fast is pretty this truck very
0 1.287682 1.287682 1.287682 0.000000 1.287682 0.000000 0.000000
1 1.287682 0.000000 1.287682 1.693147 1.287682 0.000000 0.000000
2 0.000000 1.287682 0.000000 0.000000 0.000000 1.693147 1.693147