写在前面的话,既然是学习版本,那么就不是一个好用的工程实现版本,整套代码全部使用List进行匹配效率可想而知。

【原文转自】:http://computergodzilla.blogspot.com/2013/07/how-to-calculate-tf-idf-of-document.html,修改了其中一些bug。

P.S:如果不是被迫需要语言统一,尽量不要使用此工程计算TF-IDF,计算2W条短文本,Matlab实现仅是几秒之间,此Java工程要计算良久。。半个小时?甚至更久,因此此程序作为一个学习版本,并不适用于工程实现。。工程试验版本

For beginners doing a project in text mining aches them a lot by various term like :

  • TF-IDF
  • COSINE SIMILARITY
  • CLUSTERING
  • DOCUMENT VECTORS

In my earlier post I showed you guys what is Cosine Similarity. I will not talk about Cosine Similarity in this post but rather I will show a nice little code to calculate Cosine Similarity in java.

Many of you must be familiar with Tf-Idf(Term frequency-Inverse Document Frequency).
I will enlighten them in brief.

Term Frequency:
Suppose for a document “Tf-Idf Brief Introduction” there are overall 60000 words and a word Term-Frequency occurs 60times.
Then , mathematically, its Term Frequency, TF = 60/60000 =0.001.

Inverse Document Frequency:
Suppose one bought Harry-Potter series, all series. Suppose there are 7 series and a word “AbraKaDabra” comes in 2 of the series.
Then, mathematically, its Inverse-Document Frequency , IDF = 1 +
log(7/2) = …….(calculated it guys, don’t be lazy, I am lazy not you
guys.)

And Finally, TFIDF = TF * IDF;

By mathematically I assume you now know its meaning physically.

Document Vector:
There are various ways to calculate document vectors. I am just giving
you an example. Suppose If I calculate all the term’s TF-IDF of a
document A and store them in an array(list, matrix … in any ordered way,
.. you guys are genius you know how to create a vector. ) then I get an
Document Vector of TF-IDF scores of document A.

The class shown below calculates the Term Frequency(TF) and Inverse Document Frequency(IDF).

  1. //TfIdf.java
  2. package com.computergodzilla.tfidf;
  3. import java.util.List;
  4. /**
  5. * Class to calculate TfIdf of term.
  6. * @author Mubin Shrestha
  7. */
  8. public class TfIdf {
  9. /**
  10. * Calculates the tf of term termToCheck
  11. * @param totalterms : Array of all the words under processing document
  12. * @param termToCheck : term of which tf is to be calculated.
  13. * @return tf(term frequency) of term termToCheck
  14. */
  15. public double tfCalculator(String[] totalterms, String termToCheck) {
  16. double count = 0;  //to count the overall occurrence of the term termToCheck
  17. for (String s : totalterms) {
  18. if (s.equalsIgnoreCase(termToCheck)) {
  19. count++;
  20. }
  21. }
  22. return count / totalterms.length;
  23. }
  24. /**
  25. * Calculates idf of term termToCheck
  26. * @param allTerms : all the terms of all the documents
  27. * @param termToCheck
  28. * @return idf(inverse document frequency) score
  29. */
  30. public double idfCalculator(List<String[]> allTerms, String termToCheck) {
  31. double count = 0;
  32. for (String[] ss : allTerms) {
  33. for (String s : ss) {
  34. if (s.equalsIgnoreCase(termToCheck)) {
  35. count++;
  36. break;
  37. }
  38. }
  39. }
  40. return 1 + Math.log(allTerms.size() / count);
  41. }
  42. }

