第八章全部代码

本文介绍了使用Apriori算法从购物篮数据中提取频繁项集,并生成关联规则的过程。通过Python实现的apriori、generateRules等函数,展示了如何分析顾客行为,发现商品之间的购买规律。涉及数据预处理、频繁项集计算、置信度评估和规则生成等关键步骤。
摘要由CSDN通过智能技术生成
def loadDataSet():
    return [[1, 2, 5],[2, 4],[2, 3],[1, 2, 4],[1, 3],[2, 3],[1, 3],[1, 2, 3, 5],[1, 2, 3]]
D=loadDataSet()
print(D)



def createC1(dataSet):
    C = []
    for transaction in dataSet:
        for item in transaction:
            if [ item ] not in C:
                C.append([item])
    C.sort()
    return list(map(frozenset,C))
    
C1=createC1(D)
print(C1)


def scanD(D, Ck, minSupport):
    ssCnt = {}
    for tid in D:
        for can in Ck:     
            if can.issubset(tid):
                ssCnt[can] = ssCnt.get(can, 0) + 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

ret1,suD = scanD(loadDataSet(),createC1(loadDataSet()),0.22)
print(ret1)
print(suD)



def aprioriGen(Ck, k):
    retList = []
    lenCk = len(Ck)
    for i in range( lenCk ):
        for j in range( i + 1, lenCk ):
            L1 = Ck[i]|Ck[j]
            if(len(L1)==k):
                if L1 not in retList:
                    retList.append( L1 ) 
    return retList

ret2=aprioriGen(C1, 2)
print(ret2)

ret3=aprioriGen(ret2,3)
print(ret3)




def apriori(D, minSupport):
    C1=createC1(D)
    L1, suppData = 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) 
        suppData.update(supK) 
        L.append(Lk)
        print("L:%s" %L)
        k += 1
    return L, suppData

L1,suD2=apriori(D,0.22)
print("The final support rate is %s" %suD2)



def calcConf(freqSet, H, supportData, brl, minConf=0.7):
    prunedH = []
    for conseq in H:
        conf = supportData[freqSet] / supportData[freqSet - conseq]
        if conf >= minConf:
            print(freqSet - conseq, '-->', conseq, 'conf:', conf)
            brl.append((freqSet - conseq, conseq, conf))
            prunedH.append(conseq)
    return prunedH


def rulesFromConseq(freqSet, H, supportData, brl, minConf=0.7):
    m = len(H[0])  
    if len(freqSet) > m+1:
        Hmp1 = aprioriGen(H, m+1)
        Hmp1 = calcConf(freqSet, Hmp1, supportData, brl, minConf)
        if len(Hmp1) > 1:
            rulesFromConseq(freqSet, Hmp1, supportData, brl, minConf)


def generateRules(L, supportData, minConf=0.7):
    bigRuleList = []
    for i in range(1, len(L)):
        for freqSet in L[i]:
            H1 = [frozenset([item]) for item in freqSet]
            if i >1:
                rulesFromConseq(freqSet, H1, supportData, bigRuleList, minConf)
            else:
                calcConf(freqSet, H1, supportData, bigRuleList, minConf)
    return bigRuleList

bRlist = generateRules(L1,suD2,0.1)


第八章复习思考题2


import pandas as pd
import numpy as np

origData = pd.read_csv("basketdata.txt")
goodsArray=[]
for indexs in origData.index:
    goodsSeries=[]
    if (origData.loc[indexs,'fruitveg']=="T"):
        goodsSeries.append(1)
    if (origData.loc[indexs,'freshmeat']=="T"):
        goodsSeries.append(2)
    if (origData.loc[indexs,'dairy']=="T"):
        goodsSeries.append(3)
    if (origData.loc[indexs,'cannedveg']=="T"):
        goodsSeries.append(4)
    if (origData.loc[indexs,'cannedmeat']=="T"):
        goodsSeries.append(5)
    if (origData.loc[indexs,'frozenmeal']=="T"):
        goodsSeries.append(6)    
    if (origData.loc[indexs,'beer']=="T"):
        goodsSeries.append(7)
    if (origData.loc[indexs,'wine']=="T"):
        goodsSeries.append(8)
    if (origData.loc[indexs,'softdrink']=="T"):
        goodsSeries.append(9)
    if (origData.loc[indexs,'fish']=="T"):
        goodsSeries.append(10)
    if (origData.loc[indexs,'confectionery']=="T"):
        goodsSeries.append(11)
    goodsArray.append(goodsSeries)
    if(origData.loc[indexs,'age']<30):
        origData.loc[indexs,'ageGroup']=1
    elif(origData.loc[indexs,'age']<50):
        origData.loc[indexs,'ageGroup']=2
    else:
        origData.loc[indexs,'ageGroup']=3

   
L1, suppData = apriori(goodsArray, 0.15)
print("频繁项集L:", L1)
print("所有候选项集的支持度信息:", suppData)
print("所有规则的置信度信息:")
rules1 = generateRules(L1,suppData,0.15)

#简单分析不同年龄段的啤酒购买比例
beerData = origData[['beer','ageGroup']]
print(beerData.groupby([beerData['ageGroup'],beerData['beer']]).size())

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值