Merge pull request #35 from jiangzhonglian/master

更新完10 Apriori算法
This commit is contained in:
ApacheCN
2017-03-17 12:56:50 +08:00
committed by GitHub
10 changed files with 8506 additions and 215 deletions

BIN
docs/11.交易清单.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 278 KiB

View File

@@ -1,9 +1,36 @@
# 11.使用Apriori算法进行关联分析 #
**- 概念**
# 11) 使用Apriori算法进行关联分析
1. 关联关系:associati analysis 从大规模数据集中寻找物品间的隐含关系呗称作关联关系或者关联规则学习。关系有两种形式:频繁项集(经常一块出现的物品集合);关联规则(暗示两种物品之间可能存在很强的关系)
2. 项集的支持度(support):数据集中包含该项集的记录所占的比例
3. 置信度(confidence):置信度({A}->{B}) = 支持度{A,B}/支持度{A}
Apriori原理:如果某个项集是频繁的,那么它的所有子集也是频繁的,反之,一个项集是非频繁的,那么它的所有超集也是非频繁的。
* 使用场景:
* 目的:商店希望从客户身上获取尽可能多的利润。
* 忠诚度计划: 通过顾客的会员卡可获取已定的折扣,商店也可以了解客户购买的商品; 不买会员卡,商店也可以查用顾客一起购买的物品,找出商品之间的关系。
* 例如: 尿布和啤酒的故事
* 关联关系(associati analysis) 或 关联规则学习(association rule learning)
* 从大规模数据集中寻找物品间的隐含关系呗称作关联关系。
* 关联分析:
* 优点:易编码实现
* 缺点:在大数据集上可能较慢
* 适用数据类型:数值型 或者 标称型数据。
* 关联分析有2种形式:
* 1.频繁项集(frequent item sets): 经常出现在一块的物品集合
* 2.关联规则(association rules): 暗示两种物品之间可能存在很强的关系
* 总结:首先需要找到频繁项集,才能找到关联规则。
* 如下图:
* ![交易清单](./11.交易清单.png)
* 支持度(support)
* 数据集中包含该项集的记录所占的比例
* 例如上图中:{豆奶}的支持度=4/5, {豆奶,尿布}的支持度=3/5
* 置信度(confidence)
* 置信度({A}->{B}) = 支持度{A,B}/支持度{A}
* 例如上图中:{尿布,葡萄酒}的支持度=3/5, {尿布}的支持度=4/5, 所以 尿布->葡萄酒的可信度=3/4
* Apriori原理
* 如果某个项集是频繁的,那么它的所有子集也是频繁的,反之,一个项集是非频繁的,那么它的所有超集也是非频繁的。
* 例如: 我们假设知道{2, 3}是非频繁项,那么{0, 2, 3}, {1, 2, 3}, {0, 1, 2, 3}都是非频繁项。
* 如下图:
* ![非频繁项集](./11.非频繁项集.png)
* 分级法: 频繁项集->关联规则
* 1.首先从一个频繁项集开始,接着创建一个规则列表,其中规则右部分只包含一个元素,然后对这个规则进行测试。
* 2.接下来合并所有剩余规则来创建一个新的规则列表,其中规则右部包含两个元素。
* 如下图:
* ![所有可能的项集组合](./11.所有可能的项集组合.png)
* 最后: 每次增加频繁项集的大小,Apriori算法都会重新扫描整个数据集,是否有优化空间呢? 下一章:FP-growth算法等着你的到来

Binary file not shown.

After

Width:  |  Height:  |  Size: 126 KiB

BIN
docs/11.非频繁项集.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 405 KiB

View File

@@ -5,8 +5,9 @@
Created on Oct 12, 2010
Update on 2017-02-27
Decision Tree Source Code for Machine Learning in Action Ch. 3
@author: Peter Harrington/jiangzhonglian
@author: Peter Harrington/片刻
'''
print(__doc__)
import operator
from math import log
import decisionTreePlot as dtPlot

View File

@@ -5,8 +5,9 @@
Created on Feb 4, 2011
Update on 2017-03-02
Tree-Based Regression Methods Source Code for Machine Learning in Action Ch. 9
@author: Peter Harrington/jiangzhonglian
@author: Peter Harrington/片刻
'''
print(__doc__)
from numpy import *

