Apriori algorithm is the originator of data mining if pattern mining, since the 60 's began to popular, its algorithm is very simple and naïve, first digging out the length of the frequent pattern of 1, and then k=2
Merging these frequent patterns into frequent patterns of length k, calculating their frequent occurrences, and ensuring that subsets of all k-1 lengths are frequent, it is worth noting that in order to avoid duplication, merging only those first k-2 characters are the same, while k-1 characters are less than the other side.
The following is the python implementation of the algorithm:
__author__ = ' Linfuyuan ' min_frequency = Int (raw_input (' Please input min_frequency: ')] file_name = raw_input (' please Input the transaction file: ') transactions = []def has_infrequent_subset (Candidate, Lk): For I in range (Len (candidate)): subset = Candidate[:-1] Subset.sort () if not ". Join (subset) in Lk:return False l Astitem = Candidate.pop () candidate.insert (0, LastItem) return truedef countfrequency (candidate, transactions): Count = 0 for transaction in Transactions:if Transaction.issuperset (candidate): Count + = 1 ret Urn Countwith Open (file_name) as F:for line in F.readlines (): line = Line.strip () tokens = Line.split (', ' If Len (tokens) > 0:transaction = set (tokens) transactions.append (transaction) CURRENTFR Equencyset = {}for transaction in Transactions:for item in transaction:time = Currentfrequencyset.get (item, 0) Currentfrequencyset[iteM] = time + 1Lk = set () for (Itemset, Count) in Currentfrequencyset.items (): If Count >= min_frequency:Lk.add (itemset) print ', '. Join (LK) while Len (lk) > 0:newlk = set () for Itemset1 in Lk:for Itemset2 in LK: Cancombine = True for i in range (len (ITEMSET1)): If I < Len (itemset1)-1: Cancombine = itemset1[i] = = Itemset2[i] If not cancombine:break Else:cancombine = Itemset1[i] < Itemset2[i] if not cancombine: break if Cancombine:newitemset = [] for char in ITEMSET1: Newitemset.append (char) newitemset.append (itemset2[-1]) if Has_infrequent_subset (n Ewitemset, Lk) and Countfrequency (Newitemset, transactions) >= Min_frequency:newLk.add (". Join (Newi Temset)) print ', '. JOin (newlk) Lk = Newlk
Python implementation of Apriori algorithm