信息时代,大数据成为一切操作的基石,即使是人工智能及深度学习相关领域也离不开数据的支撑。因此文本挖掘、图像处理等基础技术愈加重要,本文将着重介绍文本挖掘中的加权算法——TF-idf及其Java实现。
概况简介
TF-idf常被作为一种统计算法对分词结果进行加权排序,以得出文本中重要的一些词汇,因此可以视作分类算法或评级算法。显然从其名字我们可以轻松地知道,该算法由两部分组成,TF及idf。
TF(Term Frequency,词频)指的是在一段文本中,某一词汇出现的频率。idf(inverse document frequency,逆文本频率)指的是许多文件中某一词汇的重要程度。你可以前往维基中国查看更多详细的内容。
实现
网上不乏该算法的实现,但均乏善可陈且本人钟情于Java,故开发了Java实现。
语料分词
作者采用优秀的国产开源分词软件HanLP进行分词,对它有兴趣的同学可自行前往其Github主页学习。1
NotionalTokenizer.segment(corpusText.toString());
TF值求取
1 | /** |
idf值求取
1 | ** |
测试
我将使用纳兰性德的190+首诗词作品作为语料来源,并将其TF值及TF-idf结果分别输出。如果你需要类似的诗词语料,可以考虑使用我最近的开源工具进行爬取。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34public class TF_IDFUtilsTests {
private List<String> fileList;
@Before
public void initialDate() throws IOException {
String route = Resources.getResource("text_mining/poems").getPath(), result = "";
List<File> files = FilesUtil.getAllFiles(route, 2);
fileList = new ArrayList<>();
for (File file : files) {
fileList.add(FileUtils.readFileToString(file, "UTF-8"));
}
}
@Test
public void countTF_IDF() {
// HanLP.Config.enableDebug();
String result = TF_IDFUtils.countIDF(fileList, true);
System.out.println(result);
}
@Test
public void countTF() {
StringBuilder result = new StringBuilder();
Map<String, Integer> tfMap = TF_IDFUtils.countTFByText(fileList, true);
List<Map.Entry<String, Integer>> tfArrayList = new ArrayList<>(tfMap.entrySet());
tfArrayList.sort(Comparator.comparing(Map.Entry::getValue));
result.append("--------------TF Result--------------\n");
for (Map.Entry<String, Integer> entry : tfArrayList) {
result.append(entry.getKey()).append("\t").append(entry.getValue()).append("\n");
}
System.out.println(result.toString());
}
}
结果展示:
其他
- 诗词作品爬取: https://github.com/Yodeser/PoemsCrawler
- 分词软件hanLP: https://github.com/hankcs/HanLP
- 维基百科_TF-idf:https://zh.wikipedia.org/wiki/Tf-idf
- 垂直爬虫框架: https://github.com/code4craft/webmagic