Java计算TF-IDF值
2016-03-11 15:05
387 查看
在自然语言处理中,TF-IDF模型的计算是一种很基础的方式,在很多地方都会去使用。但是由于TF-IDF的计算一般涉及到的是一个稀疏矩阵的计算,本部分使用Map来完成对TF-IDF的构建。
计算完成后,可以通过类的get方法来对计算所得的TF以及IDF的值。其中
tf格式:( 文件路径名 : ( 单词 : 词频 ) )
idf格式:( 单词 : IDF )
计算完成后,可以通过类的get方法来对计算所得的TF以及IDF的值。其中
tf格式:( 文件路径名 : ( 单词 : 词频 ) )
idf格式:( 单词 : IDF )
import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import files.FileIO; public class TFIDF { // tf格式:( 文件路径名 : ( 单词 : 词频 ) ) final private Map<String , HashMap<String, Integer>> tf = new HashMap<>(); final private Map<String, Integer> df = new HashMap<String, Integer>(); // idf格式:( 单词 : IDF ) final private Map<String, Double> idf = new HashMap<String, Double>(); final private String corpusPath; final private String charSet; /** * 获取计算所得的TF值 * @return */ public Map<String , HashMap<String, Integer>> getTf() { return tf; } /** * 获取计算所得的IDF值 * @return */ public Map<String, Double> getIdf() { return idf; } /** * 初始化类 * @param corpusPath 待计算TF-IDF的文件夹 * @param charSet 文件夹下文件的编码格式 */ public TFIDF(String corpusPath , String charSet) { this.corpusPath = corpusPath; this.charSet = charSet; } /** * 计算TF-IDF值 * @throws IOException */ public void calculate() throws IOException { int number = 0; number = forAllFiles(number , new File(corpusPath)); for (Entry<String, Integer> entry : df.entrySet()) { idf.put(entry.getKey(), Math.log(1.0 * number / entry.getValue())); } } private int forAllFiles(int number , File path) throws UnsupportedEncodingException, FileNotFoundException, IOException { if(path.isFile()) { number ++; String text = FileIO.readFile(path, charSet); HashMap<String , Integer> temp = new HashMap<>(); for (String string : text.split("\\s+")) { if(temp.containsKey(string)) { temp.put(string, 1 + temp.get(string)); } else { temp.put(string, 1); } } tf.put(path.getAbsolutePath(), temp); for (String string : temp.keySet()) { if(df.containsKey(string)) { df.put(string, 1 + df.get(string)); } else { df.put(string, 1); } } } else if(path.isDirectory()) { for (File file : path.listFiles()) { number = forAllFiles(number , file); } } return number; } final public static String readFile(File file, String charset) throws UnsupportedEncodingException, FileNotFoundException, IOException { StringBuilder re = new StringBuilder(); String line = ""; try (BufferedReader br = new BufferedReader( new InputStreamReader( new FileInputStream(file), charset))) { while ((line = br.readLine()) != null) { re.append(line + "\n"); } } return re.toString(); } }
相关文章推荐
- python实现TF-IDF算法解析
- 基于语法树的语句识别算法
- 长期招聘:自然语言处理工程师
- 长期招聘:个性化推荐
- LDA学习心得
- comodo中国招聘 搜索与自然语言工程师
- 统计学习的几种方法
- mini edit distance & minimum cost alignment
- 最大熵模型介绍
- 数学之美 系列一 -- 统计语言模型
- 数学之美 系列三 -- 隐含马尔可夫模型在语言处理中的应用
- 数学之美 系列七 -- 信息论在信息处理中的应用
- 数学之美 系列八-- 贾里尼克的故事和现代语言处理
- Google 黑板報 - 數學之美系列
- 图像处理工程师的要求
- 人工智能
- 特征表示与lucene
- 号召
- 数学之美 系列一 -- 统计语言模型