本文內(nèi)容主要摘自python? machine? learning? 2nd? ?edition
1、假設我們有以下三個文本
? '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.計算tf-idf值
我們以is為例進行計算掌腰,is對應的是矩陣第二列持偏。
tf值肖揣,表示term在該文本中出現(xiàn)的次數(shù)积蔚,這里即is在文本3出現(xiàn)的次數(shù),很容易看出是3.
idf值耕漱,sklearn做了小小的改動算色,公式是 (1+log).?的意思就是文本總數(shù)(number of? document),df(d,t)表示包含is 的文件數(shù)目,很明顯螟够,這里也是3.這樣灾梦,計算的結(jié)果為3*(1+log)=3.
需要注意的是,sklearn對結(jié)果進行了正則化處理齐鲤。
最終得到的結(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 捧灰。