python3 aproiri算法(涉及字典来统计项集tupl作为key,int转化为tuple)

来源:互联网 发布:吉林大学网络自助中心 编辑:程序博客网 时间:2024/06/03 19:06

直接上代码,代码中都有注释:

# coding =utf-8import reimport sysimport bisectimport mathdef loadData():    Data = [[1,1,0,0,1],[1,1,0,0,0],[0,1,0,1,0],[1,1,0,1,0],[1,0,1,0,0],[1,1,1,0,1],        [1,1,1,0,0],[0,1,0,0,1],[0,1,1,1,0],[0,0,1,1,0]]    return Datadef frequent_1_itemSet(D,threshold):    index = set( range(len(D[0]))) #生成属性的索引    dict_index={}#属性索引与该属性的统计次数 形成字典    for i in index: #列扫描        for item in D: #行扫描            if 1==item[i]:                a=(i,) #int转化为tuple                dict_index[a]=dict_index.get(a,0)+1    A=[]    for key in dict_index.keys():        if dict_index[key]<threshold:            A.append(key)        for key in A:            del dict_index[key] #删除非频繁项及对应的索引            #index.remove(key)    return dict_index  #也可以返回字典,或集合,后面来看 还是返回字典好些def aproiri_gen(D,IDset,theshold,k=1):    if 0!=len(IDset):  #这个条件多余的,因为后面有一个判断空集        item =[]        if (type(IDset) is dict):            for i in IDset.keys():                for j in IDset.keys():  #字典的key对应为项集的索引tuple,字典key不能改,所以不能为list(w3c中有这句话)                                        a = len(set(i) & set(j)) #集合交集的个数                    b = len(set(i) | set(j)) #集合并集的个数                    if a==k-1 and b==k+1:    #这两个条件其实是等价的                        item.append(tuple(set(i)|set(j)))  #所有二项的组合,i,j为索引,        #统计        dict_count={}        for i1 in D: #行            for j1 in item: #列                result = 1                for k in range(len(j1)):                    result *= i1[j1[k]]                if result==1:  #因为数据是0,1,所有乘积为1则表明所有项都为1                    dict_count[j1] = dict_count.get(j1,0)+1        A=[]        for key in dict_count.keys():            if dict_count[key]<theshold:                a.append(key)        for key in A: #统一删除                del dict_count[key]        if 0!=len(dict_count):  #结束条件,如果新的频繁集为空,则不进行迭代,返回旧的频繁项            print(k)            print(dict_count) #打印每一次的项集            aproiri_gen(D,dict_count,theshold,k+1)               else:        print('error')def main():    data = loadData()    threshold = 2    IDset=frequent_1_itemSet(data,threshold)    max_item=aproiri_gen(data,IDset,threshold)    print(max_item)if __name__=='__main__':    main()


0 0
原创粉丝点击