Mahout源码分析之 -- 文档向量化TF-IDF

2024-06-12 20:18

本文主要是介绍Mahout源码分析之 -- 文档向量化TF-IDF,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

 Mahout之SparseVectorsFromSequenceFiles源码分析

一、原理

TF-IDF是一种统计方法,用以评估一字词对于一个文件集或一个语料库中的其中一份文件的重要程度。字词的重要性随着它在文件中出现的次数成正比增加,但同时会随着它在语料库中出现的频率成反比下降。

TFIDF的主要思想是:如果某个词或短语在一篇文章中出现的频率TF高,并且在其他文章中很少出现,则认为此词或者短语具有很好的类别区分能力,适合用来分类。

TFIDF实际上是:TF * IDF,TF词频(Term Frequency),IDF逆向文件频率(Inverse Document Frequency)。

词频 (TF) 指的是某一个给定的词语在文件中出现的次数。这个数字通常会被归一化,以防止它偏向长的文件。(同一个词语在长文件里可能会比短文件有更高的词频,而不管该词语重要与否。)

逆向文件频率(IDF)是一个词语普遍重要性的度量,其主要思想是:如果包含词条t的文档越少,也就是n越小,IDF越大,则说明词条t具有很好的类别区分能力。

对于在某一特定文件里的词语  来说,它的重要性可表示为:


以上式子中  是该词在文件中的出现次数,而分母则是在文件中所有字词的出现次数之和(分母也可以是词出现次数的最大值)。

逆向文件频率(inverse document frequency,IDF)是一个词语普遍重要性的度量。某一特定词语的IDF,可以由总文件数目除以包含该词语之文件的数目,再将得到的商取对数得到:


其中

  • |D|:语料库中的文件总数
  • :包含词语的文件数目(即的文件数目)如果该词语不在语料库中,就会导致分母为零,因此一般情况下使用

然后


某一特定文件内的高词语频率,以及该词语在整个文件集合中的低文件频率,可以产生出高权重的TF-IDF。因此,TF-IDF倾向于过滤掉常见的词语,保留重要的词语。

二、源码分析

目标:将一个给定的sequence文件集合转化为SparseVectors

1、对文档分词

1.1)使用最新的{@link org.apache.lucene.util.Version}创建一个Analyzer,用来下文1.2分词;

复制代码
      Class<? extends Analyzer> analyzerClass = StandardAnalyzer.class;if (cmdLine.hasOption(analyzerNameOpt)) {String className = cmdLine.getValue(analyzerNameOpt).toString();analyzerClass = Class.forName(className).asSubclass(Analyzer.class);// try instantiating it, b/c there isn't any point in setting it if// you can't instantiate it
        AnalyzerUtils.createAnalyzer(analyzerClass);}
复制代码

1.2)使用{@link StringTuple}将input documents转化为token数组(input documents必须是{@link org.apache.hadoop.io.SequenceFile}格式);

DocumentProcessor.tokenizeDocuments(inputDir, analyzerClass, tokenizedPath, conf);

输入:inputDir     输出:tokenizedPath

SequenceFileTokenizerMapper

复制代码
 //将input documents按Analyzer进行分词,并将分得的词放在一个StringTuple中TokenStream stream = analyzer.tokenStream(key.toString(), new StringReader(value.toString()));CharTermAttribute termAtt = stream.addAttribute(CharTermAttribute.class);stream.reset();StringTuple document = new StringTuple();//StringTuple是一个能够被用于Hadoop Map/Reduce Job的String类型有序Listwhile (stream.incrementToken()) {if (termAtt.length() > 0) {document.add(new String(termAtt.buffer(), 0, termAtt.length()));}}
复制代码

2、创建TF向量(Term Frequency Vectors)---多个Map/Reduce Job

复制代码
        DictionaryVectorizer.createTermFrequencyVectors(tokenizedPath,outputDir,tfDirName,conf,minSupport,maxNGramSize,minLLRValue,-1.0f,false,reduceTasks,chunkSize,sequentialAccessOutput,namedVectors);
复制代码

2.1)全局词统计(TF)

startWordCounting(input, dictionaryJobPath, baseConf, minSupport);

使用Map/Reduce并行地统计全局的词频,这里只考虑(maxNGramSize == 1) 