The class shown below parsed the text documents and split them into
tokens. This class will communicate with TfIdf.java class to calculated
TfIdf. It also calls CosineSimilarity.java class to calculated the
similarity between the passed documents.

  1. //DocumentParser.java
  2. package com.computergodzilla.tfidf;
  3. import java.io.BufferedReader;
  4. import java.io.File;
  5. import java.io.FileNotFoundException;
  6. import java.io.FileReader;
  7. import java.io.IOException;
  8. import java.util.ArrayList;
  9. import java.util.List;
  10. /**
  11. * Class to read documents
  12. *
  13. * @author Mubin Shrestha
  14. */
  15. public class DocumentParser {
  16. //This variable will hold all terms of each document in an array.
  17. private List<String[]> termsDocsArray = new ArrayList<String[]>();
  18. private List<String> allTerms = new ArrayList<String>(); //to hold all terms
  19. private List<double[]> tfidfDocsVector = new ArrayList<double[]>();
  20. /**
  21. * Method to read files and store in array.
  22. * @param filePath : source file path
  23. * @throws FileNotFoundException
  24. * @throws IOException
  25. */
  26. public void parseFiles(String filePath) throws FileNotFoundException, IOException {
  27. File[] allfiles = new File(filePath).listFiles();
  28. BufferedReader in = null;
  29. for (File f : allfiles) {
  30. if (f.getName().endsWith(“.txt”)) {
  31. in = new BufferedReader(new FileReader(f));
  32. StringBuilder sb = new StringBuilder();
  33. String s = null;
  34. while ((s = in.readLine()) != null) {
  35. sb.append(s);
  36. }
  37. String[] tokenizedTerms = sb.toString().replaceAll(“[\\W&&[^\\s]]”, “”).split(“\\W+”);   //to get individual terms
  38. for (String term : tokenizedTerms) {
  39. if (!allTerms.contains(term)) {  //avoid duplicate entry
  40. allTerms.add(term);
  41. }
  42. }
  43. termsDocsArray.add(tokenizedTerms);
  44. }
  45. }
  46. }
  47. /**
  48. * Method to create termVector according to its tfidf score.
  49. */
  50. public void tfIdfCalculator() {
  51. double tf; //term frequency
  52. double idf; //inverse document frequency
  53. double tfidf; //term requency inverse document frequency
  54. for (String[] docTermsArray : termsDocsArray) {
  55. double[] tfidfvectors = new double[allTerms.size()];
  56. int count = 0;
  57. for (String terms : allTerms) {
  58. tf = new TfIdf().tfCalculator(docTermsArray, terms);
  59. idf = new TfIdf().idfCalculator(termsDocsArray, terms);
  60. tfidf = tf * idf;
  61. tfidfvectors[count] = tfidf;
  62. count++;
  63. }
  64. tfidfDocsVector.add(tfidfvectors);  //storing document vectors;
  65. }
  66. }
  67. /**
  68. * Method to calculate cosine similarity between all the documents.
  69. */
  70. public void getCosineSimilarity() {
  71. for (int i = 0; i < tfidfDocsVector.size(); i++) {
  72. for (int j = 0; j < tfidfDocsVector.size(); j++) {
  73. System.out.println(“between ” + i + “ and ” + j + “  =  ”
  74. + new CosineSimilarity().cosineSimilarity
  75. (
  76. tfidfDocsVector.get(i),
  77. tfidfDocsVector.get(j)
  78. )
  79. );
  80. }
  81. }
  82. }
  83. }

This is the class that calculates Cosine Similarity:

  1. //CosineSimilarity.java
  2. /*
  3. * To change this template, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. package com.computergodzilla.tfidf;
  7. /**
  8. * Cosine similarity calculator class
  9. * @author Mubin Shrestha
  10. */
  11. public class CosineSimilarity {
  12. /**
  13. * Method to calculate cosine similarity between two documents.
  14. * @param docVector1 : document vector 1 (a)
  15. * @param docVector2 : document vector 2 (b)
  16. * @return
  17. */
  18. public double cosineSimilarity(double[] docVector1, double[] docVector2) {
  19. double dotProduct = 0.0;
  20. double magnitude1 = 0.0;
  21. double magnitude2 = 0.0;
  22. double cosineSimilarity = 0.0;
  23. for (int i = 0; i < docVector1.length; i++) //docVector1 and docVector2 must be of same length
  24. {
  25. dotProduct += docVector1[i] * docVector2[i];  //a.b
  26. magnitude1 += Math.pow(docVector1[i], 2);  //(a^2)
  27. magnitude2 += Math.pow(docVector2[i], 2); //(b^2)
  28. }
  29. magnitude1 = Math.sqrt(magnitude1);//sqrt(a^2)
  30. magnitude2 = Math.sqrt(magnitude2);//sqrt(b^2)
  31. if (magnitude1 != 0.0 | magnitude2 != 0.0) {
  32. cosineSimilarity = dotProduct / (magnitude1 * magnitude2);
  33. } else {
  34. return 0.0;
  35. }
  36. return cosineSimilarity;
  37. }
  38. }

Here’s the main class to run the code:

  1. //TfIdfMain.java
  2. package com.computergodzilla.tfidf;
  3. import java.io.FileNotFoundException;
  4. import java.io.IOException;
  5. /**
  6. *
  7. * @author Mubin Shrestha
  8. */
  9. public class TfIdfMain {
  10. /**
  11. * Main method
  12. * @param args
  13. * @throws FileNotFoundException
  14. * @throws IOException
  15. */
  16. public static void main(String args[]) throws FileNotFoundException, IOException
  17. {
  18. DocumentParser dp = new DocumentParser();
  19. dp.parseFiles(“D:\\FolderToCalculateCosineSimilarityOf”); // give the location of source file
  20. dp.tfIdfCalculator(); //calculates tfidf
  21. dp.getCosineSimilarity(); //calculates cosine similarity
  22. }
  23. }

You can also download the whole source code from here: Download. (Google Drive)

Overall what I did is, I first calculate the TfIdf matrix of all the
documents and then document vectors of each documents. Then I used those
document vectors to calculate cosine similarity.

You think clarification is not enough. Hit me..
Happy Text-Mining!!

from: http://jacoxu.com/?p=1619

利用JAVA计算TFIDF和Cosine相似度-学习版本的更多相关文章

  1. 利用sklearn进行tfidf计算

    转自:http://blog.csdn.net/liuxuejiang158blog/article/details/31360765?utm_source=tuicool 在文本处理中,TF-IDF ...

  2. 利用sklearn计算文本相似性

    利用sklearn计算文本相似性,并将文本之间的相似度矩阵保存到文件当中.这里提取文本TF-IDF特征值进行文本的相似性计算. #!/usr/bin/python # -*- coding: utf- ...

  3. Java计算计算活了多少天

    Java计算计算活了多少天 思路: 1.输入你的出现日期: 2.利用日期转换,将字符串转换成date类型 3.然后将date时间换成毫秒时间 4.然后获取当前毫秒时间: 5.最后计算出来到这个时间多少 ...

  4. 使用不同的方法计算TF-IDF值

    摘要 这篇文章主要介绍了计算TF-IDF的不同方法实现,主要有三种方法: 用gensim库来计算tfidf值 用sklearn库来计算tfidf值 用python手动实现tfidf的计算 总结 之所以 ...

  5. 第二次作业利用java语言编写计算器进行四则运算

    随着第一次作业的完成,助教 牛老师又布置了第二次作业:用java语言编写一个程序然后进行四则运算用户用键盘输入一个字符来结束程序显示统计结果.一开始看到这个题目我也着实吓了一跳 因为不知道如何下手而且 ...

  6. SparkGraphx计算指定节点的N度关系节点

    直接上代码: package horizon.graphx.util import java.security.InvalidParameterException import horizon.gra ...

  7. 初学Hadoop之计算TF-IDF值

    1.词频 TF(term frequency)词频,就是该分词在该文档中出现的频率,算法是:(该分词在该文档出现的次数)/(该文档分词的总数),这个值越大表示这个词越重要,即权重就越大. 例如:一篇文 ...

  8. 基于熵的方法计算query与docs相似度

    一.简单总结 其实相似度计算方法也是老生常谈,比如常用的有: 1.常规方法 a.编辑距离 b.Jaccard c.余弦距离 d.曼哈顿距离 e.欧氏距离 f.皮尔逊相关系数 2.语义方法 a.LSA ...

  9. 利用Java动态生成 PDF 文档

    利用Java动态生成 PDF 文档,则需要开源的API.首先我们先想象需求,在企业应用中,客户会提出一些复杂的需求,比如会针对具体的业务,构建比较典型的具备文档性质的内容,一般会导出PDF进行存档.那 ...

随机推荐

  1. 3.PHP内核探索:一次请求生命周期

    我们从未手动开启过PHP的相关进程,它是随着Apache的启动而运行的.PHP通过mod_php5.so模块和Apache相连(具体说来是SAPI,即服务器应用程序编程接口). PHP总共有三个模块: ...

  2. breadth-first depth-first best-first

    Computer Science An Overview _J. Glenn Brookshear _11th Edition For our example in Figure 11.7, we c ...

  3. ssi服务器端指令

    SSI使用详解 你是否曾经或正在为如何能够在最短的时间内完成对一个包含上千个页面的网站的修改而苦恼?那么可以看一下本文的介绍,或许能够对你有所帮助.什么是SSI?SSI是英文Server Side I ...

  4. mysql 数据库封装类:返回索引、关联、字符串数组;分页查询封装类 :$page=new Page(表的总条数,每页的条数);$sql = "".$page->limit; echo $page->fpage();

    <?php class czy { public $host="localhost"; //地址 public $uid="root"; //用户名 pu ...

  5. USB2.0协议笔记

    1.概述     USB(Universal Serial Bus)具有传输速率快,可热插拔等显著特点,应用已经十分广泛,目前的相当多的设备已经支持最新的USB3.0协议.理论上USB1.1的传输速度 ...

  6. Region的预分区

    1.预分区的方式 共有四种方式 2.帮助信息 help 'create' 3.第一种方式 4.在页面上查看效果(端口号:60010) 5.第二种方式 )创建文件,并在文件中书写分区的值 )创建表 6. ...

  7. JVM GC (一)

    1. 先来说GC工作在哪块区域呢? 程序计数器,虚拟机栈(也就平时所说的栈), 本地方法栈这三区域随着线程而生,随着线程而灭,出栈入栈的操作,在栈中分配配的多少内存都具 有确定性,在这几个区域就不用考 ...

  8. ArcGIS API for Silverlight代码中使用Template模板

    原文:ArcGIS API for Silverlight代码中使用Template模板 在项目开发中,会遇到点选中聚焦闪烁效果,但是因为在使用Symbol的时候,会设置一定的OffSetX和OffS ...

  9. EF不同查询方法生成的SQL比较

    var test1 = db.jj_RolesItem.Join(db.jj_SysItemsClass, m => m.ClassID, g => g.ClassID, (m, g) = ...

  10. [iOS]如何把App打包成ipa文件,然后App上架流程[利用Application Loader]

    摘自:http://www.cnblogs.com/wangqi1221/p/5240281.html 在上一篇博客已经讲过上传项目了,但是有的时候,需要我们进行打包成ipa包到别的手机上跑(但是前提 ...