本文內(nèi)容主要摘自python? machine? learning? 2nd? ?edition
1、假設(shè)我們有以下三個(gè)文本
? 'The sun is shining'
?? 'The weather is sweet'
?? 'The sun is shining, the weather is sweet, and one and one is? two
2、利用CountVectorizer類得到如下字典
{'and': 0,'two': 7,'shining': 3,'one': 2,'sun': 4,'weather': 8,'the': 6,'sweet': 5,'is': 1}
3、將步驟1的文檔轉(zhuǎn)換為矩陣
[[0 1 0 1 1 0 1 0 0]
[0 1 0 0 0 1 1 0 1]
[2 3 2 1 1 1 2 1 1]]
4.計(jì)算tf-idf值
我們以is為例進(jìn)行計(jì)算,is對(duì)應(yīng)的是矩陣第二列。
tf值,表示term在該文本中出現(xiàn)的次數(shù),這里即is在文本3出現(xiàn)的次數(shù),很容易看出是3.
idf值,sklearn做了小小的改動(dòng),公式是 (1+log).?
的意思就是文本總數(shù)(number of? document),df(d,t)表示包含is 的文件數(shù)目,很明顯,這里也是3.這樣,計(jì)算的結(jié)果為3*(1+log
)=3.
需要注意的是,sklearn對(duì)結(jié)果進(jìn)行了正則化處理。

最終得到的結(jié)果為
[[ 0.? 0.43? ?0. 0.56 0.56? 0.? ? 0.43? ? 0.? ? 0. ]
[ 0.??0.43? ? 0.? ?0.? ?0.? ? 0.56 0.43? 0.? ?0.56]
[ 0.5 0.45? ?0.5 0.19 0.19 0.19 0.3 0.25 0.19]]
每一行的平方和均為1,這是l2正則化處理的結(jié)果。
另外可以看出,原先is的詞頻是 1 1 3,最終tf-idf值是0.43 0.43 0.45 。