Apriori求频繁项集

使用语言Python

实现的算法:寻找频繁项集

源码如下:

# -*- coding: cp936 -*-
def candidate_gen(F_prior):#F_prior是一个双层list 为项目集
    '''候选项集集合生成函数'''
    candidate=[]
    print '下面进行合并:'
    for list1 in F_prior:
for list2 in F_prior:
   if list1!=None and list2!=None and list1!=list2 and list1[0:len(list1)-1]==list2[0:len(list2)-1]:
    list_tmp=list1+list2
    list_tmp.sort()
    assistset=set(list_tmp)
    tmp=[]
    while assistset!=set([]):
     tmp.append(assistset.pop())
    print '******************************'
    print'%s与%s融合生成%s'%(list1,list2,tmp)
    if tmp not in candidate:
                            candidate.append(tmp)
    print '下面进行剪枝:'
    for i in range(len(candidate),0,-1):
        sub_sets=get_subset(candidate[i-1])
        for myset in sub_sets:
            if myset not in F_prior:
                print'**************************'
                print'%s的k-1子集不是平凡项目集,故删除'%candidate[i-1]
                del candidate[i-1]
                break
    print '候选集总共有%s'%candidate
    return candidate
       
#**********************************************************#

           
def get_subset(myset):#myset 为候选集合中的一个k项目
    '''求K-项集的K-1子项集'''
    sub_sets=[]#为k-1项目集
    length=len(myset)
    sub_count=length-1
    for begin in range(0,length):
        end=begin+sub_count
        if end<=length:
            tmp=myset[begin:end]
            tmp.sort()
        else:
            end=end%length
            tmp=myset[begin:length]+myset[0:end]
            tmp.sort()
        if tmp not in sub_sets:
            sub_sets.append(tmp)
    return sub_sets
               
   
#********************************************************************#    
           
def AprioriFrequecySet(T,minsup,F_info):
    #F_info格式如下(list,support)它的初始值是F1
    F_total=[]
    F=[m[0]for m in F_info]
    k=2
    while len(F)>1:
        print k
        F_entire=[]#是F_info的结合
        F_temp=[]
        Candidates=candidate_gen(F)
        for can in Candidates:
            count=0
            for t in T:
                tmp_t=set(t)
                tmp_can=set(can)
                if tmp_can.issubset(tmp_t):
                    count=count+1
            can_tuple=(can,count)
                   
            F_temp.append(can_tuple)
        #F_entire=[m for m in F_temp if fm[1]>=minsup]
        for m in F_temp:
            support=float(m[1])/len(T)
            if float(m[1])/len(T)>=minsup:
                print '*********************'
                print '将(%s,%s)加入频繁项集,因为他的支持度%s大于最小支持度'%(m[0],m[1],support)
                F_entire.append(m)
        pause=raw_input('pleas wait a minute')
        F=[m[0] for m in F_entire]
        F_total=F_total+F_entire
        k=k+1
    return F_total
       
               
   
#######################################################################

参考书籍:《刘兵网络数据挖掘》

原文地址:https://www.cnblogs.com/finallyliuyu/p/1735838.html