JAVA实现FP_Growth算法(附详细注释)
在学习数据挖掘的过程中,必然会接触到FP_Growth算法。
而FP_Growth算法需要使用大量的递归调用,比较难以理解和实践,作者在网上多番搜寻也没有找到一个完整详细解释的FP_Growth代码,可能是高手大多不屑于解释自己的代码,无奈只能自己动手,有不足之处请多谅解。
程序编写过程中部分参考了JAVA实现FP-GROWTH算法https://www.cnblogs.com/liguangsunls/p/6892482.html,数据集使用的是FP-Tree算法的实现https://www.cnblogs.com/zhangchaoyang/articles/2198946.html中的trolley.txt。
具体实现
作者编写了两个类来实现FP_Growth算法的相关功能,其中TreeNode类用以保存树结点的信息,FPTree类用以实现需要用到的各种方法。
TreeNode类
import java.util.ArrayList;
import java.util.Comparator;
public class TreeNode{
private String name; //项名称
private int count; //支持度
private TreeNode parent; //父结点
private ArrayList<TreeNode> childs; //子结点(列表)
private TreeNode nextSameNode; //指向下一个相同结点
public TreeNode() {
super();
}
public TreeNode(String name, int count) {
super();
this.name = name;
this.count = count;
this.childs = new ArrayList<TreeNode>();
this.parent = null;
this.nextSameNode = null;
}
public TreeNode(String name, int count, TreeNode parent) {
super();
this.name = name;
this.count = count;
this.childs = new ArrayList<TreeNode>();
this.parent = parent;
this.nextSameNode = null;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public TreeNode getParent() {
return this.parent;
}
public boolean hasParent(){
return this.parent == null ? false : true;
}
public void setParent(TreeNode parent) {
this.parent = parent;
}
public void addChild(TreeNode child){
this.childs.add(child);
}
public void addChilds(ArrayList<TreeNode> childs){
this.childs.addAll(childs);
}
public void delChild(TreeNode child){
this.childs.remove(child);
}
public TreeNode getNextSameNode() {
return this.nextSameNode;
}
public boolean hasNextSameNode(){
return this.nextSameNode == null ? false : true;
}
public void setNextSameNode(TreeNode nextSameNode) {
this.nextSameNode = nextSameNode;
}
public ArrayList<TreeNode> getChilds() {
return childs;
}
public void inc(int i){
this.count += i;
}
@Override
public String toString() {
return this.getName() + ":" + this.getCount();
}
}
/*
* @function:为实现使用Collections.sort方法对泛型为TreeNode的List进行排序,需要实现Comparator接口
*/
class TreeNodeSort implements Comparator<TreeNode>{
@Override
public int compare(TreeNode o1, TreeNode o2) {
int result = Integer.compare(o2.getCount(), o1.getCount()); //实现降序排列
//int result = Integer.compare(o1.getCount(), o2.getCount()); //实现升序排列
if(result != 0)
return result;
return o1.getName().compareTo(o2.getName