文档的词频-反向文档频率(TF-IDF)计算

TF-IDF计算:

TF-IDF反映了在文档集合中一个单词对一个文档的重要性,经常在文本数据挖据与信息

提取中用来作为权重因子。在一份给定的文件里,词频(termfrequency-TF)指的是某一

个给定的词语在该文件中出现的频率。逆向文件频率(inversedocument frequency,

IDF)是一个词语普遍重要性的度量。某一特定词语的IDF,可以由总文件数目除以包含

该词语之文件的数目,再将得到的商取对数得到。

相关代码:

[java] view plain copy
  1. privatestaticPatternr=Pattern.compile("([\\t{}()\",:;.\n])");
  2. privatestaticList<String>documentCollection;
  3. //CalculatesTF-IDFweightforeachtermtindocumentd
  4. privatestaticfloatfindTFIDF(Stringdocument,Stringterm)
  5. {
  6. floattf=findTermFrequency(document,term);
  7. floatidf=findInverseDocumentFrequency(term);
  8. returntf*idf;
  9. }
  10. privatestaticfloatfindTermFrequency(Stringdocument,Stringterm)
  11. {
  12. intcount=getFrequencyInOneDoc(document,term);
  13. return(float)((float)count/(float)(r.split(document).length));
  14. }
  15. privatestaticintgetFrequencyInOneDoc(Stringdocument,Stringterm)
  16. {
  17. intcount=0;
  18. for(Strings:r.split(document))
  19. {
  20. if(s.toUpperCase().equals(term.toUpperCase())){
  21. count++;
  22. }
  23. }
  24. returncount;
  25. }
  26. privatestaticfloatfindInverseDocumentFrequency(Stringterm)
  27. {
  28. //findtheno.ofdocumentthatcontainstheterminwholedocumentcollection
  29. intcount=0;
  30. for(Stringdoc:documentCollection)
  31. {
  32. count+=getFrequencyInOneDoc(doc,term);
  33. }
  34. /*
  35. *logoftheratiooftotalnoofdocumentinthecollectiontotheno.ofdocumentcontainingtheterm
  36. *wecanalsouseMath.Log(count/(1+documentCollection.Count))todealwithdividebyzerocase;
  37. */
  38. return(float)Math.log((float)documentCollection.size()/(float)count);
  39. }
建立文档的向量空间模型Vector Space Model并计算余弦相似度。

相关代码:

[java] view plain copy
  1. publicstaticfloatfindCosineSimilarity(float[]vecA,float[]vecB)
  2. {
  3. floatdotProduct=dotProduct(vecA,vecB);
  4. floatmagnitudeOfA=magnitude(vecA);
  5. floatmagnitudeOfB=magnitude(vecB);
  6. floatresult=dotProduct/(magnitudeOfA*magnitudeOfB);
  7. //when0isdividedby0itshowsresultNaNsoreturn0insuchcase.
  8. if(Float.isNaN(result))
  9. return0;
  10. else
  11. return(float)result;
  12. }
  13. publicstaticfloatdotProduct(float[]vecA,float[]vecB)
  14. {
  15. floatdotProduct=0;
  16. for(inti=0;i<vecA.length;i++)
  17. {
  18. dotProduct+=(vecA[i]*vecB[i]);
  19. }
  20. returndotProduct;
  21. }
  22. //Magnitudeofthevectoristhesquarerootofthedotproductofthevectorwithitself.
  23. publicstaticfloatmagnitude(float[]vector)
  24. {
  25. return(float)Math.sqrt(dotProduct(vector,vector));
  26. }
注意点

零词过滤(stop-words filter)

零词列表

ftp://ftp.cs.cornell.edu/pub/smart/english.stop

关于TF-IDF参考这里:

链接–>http://en.wikipedia.org/wiki/Tf*idf


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值