nlp中TF-IDF模型和python实现
一、文本向量化存在的不足
英语为例,I come to China to travel。如果将统计词频后的特征作为文本分类的输入,那么come、China、Travel各出现一次,但to出现两次。但是to的重要性却比词频为1的China、travel要低很多。
二、TF-IDF原理概述
1、词频(term frequency, TF)指的是某一个给定的词语在该文件中出现的次数
2、逆向文件频率 (inverse document frequency, IDF) 是一个词语普遍重要性的度量
3、TF-IDF倾向于过滤掉常见的词语,保留重要的词语。实际上是,TF * IDF
4、IDF的公式:N代表语料库中文本的总数,而N(x)代表语料库中包含词x的文本总数。
基本公式: I D F ( x ) = l o g N N ( X ) IDF(x)=log{N\over N(X)} IDF(x)=logN(X)N
平滑公式: I D F ( x ) = l o g N + 1 N ( x ) + 1 + 1 IDF(x)=log{N+1\over N(x)+1}+1 IDF(x)=logN(x)+1N+1+1
某一词的TF-IDF值: T F − I D F ( x ) = T F ( x ) ∗ I D F ( x ) TF-IDF(x)=TF(x)*IDF(x) TF−IDF(x)=TF(x)∗IDF(x)
某一特定文件里的词语x的重要性: T F ( x ) = n x , y ∑ k n k , j TF(x)={n_{x,y}\over \sum_k n_{k,j}} TF(x)=∑knk,jnx,y ,分子为x词在第j个文件中出现的次数,而分母是在第j个文件中所有字词的出现词数之和。
三、TF-IDF算法实现
3.1 CountVectorizer+TfidfTransformer的组合方式
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import CountVectorizer
corpus=[
'this is the first document.',
'this is the second document.',
'and the third one.',
'is yhis the first documnet?',
'i come to China to travel'
]
words=CountVectorizer().fit_transform(corpus)
tfidf=TfidfTransformer().fit_transform(words)
print(tfidf)
3.2直接调用TfidfVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
corpus=[
'this is the first document.',
'this is the second document.',
'and the third one.',
'is yhis the first documnet?',
'i come to China to travel'
]
tfidf=TfidfVectorizer().fit_transform(corpus)
print(tfidf)