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. POJ 3713 Transferring Sylla (三连通图)

    [题目链接] http://poj.org/problem?id=3713 [题目大意] 给出一个图判断是不是三连通图,三连通图的意思是对于图中任意两点, 至少有三条路是可以相互连通的. [题解] 我 ...

  2. (转)Unity3d各种坑

    1.unity的资源包一旦量很大的时候卸载不干净,你可以尝试反复切场景 ,内存诡异的 增加 一直到爆,assetsbundle.unload(true);有问题 你想要卸载你必须先让你加载过的资源为n ...

  3. /usr/local/lib/libz.a: could not read symbols: Bad value(64 位 Linux)

    /usr/local/lib/libz.a: could not read symbols: Bad value(64 位 Linux) /usr/bin/ld: /usr/local/lib/lib ...

  4. Spark-submit脚本解读

    #!/usr/bin/env bash # # Licensed to the Apache Software Foundation (ASF) under one or more # contrib ...

  5. Android Rx Android实战

    上一次捣蛋 RxAndroid 是今年二月份的事情了,当时 RxAndroid 还处于一个资料甚少交流难的状态,当时还特意建了一个交流群,让搞这个的人可以加进来讨论讨论,毕竟这玩意还是挺有意思的,于是 ...

  6. 解压缩报错tar: Error is not recoverable: exiting now

    [root@Gris-11140 FMIS2600bak]# tar -zxvf /home/oradata/FMIS2600DMP.tar.gzgzip: stdin: not in gzip fo ...

  7. How to Clear setInterval() without Knowing the ID

    ProblemDeclaring a setInterval() without keeping a reference to it (which is returned from the funct ...

  8. ElasticSearch高级查询

    ElasticSearch高级查询 https://www.imooc.com/video/15759/0 ElasticSearch查询 1,子条件查询:特定字段查询所指特定值 1.1query c ...

  9. Angular 学习笔记——ng-repeat 隔行换色

    <!DOCTYPE html> <html lang="en" ng-app="myApp"> <head> <met ...

  10. Phalcon 上下文编码(Contextual Escaping)

    站点及其他B/S应用极易受到 XSS 攻击,虽然PHP提供了转义功能.在某些情况下依旧不够安全.在Phalcon中 Phalcon\Escaper 提供了上下文转义功能,这个模块是由C语言实现的, 这 ...