View File

@@ -0,0 +1,324 @@
#!/usr/bin/python
# coding: utf8
'''
Created on Mar 24, 2011
Update on 2017-03-16
Ch 11 code
@author: Peter/片刻
'''
print(__doc__)
from numpy import *
def loadDataSet():
return [[1, 3, 4], [2, 3, 5], [1, 2, 3, 5], [2, 5]]
def createC1(dataSet):
C1 = []
for transaction in dataSet:
for item in transaction:
if not [item] in C1:
# 遍历所有的元素,然后append到C1中
C1.append([item])
# 对数组进行 从小到大 的排序
C1.sort()
# frozenset表示冻结的set集合,元素无可改变;可以把它当字典的key来使用
return map(frozenset, C1)
def scanD(D, Ck, minSupport):
"""scanD
Args:
D 原始数据集, D用来判断,CK中的元素,是否存在于原数据D中
Ck 合并后的数据集
Returns:
retList 支持度大于阈值的集合
supportData 全量key的字典集合
"""
# ssCnt 临时存放Ck的元素集合,查看Ck每个元素 并 计算元素出现的次数 生成相应的字典
ssCnt = {}
for tid in D:
for can in Ck:
# s.issubset(t) 测试是否 s 中的每一个元素都在 t 中
if can.issubset(tid):
if not ssCnt.has_key(can):
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的首位插入元素,只存储支持度满足频繁项集的值
retList.insert(0, key)
# 存储所有的key和对应的support值
supportData[key] = support
return retList, supportData
# creates Ck
def aprioriGen(Lk, k):
"""aprioriGen(循环数据集,然后进行两两合并)
Args:
Lk 频繁项集
k 元素的前k-2相同,就进行合并
Returns:
retList 元素两两合并的数据集
"""
retList = []
lenLk = len(Lk)
# 循环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]
# print '-----', Lk, Lk[i], L1
L1.sort()
L2.sort()
# 第一次L1,L2为空,元素直接进行合并,返回元素两两合并的数据集
# if first k-2 elements are equal
if L1 == L2:
# set union
# print 'union=', Lk[i] | Lk[j], Lk[i], Lk[j]
retList.append(Lk[i] | Lk[j])
return retList
def apriori(dataSet, minSupport=0.5):
"""apriori
Args:
dataSet 原始数据集
minSupport 支持度的阈值
Returns:
L 频繁项集的全集
supportData 所有元素的支持度全集
"""
# 冻结每一行数据
C1 = createC1(dataSet)
D = map(set, dataSet)
# 计算支持support, L1表示满足support的key, supportData表示全集的集合
L1, supportData = scanD(D, C1, minSupport)
# print "L1=", L1, "\n", "outcome: ", supportData
L = [L1]
k = 2
while (len(L[k-2]) > 0):
# 合并k-2相同的数据集
Ck = aprioriGen(L[k-2], k)
# print '-----------', D, Ck
# 计算合并后的数据集的支持度
# Lk满足支持度的key的list, supK表示key全集
# print 'Ck', Ck
Lk, supK = scanD(D, Ck, minSupport)
# 如果字典没有,就追加元素,如果有,就更新元素
supportData.update(supK)
if len(Lk) == 0:
break
# Lk表示满足频繁子项的集合,L元素在增加
L.append(Lk)
k += 1
# print 'k=', k, len(L[k-2])
return L, supportData
def calcConf(freqSet, H, supportData, brl, minConf=0.7):
"""calcConf
Args:
freqSet 每一组的各个元素
H 将元素变成set集合
supportData 所有元素的支持度全集
brl bigRuleList的空数组
minConf 置信度的阈值
Returns:
prunedH 记录 可信度大于阈值的集合
"""
# 记录 可信度大于阈值的集合
prunedH = []
for conseq in H:
# 计算自信度的值,例如元素 H=set(1, 2), 分别求:supportData[1] 和 supportData[2]
# print 'confidence=', freqSet, conseq, freqSet-conseq
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):
"""rulesFromConseq
Args:
freqSet 每一组的各个元素
H 将元素变成set集合
supportData 所有元素的支持度全集
brl bigRuleList的空数组
minConf 置信度的阈值
Returns:
prunedH 记录 可信度大于阈值的集合
"""
# 去除list列表中第一个出现的冻结的set集合
m = len(H[0])
# 判断,freqSet的长度是否>组合的长度+1
if (len(freqSet) > (m + 1)):
# 合并相邻的集合,组合为2/3/..n的集合
Hmp1 = aprioriGen(H, m+1)
Hmp1 = calcConf(freqSet, Hmp1, supportData, brl, minConf)
# 如果有2个结果都可以,直接返回结果就行,下面这个判断是多余,我个人觉得
# print 'Hmp1=', Hmp1
if (len(Hmp1) > 1):
# print '-------'
# print len(freqSet), len(Hmp1[0]) + 1
rulesFromConseq(freqSet, Hmp1, supportData, brl, minConf)
def generateRules(L, supportData, minConf=0.7):
"""generateRules
Args:
L 频繁项集的全集
supportData 所有元素的支持度全集
minConf 可信度的阈值
Returns:
bigRuleList 关于 (A->B+置信度) 3个字段的组合
"""
bigRuleList = []
# 循环L频繁项集,所有的统一大小组合(2/../n个的组合,从第2组开始)
for i in range(1, len(L)):
# 获取频繁项集中每个组合的所有元素
for freqSet in L[i]:
# 组合总的元素并遍历子元素,并转化为冻结的set集合,再存放到list列表中
H1 = [frozenset([item]) for item in freqSet]
# 2个的组合,走else, 2个以上的组合,走if
if (i > 1):
rulesFromConseq(freqSet, H1, supportData, bigRuleList, minConf)
else:
calcConf(freqSet, H1, supportData, bigRuleList, minConf)
return bigRuleList
def getActionIds():
from time import sleep
from votesmart import votesmart
# votesmart.apikey = 'get your api key first'
votesmart.apikey = 'a7fa40adec6f4a77178799fae4441030'
actionIdList = []
billTitleList = []
fr = open('testData/Apriori_recent20bills.txt')
for line in fr.readlines():
billNum = int(line.split('\t')[0])
try:
billDetail = votesmart.votes.getBill(billNum) # api call
for action in billDetail.actions:
if action.level == 'House' and (action.stage == 'Passage' or action.stage == 'Amendment Vote'):
actionId = int(action.actionId)
print 'bill: %d has actionId: %d' % (billNum, actionId)
actionIdList.append(actionId)
billTitleList.append(line.strip().split('\t')[1])
except:
print "problem getting bill %d" % billNum
sleep(1) # delay to be polite
return actionIdList, billTitleList
def getTransList(actionIdList, billTitleList): #this will return a list of lists containing ints
itemMeaning = ['Republican', 'Democratic']#list of what each item stands for
for billTitle in billTitleList:#fill up itemMeaning list
itemMeaning.append('%s -- Nay' % billTitle)
itemMeaning.append('%s -- Yea' % billTitle)
transDict = {}#list of items in each transaction (politician)
voteCount = 2
for actionId in actionIdList:
sleep(3)
print 'getting votes for actionId: %d' % actionId
try:
voteList = votesmart.votes.getBillActionVotes(actionId)
for vote in voteList:
if not transDict.has_key(vote.candidateName):
transDict[vote.candidateName] = []
if vote.officeParties == 'Democratic':
transDict[vote.candidateName].append(1)
elif vote.officeParties == 'Republican':
transDict[vote.candidateName].append(0)
if vote.action == 'Nay':
transDict[vote.candidateName].append(voteCount)
elif vote.action == 'Yea':
transDict[vote.candidateName].append(voteCount + 1)
except:
print "problem getting actionId: %d" % actionId
voteCount += 2
return transDict, itemMeaning
# 暂时没用上
# def pntRules(ruleList, itemMeaning):
# for ruleTup in ruleList:
# for item in ruleTup[0]:
# print itemMeaning[item]
# print " -------->"
# for item in ruleTup[1]:
# print itemMeaning[item]
# print "confidence: %f" % ruleTup[2]
# print #print a blank line
def main():
# 以前的测试
# project_dir = os.path.dirname(os.path.dirname(os.getcwd()))
# 收集并准备数据
# dataMat, labelMat = loadDataSet("%s/resources/Apriori_testdata.txt" % project_dir)
# 现在的的测试
# # 1. 加载数据
# dataSet = loadDataSet()
# print(dataSet)
# # 调用 apriori 做购物篮分析
# # 支持度满足阈值的key集合L,和所有key的全集suppoerData
# L, supportData = apriori(dataSet, minSupport=0.5)
# # print L, supportData
# print '\ngenerateRules\n'
# rules = generateRules(L, supportData, minConf=0.05)
# print rules
# 项目实战
# 构建美国国会投票记录的事务数据集
# actionIdList, billTitleList = getActionIds()
# # 测试前2个
# # transDict, itemMeaning = getTransList(actionIdList[: 2], billTitleList[: 2])
# # transDict 表示 action_id的集合,transDict[key]这个就是action_id对应的选项,例如 [1, 2, 3]
# transDict, itemMeaning = getTransList(actionIdList, billTitleList)
# # 得到全集的数据
# dataSet = [transDict[key] for key in transDict.keys()]
# L, supportData = apriori(dataSet, minSupport=0.3)
# rules = generateRules(L, supportData, minConf=0.95)
# print rules
# 项目实战
# 发现毒蘑菇的相似特性
# 得到全集的数据
dataSet = [line.split() for line in open("testData/Apriori_mushroom.dat").readlines()]
L, supportData = apriori(dataSet, minSupport=0.3)
# 2表示毒蘑菇,1表示可食用的蘑菇
# 找出关于2的频繁子项出来,就知道如果是毒蘑菇,那么出现频繁的也可能是毒蘑菇
for item in L[1]:
if item.intersection('2'):
print item
for item in L[2]:
if item.intersection('2'):
print item
if __name__ == "__main__":
main()

