我正在阅读《机器学习在行动》一书中有关关联分析的内容。书中给出了以下代码
k-2可能有点令人困惑。让我们看一下 进一步。当您从{0},{1},{2}创建{0,1} {0,2},{1,2}时, 您只是合并项目。现在,如果您想使用{0,1} {0,2},该怎么办, {1,2}创建三个项目集?如果您完成每组的结合, 您会得到{0,1,2},{0,1,2},{0,1,2}。那就对了。一样的 设置三遍。现在,您必须浏览三个项目的列表 设置为仅获取唯一值。您正在尝试保持 您浏览列表的次数最少。现在,如果您比较 第一个元素{0,1} {0,2},{1,2},并且只接受那些 拥有相同的第一项,您会得到什么? {0,1,2}仅一次。 现在,您无需遍历列表即可查找唯一值。
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] # Join sets if first k-2 items are equal
L1.sort(); L2.sort()
if L1==L2:
retList.append(Lk[i] | Lk[j])
return retLis
假设我正在调用上面的函数
Lk = [frozenset({2, 3}), frozenset({3, 5}), frozenset({2, 5}), frozenset({1, 3})]
k = 3
aprioriGen(Lk,3)
我得到以下输出
[frozenset({2, 3, 5})]
我认为上述逻辑中存在错误,因为我们缺少其他组合,例如{1,2,3},{1,3,5}。是不是我的理解正确吗?
答案 0 :(得分:0)
我认为您正在关注以下链接,输出集取决于我们通过的minSupport。
http://adataanalyst.com/machine-learning/apriori-algorithm-python-3-0/
如果将minSupport值减小为0.2,则会得到所有集合。
下面是完整的代码
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 31 16:57:26 2018
@author: rponnurx
"""
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 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
dataSet = loadDataSet()
print(dataSet)
C1 = createC1(dataSet)
print(C1)
#D is a dataset in the setform.
D = list(map(set,dataSet))
print(D)
L1,suppDat0 = scanD(D,C1,0.5)
print(L1)
def aprioriGen(Lk, k): #creates Ck
retList = []
print("Lk")
print(Lk)
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 = list(map(set, dataSet))
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)#scan DB to get Lk
supportData.update(supK)
L.append(Lk)
k += 1
return L, supportData
L,suppData = apriori(dataSet,0.2)
print(L)
输出: [[frozenset({5}),frozenset({2}),frozenset({4}),frozenset({3}),frozenset({1})],[frozenset({1,2}),frozenset( {1,5}),frozenset({2,3}),frozenset({3,5}),frozenset({2,5}),frozenset({1,3}),frozenset({1,4} ),frozenset({3,4})],[frozenset({1,3,5}),frozenset({1,2,3}),frozenset({1,2,5}),frozenset({2 ,3、5}),frozenset({1,3,4})],[frozenset({1、2、3、5})],[]]
谢谢, 拉杰斯瓦里·蓬努鲁(Rajeswari Ponnuru)