Java Implementation Fp-growth algorithm

Source: Internet
Author: User

This paper Jiawei Han the sixth chapter of "Data mining-concept and technology", the precondition is to understand the Apriori algorithm.

Another well-written article is recommended here:

Http://hi.baidu.com/nefzpohtpndhovr/item/9d5c371ba2dbdc0ed1d66dca

0. Experimental data set: User2items.csv

I1,i2,i5i2,i4i2,i3i1,i2,i4 I1,i3 I2,i3i1,i3i1,i2,i3,i5i1,i2,i3

1. Algorithm principleConstruction Fptree
1. First read all kinds of items in the database and the count of the support of these items.

Into the ittotal linked list.
2, the ittotal linked list according to the support of the count from the big to the small sort
3. Insert the Ittotal linked list into the ITEMTB table
4, the second reads the transaction in the database, inserting the items in the transaction into the tree in the order of the support count from large to small.


5. Traverse the tree to connect the nodes that belong to the same item through the BNode pointer.
In this program, all the itemsets are stored in Fp-tree, and the minimum support is not considered.

Only consider minimum support when mining frequent itemsets in fp-growth

/** * * @param Records Records of the build tree, such as I1,i2,i3 * @param header in Korean book * @return return to the built tree */public TreeNode2 builderfptree (Linke   Dlist<linkedlist<string>> records,list<treenode2> header) {TreeNode2 root;   if (Records.size () <=0) {return null;   } root=new TreeNode2 ();  for (linkedlist<string> items:records) {itemsort (Items,header); AddNode (Root,items,header);} String dd= "DD"; String Test=dd;return Root;} When there is already a branch, infer whether the new node belongs to a node of that branch. or all coincident, recursive public TreeNode2 addNode (TreeNode2 root,linkedlist<string> items,list<treenode2> header) {if ( Items.size () <=0) return null; String item=items.poll ();//The child node of the current node does not include the node. Then create a branch in addition. TreeNode2 Node=root.findchild (item), if (node==null) {node=new TreeNode2 (); Node.setname (item); Node.setcount (1); no De.setparent (Root), Root.addchild (node), and/or add the nodes of each name to the chain header for (TreeNode2 head:header) {if (Head.getname (). Equals (item ) {while (head.getnexthomonym ()!=null) {head=head.getnexthomonym ();} head.setnexthomonym (node); break;}} //Add each node to the chain header}else{node.setcount (Node.getcount () +1);} addNode (Node,items,header); return root;} 




fp_growth algorithm:
Get the first item I1 from the ITEMTB table of a fptree. Assume that the support count for this item satisfies the minimum support count of {
1. Add the item I1 to the data structure itemset of the frequent itemsets to which the mining is stored
2. Obtain the conditional model base of the I1 in the current fptree. The prefix path to the node of the item in the tree (the entry is no longer included in the path).
Note that the support count for each item in the conditional pattern base of the item I1 is equal. equals the support count for the item I1
3. Each path is considered a transaction, the condition of which is constructed using these paths fptree, and the fp_growth algorithm is called recursively.
When the fp_growth algorithm is called recursively, those items that are larger than the support count are stored in itemset as the child node of the item I1.
}

I think that if we want to understand better, or if there is something unclear, we should take a test.HTTP://HI.BAIDU.COM/NEFZPOHTPNDHOVR/ITEM/9D5C371BA2DBDC0ED1D66DCA
This article of this place, see.



public void Fpgrowth (linkedlist<linkedlist<string>> records,string Item) {//saves individual records of the new conditional pattern base, Once again constructed fp-treelinkedlist<linkedlist<string>> newrecords=new linkedlist<linkedlist<string> > ();//Build Chain head linkedlist<treenode2> Header=buildheaderlink (records);//Create Fp-treetreenode2 fptree= Builderfptree (Records,header);//End recursion condition if (header.size () <=0| | Fptree==null) {System.out.println ("-----------------"); return;} Print the result, output frequent itemsets if (item!=null) {//Search for conditional pattern base, start from the end of the chain for (int i=header.size () -1;i>=0;i--) {TreeNode2 head=header.get (i); String itemname=head.getname (); Integer Count=0;while (head.getnexthomonym ()!=null) {head=head.getnexthomonym ();// Number of leaves Count equals. Even how many records count=count+head.getcount ();} Print frequent itemsets System.out.println (Head.getname () + "," +item+ "\ T" +count);} Look for the conditional pattern base, start at the end of the chain for (int i=header.size () -1;i>=0;i--) {TreeNode2 head=header.get (i); String itemname;//Re-assembly if (Item==null) {itemname=head.getname ();} Else{itemname=head.getname () + "," +item;} while (head.getnexthomonym ()!=null) {Head=head. getnexthomonym ();///leaf count equals how much, even if how many records integer Count=head.getcount (); for (int n=0;n<count;n++) {linkedlist<   String> record=new linkedlist<string> ();   Toroot (Head.getparent (), record); Newrecords.add (record);}}    System.out.println ("-----------------");//recursion, in order to Fp-treefpgrowth (Newrecords,itemname);} }


structure of the 2.treeprivate String name;//node names
Private Integer count; Count
Private TreeNode2 parent; Parent node
Private list<treenode2> children; Child nodes
Private TreeNode2 nexthomonym; Next node with the same name
See the TreeNode2 class below3. Complete source code:two copies. java files, which can be run directly into eclipse.
Package Mysequence.machineleaning.association.fpgrowth;import Java.io.bufferedreader;import Java.io.fileinputstream;import Java.io.ioexception;import Java.io.inputstreamreader;import java.util.ArrayList; Import Java.util.collections;import java.util.hashmap;import Java.util.linkedlist;import Java.util.List;import Java.util.map;import Java.util.set;public class Myfptree2 {public static final int supported = 2;//set minimum support frequency to 2//save First Order P Ublic map<string,integer> ordermap=new hashmap<string,integer> ();p ublic LinkedList<LinkedList< String>> readF1 () throws IOException {linkedlist<linkedlist<string>> records=new LinkedList<Lin Kedlist<string>> ();//string filepath= "Scripts/clustering/canopy/canopy.dat"; String filepath= "Datafile/association/user2items.csv";        BufferedReader br = new BufferedReader (new InputStreamReader (New FileInputStream (FilePath)));           for (String line = Br.readline (), line = null, line = Br.readline ()) { if (Line.length () ==0| | "".        Equals (line)) continue;           String[] Str=line.split (",");        Linkedlist<string> litm=new linkedlist<string> ();        for (int i=0;i<str.length;i++) {Litm.add (Str[i].trim ());                     } records.add (LITM);        } br.close ();    return records; }//creating a header chain public linkedlist<treenode2> Buildheaderlink (Linkedlist<linkedlist<string>> Records) { Linkedlist<treenode2> header=null;if (Records.size () >0) {header=new linkedlist<treenode2> ();} Else{return null;} map<string, treenode2> map = new hashmap<string, treenode2> (); for (linkedlist<string> items:records) {for (String item:items) {//If there is an increase of 1, there is no new if (Map.containskey (item)) {Map.get (item). Sum (1);}             Else{treenode2 node=new TreeNode2 (); Node.setname (item); Node.setcount (1); Map.put (item, node);}        }}//Increase the number of items with a support level greater than (or equal to) Minsup to F1 set<string> names = Map.keyset ();    for (String name:names) {        TreeNode2 tnode = map.get (name);            if (Tnode.getcount () >= support) {Header.add (tnode);        }} sort (header); String test= "ddd"; return header;} Sort by selection, assuming equal number of times, sort by name, dictionary order, lowercase after uppercase public list<treenode2> sort (list<treenode2> List) {int len=list.size () ; for (int i=0;i<len;i++) {for (int j=i+1;j<len;j++) {TreeNode2 node1=list.get (i); TreeNode2 Node2=list.get (j); if (Node1.getcount () <node2.getcount ()) {TreeNode2 tmp=new TreeNode2 (); tmp=node2; List.remove (j);//list the specified position is inserted, the original &GT;=J element will move down and will not be deleted, so remove the original element List.add (j,node1) before inserting; List.remove (i); List.add (I, TMP);} If the number of times is equal, sort by name, dictionary order, first lowercase and then uppercase if (Node1.getcount () ==node2.getcount ()) {String name1=node1.getname (); String name2=node2.getname (); int Flag=name1.compareto (name2); if (flag>0) {TreeNode2 tmp=new TreeNode2 (); tmp=node2 ; List.remove (j);//list the specified position is inserted, the original &GT;=J element will move down. Will not be deleted, so remove the original element List.add (J,NODE1) before inserting it; List.remove (i); List.add (i,tmp);}}} return list;} Sorting by selection method. Descending, assuming that the same name is sorted by the order in L public list<String> itemsort (linkedlist<string> lis,list<treenode2> header) {//list<string> list=new Arraylist<string> ();//Selection method sort int len=lis.size (); for (int i=0;i<len;i++) {for (int j=i+1;j<len;j++) {String Key1=lis.get (i); String Key2=lis.get (j); Integer Value1=findcountbyname (Key1,header); if (value1==-1) Continue;integer value2= Findcountbyname (Key2,header); if (value2==-1) continue;if (value1<value2) {String tmp=key2;lis.remove (j); Lis.add ( J,key1); Lis.remove (i); Lis.add (i,tmp);} if (value1==value2) {int v1=ordermap.get (key1); int v2=ordermap.get (KEY2); if (v1>v2) {String Tmp=key2;lis.remove (j)     ; Lis.add (j,key1); Lis.remove (i); Lis.add (i,tmp);}} }}return Lis;} Public Integer findcountbyname (String itemname,list<treenode2> header) {Integer count=-1;for (TreeNode2 node: header) {if (Node.getname (). Equals (ItemName)) {count= node.getcount ();}} return count;} /** * * @param Records Records of the build tree, such as I1,i2,i3 * @param header in Korean book * @return return to the built tree */public TreeNode2 builderfptree (Linke dlist&Lt   Linkedlist<string>> records,list<treenode2> header) {TreeNode2 root;   if (Records.size () <=0) {return null;   } root=new TreeNode2 ();  for (linkedlist<string> items:records) {itemsort (Items,header); AddNode (Root,items,header);} String dd= "DD"; String Test=dd;return Root;} When there is already a branch in existence. Infers whether the new node belongs to a node of the branch. or all coincident, recursive public TreeNode2 addNode (TreeNode2 root,linkedlist<string> items,list<treenode2> header) {if ( Items.size () <=0) return null; String item=items.poll ();//The child node of the current node does not include the node, then another branch is created.

TreeNode2 Node=root.findchild (item), if (node==null) {node=new TreeNode2 (); Node.setname (item); Node.setcount (1); no De.setparent (Root), Root.addchild (node),//Add each node to the chain header for (TreeNode2 head:header) {if (Head.getname (). Equals (item)) { while (head.getnexthomonym ()!=null) {head=head.getnexthomonym ();} head.setnexthomonym (node); break;}} Add each node to the chain header}else{node.setcount (Node.getcount () +1);} addNode (Node,items,header); return root;} Find the root node from the leaf. Recursive public void Toroot (TreeNode2 node,linkedlist<string> NewRecord) {if (node.getparent () ==null) return; String name=node.getname (); Newrecord.add (name); Toroot (Node.getparent (), NewRecord);} The conditional Fp-tree tree is combined in order to make frequent itemsets public void Combineitem (TreeNode2 node,linkedlist<string> newrecord,string Item) {if ( Node.getparent () ==null) return; String name=node.getname (); Newrecord.add (name); Toroot (Node.getparent (), NewRecord);} fp-growthpublic void Fpgrowth (linkedlist<linkedlist<string>> records,string Item) {//save individual records of the new conditional pattern base, To construct Fp-treelinkedlist<linkedl againIst<string>> newrecords=new linkedlist<linkedlist<string>> ();//Build Chain head Linkedlist<treenode2 > Header=buildheaderlink (Records);//Create Fp-treetreenode2 fptree= builderfptree (records,header);//End recursion condition if ( Header.size () <=0| | Fptree==null) {System.out.println ("-----------------"); return;} Print the result, output frequent itemsets if (item!=null) {//Search for conditional pattern base, start from the end of the chain for (int i=header.size () -1;i>=0;i--) {TreeNode2 head=header.get (i); String itemname=head.getname (); Integer Count=0;while (head.getnexthomonym ()!=null) {head=head.getnexthomonym ();// Number of leaves Count equals. Even how many records count=count+head.getcount ();} Print frequent itemsets System.out.println (Head.getname () + "," +item+ "\ T" +count);} Look for the conditional pattern base, start at the end of the chain for (int i=header.size () -1;i>=0;i--) {TreeNode2 head=header.get (i); String itemname;//Re-assembly if (Item==null) {itemname=head.getname ();} Else{itemname=head.getname () + "," +item;} while (head.getnexthomonym ()!=null) {head=head.getnexthomonym ();//leaf count equals how much, even if how many records integer Count=head.getcount ( ); for (int n=0;n<count;n++) {linkedlist<string> record=newLinkedlist<string> (); Toroot (Head.getparent (), record); Newrecords.add (record);}} System.out.println ("-----------------");//recursion, in order to Fp-treefpgrowth (Newrecords,itemname);} }//Save order. This step can also be omitted, in order to reduce the trouble of reprocessing results add public void orderF1 (linkedlist<treenode2> orderheader) {for (int i=0;i< Orderheader.size (); i++) {TreeNode2 node=orderheader.get (i); Ordermap.put (Node.getname (), i);}} public static void Main (string[] args) throws IOException {//TODO auto-generated method stub/*string s1= "I1"; int flag=s1. CompareTo ("I1"); SYSTEM.OUT.PRINTLN (flag); *///read Data Myfptree2 fpg=new Myfptree2 (); Linkedlist<linkedlist<string>> records=fpg.readf1 (); Linkedlist<treenode2> Orderheader=fpg.buildheaderlink (records); Fpg.orderf1 (OrderHeader); Fpg.fpgrowth (Records,null);}}


Structure of the tree:
Package Mysequence.machineleaning.association.fpgrowth;import Java.util.arraylist;import Java.util.List;public    Class TreeNode2 implements comparable<treenode2>{private String name;//node name private Integer count;//Count Private TreeNode2 parent; Parent node private list<treenode2> children; Child node private TreeNode2 nexthomonym; The next node with the same name, public TreeNode2 () {}public String getName () {return name;} public void SetName (String name) {this.name = name;} Public Integer GetCount () {return count;} public void SetCount (Integer count) {This.count = count;} public void Sum (Integer count) {This.count =this.count+count;} Public TreeNode2 getParent () {return parent;} public void SetParent (TreeNode2 parent) {this.parent = parent;} Public list<treenode2> GetChildren () {return children;} public void Setchildren (list<treenode2> children) {This.children = children;} Public TreeNode2 getnexthomonym () {return nexthomonym;} public void setnexthomonym (TreeNode2 nexthomonym) {this.nexthomonym = nexthomonym;} /** * Join a node * @param child */public void AddChild (TreeNode2 child) {if (This.getchildren () = = nul            L) {list<treenode2> List = new arraylist<treenode2> ();            List.add (child);        This.setchildren (list);        } else {This.getchildren (). Add (child);  }}/** * exists for that node, there is no return to that node, there is no return null * @param name * @return */public TreeNode2 Findchild (String name)        {list<treenode2> children = This.getchildren ();                    if (children! = null) {for (TreeNode2 Child:children) {if (Child.getname (). Equals (name)) {                return child;    }}} return null; } @Override public int compareTo (TreeNode2 arg0) {//TODO auto-generated method stub int count0 = arg        0.getCount (); Is the opposite of the default size.    Causes the call to Arrays.sort () to be sorted in descending order of return count0-this.count; }}




Java Implementation Fp-growth algorithm

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.