输入:tokenizedPath   输出:wordCountPath

TermCountMapper

复制代码
  //统计一个文本文档中的词频OpenObjectLongHashMap<String> wordCount = new OpenObjectLongHashMap<String>();for (String word : value.getEntries()) {if (wordCount.containsKey(word)) {wordCount.put(word, wordCount.get(word) + 1);} else {wordCount.put(word, 1);}}wordCount.forEachPair(new ObjectLongProcedure<String>() {@Overridepublic boolean apply(String first, long second) {try {context.write(new Text(first), new LongWritable(second));} catch (IOException e) {context.getCounter("Exception", "Output IO Exception").increment(1);} catch (InterruptedException e) {context.getCounter("Exception", "Interrupted Exception").increment(1);}return true;}});
复制代码

TermCountCombiner:( 同 TermCountReducer)

TermCountReducer

复制代码
//汇总所有的words和单词的weights,并将同一word的权重sumlong sum = 0;for (LongWritable value : values) {sum += value.get();}if (sum >= minSupport) {//TermCountCombiner没有这个过滤)context.write(key, new LongWritable(sum));}
复制代码

2.2)创建词典

 List<Path> dictionaryChunks;dictionaryChunks =createDictionaryChunks(dictionaryJobPath, output, baseConf, chunkSizeInMegabytes, maxTermDimension);

读取2.1词频Job的feature frequency List,并给它们指定id

输入:wordCountPath   输出:dictionaryJobPath

复制代码
 /*** Read the feature frequency List which is built at the end of the Word Count Job and assign ids to them.* This will use constant memory and will run at the speed of your disk read*/private static List<Path> createDictionaryChunks(Path wordCountPath,Path dictionaryPathBase,Configuration baseConf,int chunkSizeInMegabytes,int[] maxTermDimension) throws IOException {List<Path> chunkPaths = Lists.newArrayList();Configuration conf = new Configuration(baseConf);FileSystem fs = FileSystem.get(wordCountPath.toUri(), conf);long chunkSizeLimit = chunkSizeInMegabytes * 1024L * 1024L;//默认64Mint chunkIndex = 0;Path chunkPath = new Path(dictionaryPathBase, DICTIONARY_FILE + chunkIndex);chunkPaths.add(chunkPath);SequenceFile.Writer dictWriter = new SequenceFile.Writer(fs, conf, chunkPath, Text.class, IntWritable.class);try {long currentChunkSize = 0;Path filesPattern = new Path(wordCountPath, OUTPUT_FILES_PATTERN);int i = 0;for (Pair<Writable,Writable> record: new SequenceFileDirIterable<Writable,Writable>(filesPattern, PathType.GLOB, null, null, true, conf)) {if (currentChunkSize > chunkSizeLimit) {//生成新的词典文件Closeables.close(dictWriter, false);chunkIndex++;chunkPath = new Path(dictionaryPathBase, DICTIONARY_FILE + chunkIndex);chunkPaths.add(chunkPath);dictWriter = new SequenceFile.Writer(fs, conf, chunkPath, Text.class, IntWritable.class);currentChunkSize = 0;}Writable key = record.getFirst();int fieldSize = DICTIONARY_BYTE_OVERHEAD + key.toString().length() * 2 + Integer.SIZE / 8;currentChunkSize += fieldSize;dictWriter.append(key, new IntWritable(i++));//指定id}maxTermDimension[0] = i;//记录最大word数目} finally {Closeables.close(dictWriter, false);}return chunkPaths;}
复制代码

2.3)构造PartialVectors(TF)

复制代码
int partialVectorIndex = 0;Collection<Path> partialVectorPaths = Lists.newArrayList();for (Path dictionaryChunk : dictionaryChunks) {Path partialVectorOutputPath = new Path(output, VECTOR_OUTPUT_FOLDER + partialVectorIndex++);partialVectorPaths.add(partialVectorOutputPath);makePartialVectors(input, baseConf, maxNGramSize, dictionaryChunk, partialVectorOutputPath,maxTermDimension[0], sequentialAccess, namedVectors, numReducers);}
复制代码

将input documents使用a chunk of features创建a partial vector

(这是由于词典文件被分成了多个文件,每个文件只能构造总的vector的一部分,其中每一部分叫一个partial vector)

