赞
踩
TF-IDF是一种文本特征提取算法,用于评估一篇文本中的某个词对于文本在整个语料库中的重要程度。它是根据单词在文本中的出现频率和在整个语料库中的文档频率来计算的,其中TF代表词频,IDF代表逆文档频率。
具体而言,TF表示某个词在一篇文档中出现的次数除以文档中所有词的总数,即:
一下为一个简单的TF-IDF算法:
- import math
-
- # 假设一个文档集合由以下三个文档组成
- documents = [
- "This is the first document.",
- "This is the second document.",
- "And this is the third one."
- ]
-
- # 首先计算每个文档中单词的出现频率(Term Frequency)
- tf = []
- for doc in documents:
- tf_doc = {}
- words = doc.split()
- for word in words:
- if word in tf_doc:
- tf_doc[word] += 1
- else:
- tf_doc[word] = 1
- tf.append(tf_doc)
-
- # 计算逆文档频率(Inverse Document Frequency)
- idf = {}
- N = len(documents)
- for doc in tf:
- for word in doc:
- if word in idf:
- idf[word] += 1
- else:
- idf[word] = 1
- for word in idf:
- idf[word] = math.log(N / idf[word])
-
- # 计算TF-IDF值
- tfidf = []
- for doc in tf:
- tfidf_doc = {}
- for word in doc:
- tfidf_doc[word] = doc[word] * idf[word]
- tfidf.append(tfidf_doc)
-
- # 输出TF-IDF值
- for i in range(len(tfidf)):
- print("Document {}:".format(i+1))
- for word in tfidf[i]:
- print("\t%s: %f" % (word, tfidf[i][word]))
'运行
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。