首先介绍下SPMF,SPMF是一个采用Java开发的开源数据挖掘平台。它提供了51种数据挖掘算法实现,用于:
•序列模式挖掘,
•关联规则挖掘,
•frequent itemset 挖掘,
•顺序规则挖掘,
•聚类
这几天放假研究了下Apriori算法的源代码,把总结写下,好记性不如一个烂笔头,防止以后忘。
Apriori算法的主要步骤:
- 数据读取
- 生成频繁1项集
- 如何由频繁K-1项集生成候选Ck项集(候选项集内部剪枝:确保k阶候选项集的每一个k-1阶子集都是频繁的)
- 计数、剪枝生成频繁k项集
现在将以上步骤的核心源代码的注释和分析贴在下面,Apriori算法的源代码在此处下载(eclipse编译过,可用eclipse直接打开使用):DataMiningApriori
(1)数据读取
根据输入文件IO路径,按行读取文件,每一行按照空格“ ”分割,分割后存入数组中,然后存入map中,key是每一个项,value是key出现的次数,即使支持度计数。通过这个操作,便可获得每一个项及其支持度,并且把数据库存入database中。输入文件为本地txt文件,内容为:
1 3 4
2 3 5
1 2 3 5
2 5
1 2 3 5
Map<Integer, Integer> mapItemCount = new HashMap<Integer, Integer>();
database = new ArrayList<int[]>();
BufferedReader reader = new BufferedReader(new FileReader(input));
String line;
while (((line = reader.readLine()) != null)) {
if (line.isEmpty() == true ||
line.charAt(0) == '#' || line.charAt(0) == '%'
|| line.charAt(0) == '@') {
continue;
}
String[] lineSplited = line.split(" ");
int transaction[] = new int[lineSplited.length];
for (int i=0; i< lineSplited.length; i++) {
Integer item = Integer.parseInt(lineSplited[i]);
transaction[i] = item;
Integer count = mapItemCount.get(item);
if (count == null) {
mapItemCount.put(item, 1);
} else {
mapItemCount.put(item, ++count);
}
}
database.add(transaction);
}
(2)如何由频繁K-1项集生成候选Ck项集
当k=2时,由频繁1项集生成候选2项集。这个情况时比较简单,直接依次比较组合即可,源代码也是这么实现的,在生成候选项集前,对候选项集进行排列,使后选项集按照字典序列排列: