您的位置:首页 > 编程语言 > Python开发

Pyhton 基于scikit的TFIDF特征抽取如何使用

2017-10-11 19:06 531 查看
  在对文本分析中 抽取特征有很多方法,TF-IDF方法抽取文本特征词效果还是很不错的,TF-IDF方法可以表征一个词的辨识度,比较官方的解释是:TF-IDF是一种统计方法,用以评估一字词对于一个文件集或一个语料库中的其中一份文件的重要程度。字词的重要性随着它在文件中出现的次数成正比增加,但同时会随着它在语料库中出现的频率成反比下降。TF-IDF加权的各种形式常被搜索引擎应用,作为文件与用户查询之间相关程度的度量或评级。除了TF-IDF以外,因特网上的搜索引擎还会使用基于链接分析的评级方法,以确定文件在搜寻结果中出现的顺序。

那么在实际工程应用中我们该如何提取文档的TF-IDF值呢,scikit-learn已经提供了一套非常完善的方法了,怎么用就直接上代码了,在处理过程中经常会遇到一些字符串编码的问题,解决方法可以参考这里

#-*-coding:utf8-*-
from sklearn.feature_extraction.text import TfidfVectorizer
from keras.preprocessing import text
from collections import OrderedDict
import os

max_word_length = 30
min_word_length = 3

class TFIDFExtractor:
def __init__(self, sample_folder, topn):
self._sample_folder = sample_folder
self._topn = topn # select the topn keywords by tfidf value
self._to_vectorize_word = []   # the word is filtered by simple rule (max_word_length > length > min_word_length)
self._words = []
self._wordweight = [[]]
self._topn_word = {}

def extract_word_vector(self):
for root, dirs, samples in os.walk(self._sample_folder):
for sample in samples:
with open(os.path.join(root, sample), 'r+') as fd:
words = text.text_to_word_sequence(fd.read(),
filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n',
lower=True,
split=" ")
line = ''
for word in words:
if min_word_length < len(word) < max_word_length:
line += word + ' '
line.rstrip(' ')
self._to_vectorize_word.append(line)

def compute_tfidf(self):
print 'compute tfidf'
try:
vectorizer = TfidfVectorizer()
self._wordweight =  vectorizer.fit_transform(self._to_vectorize_word).toarray()
self._words = vectorizer.get_feature_names()
except UnicodeDecodeError:
print 'get exception'

def extracto_topn_keyword(self):
print 'extract topn words'
rows = len(self._wordweight)
columns = len(self._wordweight[0])
new_arr = [[r[col] for r in self._wordweight] for col in xrange(columns)]
for i in range(len(self._words)):
self._topn_word[self._words[i]] = max(new_arr[i])

def get_topn_keyword(self):
return self._topn_word.keys()

def dump_topn_word_tofile(self):
ordered_dict = OrderedDict(sorted(self._topn_word.items(), key=lambda x: x[1], reverse=True))
with open(os.path.join(os.getcwd(), 'TFIDF_Sorted.txt'), 'w+') as fd:
for key, value in ordered_dict.items():
try:
fd.write((key +':' + str(value)))
fd.write(',\n')
except UnicodeEncodeError:
print 'encode error'

def auto(self):
self.extract_word_vector()
self.compute_tfidf()
self.extracto_topn_keyword()
self.dump_topn_word_tofile()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息