输入:tokenizedPath   输出:partialVectorPaths

Mapper:(Mapper)

TFPartialVectorReducer

复制代码
    //读取词典文件
//MAHOUT-1247Path dictionaryFile = HadoopUtil.getSingleCachedFile(conf);// key is word value is idfor (Pair<Writable, IntWritable> record: new SequenceFileIterable<Writable, IntWritable>(dictionaryFile, true, conf)) {dictionary.put(record.getFirst().toString(), record.getSecond().get());}
复制代码
复制代码
//转化a document为a sparse vectorStringTuple value = it.next();Vector vector = new RandomAccessSparseVector(dimension, value.length()); // guess at initial sizefor (String term : value.getEntries()) {if (!term.isEmpty() && dictionary.containsKey(term)) { // unigramint termId = dictionary.get(term);vector.setQuick(termId, vector.getQuick(termId) + 1);}}
复制代码

2.4)合并PartialVectors(TF)

    Configuration conf = new Configuration(baseConf);Path outputDir = new Path(output, tfVectorsFolderName);PartialVectorMerger.mergePartialVectors(partialVectorPaths, outputDir, conf, normPower, logNormalize,maxTermDimension[0], sequentialAccess, namedVectors, numReducers);

合并所有的partial {@link org.apache.mahout.math.RandomAccessSparseVector}s为完整的{@link org.apache.mahout.math.RandomAccessSparseVector}

输入:partialVectorPaths   输出:tfVectorsFolder

Mapper:(Mapper)

PartialVectorMergeReducer:

//合并partial向量为完整的TF向量Vector vector = new RandomAccessSparseVector(dimension, 10);for (VectorWritable value : values) {vector.assign(value.get(), Functions.PLUS);//将包含不同word的向量合并为一个}

 3、创建IDF向量(document frequency Vectors)---多个Map/Reduce Job

复制代码
      Pair<Long[], List<Path>> docFrequenciesFeatures = null;// Should document frequency features be processedif (shouldPrune || processIdf) {log.info("Calculating IDF");docFrequenciesFeatures =TFIDFConverter.calculateDF(new Path(outputDir, tfDirName), outputDir, conf, chunkSize);}
复制代码

3.1)统计DF词频

Path wordCountPath = new Path(output, WORDCOUNT_OUTPUT_FOLDER);

startDFCounting(input, wordCountPath, baseConf);

输入:tfDir  输出:featureCountPath

 TermDocumentCountMapper

复制代码
 //为一个文档中的每个word计数1、文档数1Vector vector = value.get();for (Vector.Element e : vector.nonZeroes()) {out.set(e.index());context.write(out, ONE);}context.write(TOTAL_COUNT, ONE);
复制代码

Combiner:(TermDocumentCountReducer)

TermDocumentCountReducer

   //将每个word的文档频率和文档总数sumlong sum = 0;for (LongWritable value : values) {sum += value.get();}

3.2)df词频分块

 return createDictionaryChunks(wordCountPath, output, baseConf, chunkSizeInMegabytes);

将df词频分块存放到多个文件,记录word总数、文档总数

输入:featureCountPath    输出:dictionaryPathBase

