NLP相似度之tf-idf计算
当然,在学习过程中也是参考了很多其他的资料,代码都是一行一行敲出来的。
一、将多个文件合并成一个文件,避免频繁的打开和关闭
import sys for line in sys.stdin:
ss = line.strip().split('\t')
file_name = ss[0].strip()
file_context = ss[1].strip()
word_list = file_context.split(' ') word_set = set()
for word in word_list:
word_set.add(word) for word in word_set:
print '\t'.join([word, ''])
执行命令:就可以得到合并后的文件啦!!!
python convert.py input_tfidf_dir/ > merge_files.data
tf-idf计算流程图:

二 、计算IDF的值:
map阶段:读取每一行
import sys for line in sys.stdin:
ss = line.strip().split('\t')
file_name = ss[0].strip()
file_context = ss[1].strip()
word_list = file_context.split(' ') word_set = set()
for word in word_list:
word_set.add(word) for word in word_set:
print '\t'.join([word, ''])
reduce阶段:
import sys
import math current_word = None
doc_cnt = 508
count_pool = []
sum = 0 for line in sys.stdin:
ss = line.strip().split('\t')
if len(ss) != 2:
continue word, val = ss
if current_word == None:
current_word = word
if current_word != word:
for count in count_pool:
sum += count idf_score = math.log(float(doc_cnt) / (float(sum) + 1))
print '\t'.join([current_word, str(idf_score)]) current_word = word
count_pool = []
sum = 0 count_pool.append((int(val))) for count in count_pool:
sum += count idf_score = math.log(float(doc_cnt) / (float(sum) + 1))
print '\t'.join([current_word, str(idf_score)])
三、计算TF的值:
# 计算tf
# 读取合并后的数据
# 执行命令 cat merge_files.data | python map_tf.py mapper_func idf.data import sys word_dict = {}
idf_dict = {} # 读取计算的idf数据文件
def read_idf_file_func(idf_file_fd):
with open() as fd:
for line in fd:
ss = line.strip().split('\t')
if len(ss) != 2:
continue
token = ss[0].strip()
idf_score = ss[1].strip()
idf_dict[token] = float(idf_score)
return idf_dict # cat merge_files.data | python map_tf.py mapper_func
def mapper_func(idf_file_fd):
idf_dict = read_idf_file_func(idf_file_fd)
# 标准输入
for line in sys.stdin:
ss = line.strip().split('\t')
file_name = ss[0].strip()
file_context = ss[1].strip()
word_list = file_context.split(' ') for word in word_list:
if word not in word_dict:
word_dict[word] = 1
else:
word_dict[word] += 1 for k,v in word_dict.item():
if k not in idf_dict:
continue
print(file_name,k,v,idf_file_fd[k])
print(k,v) if __name__ == "__main__":
module = sys.modules[__name__]
func = getattr(module, sys.argv[1])
args = None
if len(sys.argv) > 1:
args = sys.argv[2:]
func(*args)
NLP相似度之tf-idf计算的更多相关文章
- TF/IDF(term frequency/inverse document frequency)
TF/IDF(term frequency/inverse document frequency) 的概念被公认为信息检索中最重要的发明. 一. TF/IDF描述单个term与特定document的相 ...
- TF/IDF计算方法
FROM:http://blog.csdn.net/pennyliang/article/details/1231028 我们已经谈过了如何自动下载网页.如何建立索引.如何衡量网页的质量(Page R ...
- 信息检索中的TF/IDF概念与算法的解释
https://blog.csdn.net/class_brick/article/details/79135909 概念 TF-IDF(term frequency–inverse document ...
- Elasticsearch由浅入深(十)搜索引擎:相关度评分 TF&IDF算法、doc value正排索引、解密query、fetch phrase原理、Bouncing Results问题、基于scoll技术滚动搜索大量数据
相关度评分 TF&IDF算法 Elasticsearch的相关度评分(relevance score)算法采用的是term frequency/inverse document frequen ...
- tf–idf算法解释及其python代码实现(下)
tf–idf算法python代码实现 这是我写的一个tf-idf的简单实现的代码,我们知道tfidf=tf*idf,所以可以分别计算tf和idf值在相乘,首先我们创建一个简单的语料库,作为例子,只有四 ...
- tf–idf算法解释及其python代码实现(上)
tf–idf算法解释 tf–idf, 是term frequency–inverse document frequency的缩写,它通常用来衡量一个词对在一个语料库中对它所在的文档有多重要,常用在信息 ...
- 文本分类学习(三) 特征权重(TF/IDF)和特征提取
上一篇中,主要说的就是词袋模型.回顾一下,在进行文本分类之前,我们需要把待分类文本先用词袋模型进行文本表示.首先是将训练集中的所有单词经过去停用词之后组合成一个词袋,或者叫做字典,实际上一个维度很大的 ...
- Elasticsearch学习之相关度评分TF&IDF
relevance score算法,简单来说,就是计算出,一个索引中的文本,与搜索文本,他们之间的关联匹配程度 Elasticsearch使用的是 term frequency/inverse doc ...
- tf idf公式及sklearn中TfidfVectorizer
在文本挖掘预处理之向量化与Hash Trick中我们讲到在文本挖掘的预处理中,向量化之后一般都伴随着TF-IDF的处理,那么什么是TF-IDF,为什么一般我们要加这一步预处理呢?这里就对TF-IDF的 ...
- 25.TF&IDF算法以及向量空间模型算法
主要知识点: boolean model IF/IDF vector space model 一.boolean model 在es做各种搜索进行打分排序时,会先用boolean mo ...
随机推荐
- RePr: Improved Training of Convolutional Filters
关键点: 1.关于filter正交 将一层中的一个$k \times k \times c$的卷积核展开为$k * k * c$的向量,表示为$f$.一层中有$J_{\ell}$个卷积核,$\bold ...
- Windows许可证即将到期激活教程
电脑提示Windows许可证即将到期,于是自己就在网上找了一些教程,但是并没有激活成功,反而由即将到期变为了通知状态,尝试了各种密钥都不行,也下载了激活工具如暴风激活工具,KMS都不管用,尝试了好多方 ...
- vue-element-ui之弹窗重置
遇到列表中需要给弹框赋默认值并且关闭后需要清空数据+清除验证时可以这么写:
- js 取整 取余
1.取整//保留整数部分parseInt(3/2) // 1 2.向上取整// 向上取整,有小数就整数部分加1Math.ceil(3/2) // 2 3.四舍五入// 四舍五入Math.round(3 ...
- ckeditor5字体颜色,字体背景颜色设置显示
在config.js中添加相关代码: config.allowedContent=true;//关闭标签过滤, config.colorButton_enableAutomatic = true; c ...
- 一、Git简介
由于工作需要,代码版本控制工具由SVN换为了Git.Git对于我来说,很陌生,不清楚其工作原理,所以查询了一些资料,将自己所得知的内容来汇总一下,梳理一下这方面的知识,同时也给其他想了解Git的童鞋们 ...
- srping的历史与哲学
历史: 要谈Spring的历史,就要先谈J2EE.J2EE应用程序的广泛实现是在1999年和2000年开始的,它的出现带来了诸如事务管理之类的核心中间层概念的标准化,但是在实践中并没有获得绝对的成功, ...
- 关于ajax的跨域
在前端开发中,跨域是经常遇到的问题,也是面试最喜欢问的问题,究其根本原因,是浏览器的同源策略所致,是浏览器为了避免不同域名不能共享cookie以及locationstorage等等,发起请求的时候无法 ...
- C# Global.asax.cs 定时任务
定时执行更新Redis缓存操作 protected void Application_Start(object sender, EventArgs e) { Timer timer = new Tim ...
- <Python Text Processing with NLTK 2.0 Cookbook>代码笔记
如下是<Python Text Processing with NLTK 2.0 Cookbook>一书部分章节的代码笔记. Tokenizing text into sentences ...