View File

@@ -1,206 +0,0 @@
#!/usr/bin/python
# coding: utf8
'''
Created on Mar 24, 2011
Ch 11 code
@author: Peter
'''
from numpy import *
def loadDataSet():
return [[1, 3, 4], [2, 3, 5], [1, 2, 3, 5], [2, 5]]
def createC1(dataSet):
C1 = []
for transaction in dataSet:
for item in transaction:
if not [item] in C1:
C1.append([item])
C1.sort()
return map(frozenset, C1) # use frozen set so we
# can use it as a key in a dict
def scanD(D, Ck, minSupport):
ssCnt = {}
for tid in D:
for can in Ck:
# s.issubset(t) 测试是否 s 中的每一个元素都在 t 中
if can.issubset(tid):
if not ssCnt.has_key(can): 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): #creates Ck
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: #if first k-2 elements are equal
retList.append(Lk[i] | Lk[j]) #set union
return retList
def apriori(dataSet, minSupport = 0.5):
# 冻结每一行数据
C1 = createC1(dataSet)
D = map(set, dataSet)
# 计算支持support
L1, supportData = scanD(D, C1, minSupport)
print("outcome: ", supportData)
L = [L1]
k = 2
while (len(L[k-2]) > 0):
Ck = aprioriGen(L[k-2], k)
Lk, supK = scanD(D, Ck, minSupport)#scan DB to get Lk
supportData.update(supK)
L.append(Lk)
k += 1
return L, supportData
def main():
# project_dir = os.path.dirname(os.path.dirname(os.getcwd()))
# 1.收集并准备数据
# dataMat, labelMat = loadDataSet("%s/resources/Apriori_testdata.txt" % project_dir)
# 1. 加载数据
dataSet = loadDataSet()
print(dataSet)
# 调用 apriori 做购物篮分析
apriori(dataSet, minSupport = 0.7)
if __name__=="__main__":
main()
def generateRules(L, supportData, minConf=0.7): #supportData is a dict coming from scanD
bigRuleList = []
for i in range(1, len(L)):#only get the sets with two or more items
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
def calcConf(freqSet, H, supportData, brl, minConf=0.7):
prunedH = [] #create new list to return
for conseq in H:
conf = supportData[freqSet]/supportData[freqSet-conseq] #calc confidence
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)): #try further merging
Hmp1 = aprioriGen(H, m+1)#create Hm+1 new candidates
Hmp1 = calcConf(freqSet, Hmp1, supportData, brl, minConf)
if (len(Hmp1) > 1): #need at least two sets to merge
rulesFromConseq(freqSet, Hmp1, supportData, brl, minConf)
def pntRules(ruleList, itemMeaning):
for ruleTup in ruleList:
for item in ruleTup[0]:
print itemMeaning[item]
print " -------->"
for item in ruleTup[1]:
print itemMeaning[item]
print "confidence: %f" % ruleTup[2]
print #print a blank line
# from time import sleep
# from votesmart import votesmart
# votesmart.apikey = 'a7fa40adec6f4a77178799fae4441030'
# #votesmart.apikey = 'get your api key first'
# def getActionIds():
# actionIdList = []; billTitleList = []
# fr = open('recent20bills.txt')
# for line in fr.readlines():
# billNum = int(line.split('\t')[0])
# try:
# billDetail = votesmart.votes.getBill(billNum) #api call
# for action in billDetail.actions:
# if action.level == 'House' and \
# (action.stage == 'Passage' or action.stage == 'Amendment Vote'):
# actionId = int(action.actionId)
# print 'bill: %d has actionId: %d' % (billNum, actionId)
# actionIdList.append(actionId)
# billTitleList.append(line.strip().split('\t')[1])
# except:
# print "problem getting bill %d" % billNum
# sleep(1) #delay to be polite
# return actionIdList, billTitleList
#
# def getTransList(actionIdList, billTitleList): #this will return a list of lists containing ints
# itemMeaning = ['Republican', 'Democratic']#list of what each item stands for
# for billTitle in billTitleList:#fill up itemMeaning list
# itemMeaning.append('%s -- Nay' % billTitle)
# itemMeaning.append('%s -- Yea' % billTitle)
# transDict = {}#list of items in each transaction (politician)
# voteCount = 2
# for actionId in actionIdList:
# sleep(3)
# print 'getting votes for actionId: %d' % actionId
# try:
# voteList = votesmart.votes.getBillActionVotes(actionId)
# for vote in voteList:
# if not transDict.has_key(vote.candidateName):
# transDict[vote.candidateName] = []
# if vote.officeParties == 'Democratic':
# transDict[vote.candidateName].append(1)
# elif vote.officeParties == 'Republican':
# transDict[vote.candidateName].append(0)
# if vote.action == 'Nay':
# transDict[vote.candidateName].append(voteCount)
# elif vote.action == 'Yea':
# transDict[vote.candidateName].append(voteCount + 1)
# except:
# print "problem getting actionId: %d" % actionId
# voteCount += 2
# return transDict, itemMeaning

8124
testData/Apriori_mushroom.dat Executable file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,20 @@
12939 Prohibiting Federal Funding of National Public Radio
12940 Removing Troops from Afghanistan
12830 Prioritizing Payment of Public Debt
12857 Calling for a Balanced Budget Constitutional Amendment
12988 Terminating the Home Affordable Modification Program
12040 Repealing Business Transaction Reporting Requirements
12465 Repealing the Health Care Bill
11451 Science and Technology Funding
11364 Credit Default Swap Regulations
11820 "Whistleblower Protection" for Offshore Oil Workers
12452 Treaty with Russia to Reduce and Limit Offensive Arms
11318 Derivatives Regulation Modifications
11414 Repealing "Don't Ask, Don't Tell" After Military Review and Certification
11719 Unemployment Benefits Extension
11205 Prohibiting 2010- 2011 Congressional Cost-of-Living Pay Increase
12747 Prohibiting Use of Federal Funds For Planned Parenthood
12792 Reducing Federal Funding of the US Institute of Peace
12827 Prohibiting the Use of Federal Funds for NASCAR Sponsorships
12445 Mine Safety Act
12049 2010-2011 Defense Authorizations