复制代码
  /*** Read the document frequency List which is built at the end of the DF Count Job. This will use constant* memory and will run at the speed of your disk read*/private static Pair<Long[], List<Path>> createDictionaryChunks(Path featureCountPath,Path dictionaryPathBase,Configuration baseConf,int chunkSizeInMegabytes) throws IOException {List<Path> chunkPaths = Lists.newArrayList();Configuration conf = new Configuration(baseConf);FileSystem fs = FileSystem.get(featureCountPath.toUri(), conf);long chunkSizeLimit = chunkSizeInMegabytes * 1024L * 1024L;int chunkIndex = 0;Path chunkPath = new Path(dictionaryPathBase, FREQUENCY_FILE + chunkIndex);chunkPaths.add(chunkPath);SequenceFile.Writer freqWriter =new SequenceFile.Writer(fs, conf, chunkPath, IntWritable.class, LongWritable.class);try {long currentChunkSize = 0;long featureCount = 0;long vectorCount = Long.MAX_VALUE;Path filesPattern = new Path(featureCountPath, OUTPUT_FILES_PATTERN);for (Pair<IntWritable,LongWritable> record: new SequenceFileDirIterable<IntWritable,LongWritable>(filesPattern,PathType.GLOB,null,null,true,conf)) {if (currentChunkSize > chunkSizeLimit) {Closeables.close(freqWriter, false);chunkIndex++;chunkPath = new Path(dictionaryPathBase, FREQUENCY_FILE + chunkIndex);chunkPaths.add(chunkPath);freqWriter = new SequenceFile.Writer(fs, conf, chunkPath, IntWritable.class, LongWritable.class);currentChunkSize = 0;}int fieldSize = SEQUENCEFILE_BYTE_OVERHEAD + Integer.SIZE / 8 + Long.SIZE / 8;currentChunkSize += fieldSize;IntWritable key = record.getFirst();LongWritable value = record.getSecond();if (key.get() >= 0) {freqWriter.append(key, value);} else if (key.get() == -1) {//文档数目vectorCount = value.get();}featureCount = Math.max(key.get(), featureCount);}featureCount++;Long[] counts = {featureCount, vectorCount};//word数目、文档数目return new Pair<Long[], List<Path>>(counts, chunkPaths);} finally {Closeables.close(freqWriter, false);}}
复制代码

4、创建TFIDF(Term Frequency-Inverse Document Frequency (Tf-Idf) Vectors)

        TFIDFConverter.processTfIdf(new Path(outputDir, DictionaryVectorizer.DOCUMENT_VECTOR_OUTPUT_FOLDER),outputDir, conf, docFrequenciesFeatures, minDf, maxDF, norm, logNormalize,sequentialAccessOutput, namedVectors, reduceTasks);

4.1)生成PartialVectors(TFIDF)

复制代码
  int partialVectorIndex = 0;List<Path> partialVectorPaths = Lists.newArrayList();List<Path> dictionaryChunks = datasetFeatures.getSecond();for (Path dictionaryChunk : dictionaryChunks) {Path partialVectorOutputPath = new Path(output, VECTOR_OUTPUT_FOLDER + partialVectorIndex++);partialVectorPaths.add(partialVectorOutputPath);makePartialVectors(input,baseConf,datasetFeatures.getFirst()[0],datasetFeatures.getFirst()[1],minDf,maxDF,dictionaryChunk,partialVectorOutputPath,sequentialAccessOutput,namedVector);}
复制代码

使用a chunk of features创建a partial tfidf vector

输入:tfVectorsFolder   输出:partialVectorOutputPath

    DistributedCache.setCacheFiles(new URI[] {dictionaryFilePath.toUri()}, conf);//缓存df分块文件

Mapper:(Mapper)

TFIDFPartialVectorReducer

复制代码
  //计算每个文档中每个word的TFIDF值
Vector value = it.next().get();Vector vector = new RandomAccessSparseVector((int) featureCount, value.getNumNondefaultElements());for (Vector.Element e : value.nonZeroes()) {if (!dictionary.containsKey(e.index())) {continue;}long df = dictionary.get(e.index());if (maxDf > -1 && (100.0 * df) / vectorCount > maxDf) {continue;}if (df < minDf) {df = minDf;}vector.setQuick(e.index(), tfidf.calculate((int) e.get(), (int) df, (int) featureCount, (int) vectorCount));}
复制代码

 4.2)合并partial向量(TFIDF)

复制代码
    Configuration conf = new Configuration(baseConf);Path outputDir = new Path(output, DOCUMENT_VECTOR_OUTPUT_FOLDER);PartialVectorMerger.mergePartialVectors(partialVectorPaths,outputDir,baseConf,normPower,logNormalize,datasetFeatures.getFirst()[0].intValue(),sequentialAccessOutput,namedVector,numReducers);
复制代码

合并所有的partial向量为一个完整的文档向量

 输入:partialVectorOutputPath   输出:outputDir

 Mapper:Mapper

 PartialVectorMergeReducer

    //汇总TFIDF向量Vector vector = new RandomAccessSparseVector(dimension, 10);for (VectorWritable value : values) {vector.assign(value.get(), Functions.PLUS);}

 

这篇关于Mahout源码分析之 -- 文档向量化TF-IDF的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1055225

相关文章

C#实现一键批量合并PDF文档

《C#实现一键批量合并PDF文档》这篇文章主要为大家详细介绍了如何使用C#实现一键批量合并PDF文档功能,文中的示例代码简洁易懂,感兴趣的小伙伴可以跟随小编一起学习一下... 目录前言效果展示功能实现1、添加文件2、文件分组(书签)3、定义页码范围4、自定义显示5、定义页面尺寸6、PDF批量合并7、其他方法

Java实现在Word文档中添加文本水印和图片水印的操作指南

《Java实现在Word文档中添加文本水印和图片水印的操作指南》在当今数字时代,文档的自动化处理与安全防护变得尤为重要,无论是为了保护版权、推广品牌,还是为了在文档中加入特定的标识,为Word文档添加... 目录引言Spire.Doc for Java:高效Word文档处理的利器代码实战:使用Java为Wo

使用Python实现Word文档的自动化对比方案

《使用Python实现Word文档的自动化对比方案》我们经常需要比较两个Word文档的版本差异,无论是合同修订、论文修改还是代码文档更新,人工比对不仅效率低下,还容易遗漏关键改动,下面通过一个实际案例... 目录引言一、使用python-docx库解析文档结构二、使用difflib进行差异比对三、高级对比方

Python自动化处理PDF文档的操作完整指南

《Python自动化处理PDF文档的操作完整指南》在办公自动化中,PDF文档处理是一项常见需求,本文将介绍如何使用Python实现PDF文档的自动化处理,感兴趣的小伙伴可以跟随小编一起学习一下... 目录使用pymupdf读写PDF文件基本概念安装pymupdf提取文本内容提取图像添加水印使用pdfplum

Python从Word文档中提取图片并生成PPT的操作代码

《Python从Word文档中提取图片并生成PPT的操作代码》在日常办公场景中,我们经常需要从Word文档中提取图片,并将这些图片整理到PowerPoint幻灯片中,手动完成这一任务既耗时又容易出错,... 目录引言背景与需求解决方案概述代码解析代码核心逻辑说明总结引言在日常办公场景中,我们经常需要从 W

C#高效实现Word文档内容查找与替换的6种方法

《C#高效实现Word文档内容查找与替换的6种方法》在日常文档处理工作中,尤其是面对大型Word文档时,手动查找、替换文本往往既耗时又容易出错,本文整理了C#查找与替换Word内容的6种方法,大家可以... 目录环境准备方法一:查找文本并替换为新文本方法二:使用正则表达式查找并替换文本方法三:将文本替换为图

Python批量替换多个Word文档的多个关键字的方法

《Python批量替换多个Word文档的多个关键字的方法》有时,我们手头上有多个Excel或者Word文件,但是领导突然要求对某几个术语进行批量的修改,你是不是有要崩溃的感觉,所以本文给大家介绍了Py... 目录工具准备先梳理一下思路神奇代码来啦!代码详解激动人心的测试结语嘿,各位小伙伴们,大家好!有没有想

Android 缓存日志Logcat导出与分析最佳实践

《Android缓存日志Logcat导出与分析最佳实践》本文全面介绍AndroidLogcat缓存日志的导出与分析方法,涵盖按进程、缓冲区类型及日志级别过滤,自动化工具使用,常见问题解决方案和最佳实... 目录android 缓存日志(Logcat)导出与分析全攻略为什么要导出缓存日志?按需过滤导出1. 按

Linux中的HTTPS协议原理分析

《Linux中的HTTPS协议原理分析》文章解释了HTTPS的必要性:HTTP明文传输易被篡改和劫持,HTTPS通过非对称加密协商对称密钥、CA证书认证和混合加密机制,有效防范中间人攻击,保障通信安全... 目录一、什么是加密和解密?二、为什么需要加密?三、常见的加密方式3.1 对称加密3.2非对称加密四、

MySQL中读写分离方案对比分析与选型建议

《MySQL中读写分离方案对比分析与选型建议》MySQL读写分离是提升数据库可用性和性能的常见手段,本文将围绕现实生产环境中常见的几种读写分离模式进行系统对比,希望对大家有所帮助... 目录一、问题背景介绍二、多种解决方案对比2.1 原生mysql主从复制2.2 Proxy层中间件:ProxySQL2.3