TF: 该词在某篇文档中出现的频率,TF(w,d),值越大,表明该词在文档中的重要性越高
IDF: 单词普遍性的度量,如果该值越小,则该词认为非常普遍,如果该值很大,则认为该词在其他文档中很少出现,可以用该词来进行分类。
TF-IDF的主要思想是:如果某个单词在一篇文章中出现的频率TF高,并且在其他文章中很少出现,则认为此词或者短语具有很好的类别区分能力,适合用来分类。
应用:
(1) 搜索引擎
在搜索引擎中,通常使用TF-IDF模型计算查询串q(由关键词w1、w2、... wk组成)和文档d之间的匹配度:
TF-IDF(q, d) = sum{i=1,2,...k | TF(wi, d)* IDF(wi)}
可见,如果关键词wi在一篇文档中出现的频率很高,同时在其他文档中很少出现,则该词具有很好的区分能力
(2) 自动提取关键词
比如我们要想提取一篇新闻的关键词,先要对该新闻进行分词,然后根据TF-IDF计算每个单词的权重,并将权重最大的N个单词作为此新闻的关键词。
(3) 找出相似文章
使用TF-IDF算法,找出两篇文章的关键词;
每篇文章各取出若干个关键词(比如20个),合并成一个集合,计算每篇文章对于这个集合中的词的词频(为了避免文章长度的差异,可以使用相对词频);
生成两篇文章各自的词频向量;
计算两个向量的余弦相似度,值越大就表示越相似。
TF-IDF_demo
#encoding:utf-8
#@Time : 2017/8/18 1:10
#@Author : JackNiu
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
vectorizer = CountVectorizer()
corpus = [
'This is the first document This.',
'This is the second second document.',
'and the third one.',
'Is this the first document?',
]
X=vectorizer.fit_transform(corpus)
print("词典")
print(vectorizer.vocabulary_)
# and
print("TF_IDF 中的TF: ")
print(X.toarray())
print("计算IDF")
transformer = TfidfTransformer(smooth_idf=False)
tfidf = transformer.fit_transform(X.toarray())
print( tfidf.toarray())
print(transformer.idf_)
print("直接用TFIDF计算")
vect = TfidfVectorizer()
y=vect.fit_transform(corpus)
print(y.toarray())
print(vect.idf_)
运行过程
D:\software\Python\Python35\python.exe D:/PycharmProjects/mlprogram/ml_program/chapter2/TF_IDF_demo.py
词典
{'and': 0, 'document': 1, 'is': 3, 'the': 6, 'third': 7, 'first': 2, 'second': 5, 'this': 8, 'one': 4}
TF_IDF 中的TF:
[[0 1 1 1 0 0 1 0 2]
[0 1 0 1 0 2 1 0 1]
[1 0 0 0 1 0 1 1 0]
[0 1 1 1 0 0 1 0 1]]
计算IDF
[[ 0. 0.34643788 0.45552418 0.34643788 0. 0.
0.26903992 0. 0.69287577]
[ 0. 0.24014568 0. 0.24014568 0. 0.89006176
0.18649454 0. 0.24014568]
[ 0.56115953 0. 0. 0. 0.56115953 0.
0.23515939 0.56115953 0. ]
[ 0. 0.43306685 0.56943086 0.43306685 0. 0.
0.33631504 0. 0.43306685]]
[ 2.38629436 1.28768207 1.69314718 1.28768207 2.38629436 2.38629436
1. 2.38629436 1.28768207]
直接用TFIDF计算
[[ 0. 0.34934021 0.43150466 0.34934021 0. 0.
0.28560851 0. 0.69868042]
[ 0. 0.27230147 0. 0.27230147 0. 0.85322574
0.22262429 0. 0.27230147]
[ 0.55280532 0. 0. 0. 0.55280532 0.
0.28847675 0.55280532 0. ]
[ 0. 0.43877674 0.54197657 0.43877674 0. 0.
0.35872874 0. 0.43877674]]
[ 1.91629073 1.22314355 1.51082562 1.22314355 1.91629073 1.91629073
1. 1.91629073 1.22314355]
如果要进行上面的应用,则是使用tfidf模型的idf进行计算
参考:http://www.cnblogs.com/chenny7/p/4002368.html