设minsupport=0.4,利用Apriori算法求出所有的频繁项集,指出最大频繁项集。
数据集:
代码实现:
# 设minsupport=40%,利用Apriori算法求出所有的频繁项目集,指出其中的最大频繁项目集。
import pandas as pd
def get_D():
D = pd.read_csv("work1.csv",index_col='TID')
D = D['Itemset'].values.tolist()
for i in range(len(D)):
D[i] = D[i].split(',')
return D
def get_C1(D):
C1=[]
for index in D:
for item in index:
if not [item] in C1:
C1.append([item])
C1.sort()
return list(map(frozenset,C1))
def scanD(D,CK,minSupport):
ssCnt = {}
for index in D: # 遍历行
for can in CK: # 遍历Ck
if can.issubset(index):
if not can in ssCnt: # 计数
ssCnt[can]=1
else:
ssCnt[can]+=1
numItems = float(len(D))
retList = []
supportData={}
for key in ssCnt:
support = ssCnt[key]/numItems
if support>=minSupport:
retList.insert(0,key)
supportData[key]=support
return retList,supportData
#频繁项集两两组合
def aprioriGen(Lk,k):
retList=[]
lenLk = len(Lk)
for i in range(lenLk):
for j in range(i+1,lenLk):
L1=list(Lk[i])[:k-2];L2=list(Lk[j])[:k-2]
L1.sort();L2.sort()
if L1==L2:
retList.append(Lk[i]|Lk[j])
return retList
def apriori(D,minSupport=0.4):
C1=get_C1(D)
D=list(map(set,D))
L1,supportData =scanD(D,C1,minSupport)
L=[L1]
k=2
while(len(L[k-2])>0):
CK = aprioriGen(L[k-2],k)
Lk,supK = scanD(D,CK,minSupport)
supportData.update(supK)
L.append(Lk)
k+=1
return L,supportData
if __name__=='__main__':
D=get_D()
L,supportData=apriori(D)
L.pop()
print("所有的频繁项目集为:")
for i in range(len(L)):
print("L{}".format(i+1),L[i])
print("所有频繁项目集对应的支持度为:")
print(supportData)
print("最大频繁项目集为:",L[len(L)-1])