votesmart下载  https://pypi.python.org/pypi/py-votesmart

test11.py

#-*- coding:utf-8
import sys
sys.path.append("apriori.py") import apriori
from numpy import * # dataSet = apriori.loadDataSet()
# print("dataSet:")
# print(dataSet)
#
# C1 = apriori.createC1(dataSet)
# print("C1:")
# print(C1)
#
# D = list(map(set, dataSet))
# print("D:")
# print(D)
#
# L1, suppData0 = apriori.scanD(D, C1, 0.5)
# print("L1:")
# print(L1)
# print("suppData0:")
# print(suppData0)
#
#
# L, suppData = apriori.apriori(dataSet)
# print("L:")
# print(L)
#
# L, suppData = apriori.apriori(dataSet, minSupport = 0.5)
# rules = apriori.generateRules(L, suppData, minConf = 0.5)
# print("L:")
# print(L)
# print("rules:")
# print(rules) mushDatSet = [line.split() for line in open('mushroom.dat').readlines()]
L, suppData = apriori.apriori(mushDatSet, minSupport = 0.3)
print("L[1]:")
print(L[1])
for item in L[1]:
if item.intersection(''):
print(item) print("over!!!")

apriori.py
'''
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 list(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:
if can.issubset(tid):
if can not 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): #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]
test0 = list(Lk[i])
test1 = list(Lk[j])
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 = list(map(set, dataSet))
L1, supportData = scanD(D, C1, minSupport)
L = [L1]
k = 2
test0 = L[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 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
												

机器学习11—Apriori学习笔记的更多相关文章

  1. 《机器学习实战》学习笔记第十四章 —— 利用SVD简化数据

    相关博客: 吴恩达机器学习笔记(八) —— 降维与主成分分析法(PCA) <机器学习实战>学习笔记第十三章 —— 利用PCA来简化数据 奇异值分解(SVD)原理与在降维中的应用 机器学习( ...

  2. 《机器学习实战》学习笔记第九章 —— 决策树之CART算法

    相关博文: <机器学习实战>学习笔记第三章 —— 决策树 主要内容: 一.CART算法简介 二.分类树 三.回归树 四.构建回归树 五.回归树的剪枝 六.模型树 七.树回归与标准回归的比较 ...

  3. (转载)林轩田机器学习基石课程学习笔记1 — The Learning Problem

    (转载)林轩田机器学习基石课程学习笔记1 - The Learning Problem When Can Machine Learn? Why Can Machine Learn? How Can M ...

  4. Coursera台大机器学习基础课程学习笔记1 -- 机器学习定义及PLA算法

    最近在跟台大的这个课程,觉得不错,想把学习笔记发出来跟大家分享下,有错误希望大家指正. 一机器学习是什么? 感觉和 Tom M. Mitchell的定义几乎一致, A computer program ...

  5. MNIST机器学习入门【学习笔记】

    平台信息:PC:ubuntu18.04.i5.anaconda2.cuda9.0.cudnn7.0.5.tensorflow1.10.GTX1060 作者:庄泽彬(欢迎转载,请注明作者) 说明:本文是 ...

  6. 《机器学习实战》学习笔记第十一章 —— Apriori算法

    主要内容: 一.关联分析 二.Apriori原理 三.使用Apriori算法生成频繁项集 四.从频繁项集中生成关联规则 一.关联分析 1.关联分析是一种在大规模数据集中寻找有趣关系的任务.这些关系可以 ...

  7. 《机器学习实战》学习笔记——第2章 KNN

    一. KNN原理: 1. 有监督的学习 根据已知事例及其类标,对新的实例按照离他最近的K的邻居中出现频率最高的类别进行分类.伪代码如下: 1)计算已知类别数据集中的点与当前点之间的距离 2)按照距离从 ...

  8. [转]Python3《机器学习实战》学习笔记(一):k-近邻算法(史诗级干货长文)

    转自http://blog.csdn.net/c406495762/article/details/75172850 版权声明:本文为博主原创文章,未经博主允许不得转载.   目录(?)[-] 一 简 ...

  9. Andrew N.G的机器学习公开课学习笔记(一):机器学习的动机与应用

    机器学习由对于人工智能的研究而来,是一个综合性和应用性学科,可以用来解决计算机视觉/生物学/机器人和日常语言等各个领域的问题,机器学习的目的是让计算机具有像人类的学习能力,这样做是因为我们发现,计算机 ...

随机推荐

  1. Google Kickstart Round E 2018 B. Milk Tea

    太蠢了,,,因为初始化大数据没过,丢了10分,纪念一下这个错误 大概思路:先求出让损失值最小的排列,由已生成的这些排列,通过更改某一个位置的值,生成下一个最优解,迭代最多生成m+1个最优解即可,遍历求 ...

  2. POJ 3041 Asteroids (二分图匹配)

    [题目链接] http://poj.org/problem?id=3041 [题目大意] 一个棋盘上放着一些棋子 每次操作可以拿走一行上所有的棋子或者一列上所有的棋子 问几次操作可以拿完所有的棋子 [ ...

  3. linux-配置字符串-grep

    grep -rn "hello,world!" * * : 表示当前目录所有文件,也可以是某个文件名 -r 是递归查找 -n 是显示行号 -R 查找所有文件包含子目录 -i 忽略大 ...

  4. Python学习笔记——条件控制

    Python中的条件控制方式基本和C语言类似,主要有如下几种语法: If条件判断 Python的条件语句的语法是if…elseif…else,如下的一个简单的猜数字的示例演示了这一过程: number ...

  5. win7 下注册dll文件失败

    1.win7 下注册dll文件失败,提示模块“xx.dll”已加载,但找不到入口点DllRegisterServer 原因:该dll文件非可注册组件,没有包含DllRegisterServer函数,可 ...

  6. hdoj 1159最长公共子序列

     /*Common Subsequence A subsequence of a given sequence is the given sequence with some elements ( ...

  7. RSA加密解密及数字签名Java实现

    http://my.oschina.net/jiangli0502/blog/171263

  8. Hive 脚本执行

    hive执行脚本 hive -e “sql语句” 会将查询的结果打印在控制台上.  hive -e “sql语句” >> xxx 会将查询的结果重定向到xxx文件中,会显示OK和抓取的数据 ...

  9. 初识Nginx及编译安装Nginx

    初识Nginx及编译安装Nginx 环境说明: 系统版本    CentOS 6.9 x86_64 软件版本    nginx-1.12.2 1.什么是Nginx? 如果你听说或使用过Apache软件 ...

  10. mvn 更改打包的名称

    在pom.xml中加入以下代码 <build> <finalName>moon</finalName> <pluginManagement> <p ...