-
Notifications
You must be signed in to change notification settings - Fork 0
/
PCY.py
117 lines (98 loc) · 3.52 KB
/
PCY.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import sys
import itertools
files=sys.argv
def hashing(x):
return x%int(files[3])
def apriori():
basket_items=[]
set_items=set()
lines=[l.rstrip() for l in open(files[1],'r')]
for line in lines:
basket_items.append(line.split(','))
for basket in basket_items:
for item in basket:
set_items.add(item)
unique_items=sorted(set_items)
indexed={}
for i,item in enumerate(unique_items):
indexed[item]=i+1
dict_item={}
for item in unique_items:
dict_item[item]=0
for basket in basket_items:
for item in basket:
dict_item[item]+=1
freq_item=[[]]
for item in dict_item:
if dict_item[item]>=int(files[2]):
freq_item[0].append(item)
print("Frequent itemsets of size 1")
for eachitem in freq_item[0]:
print(eachitem)
cand_items=[]
k=0
'''........................the main part starts here .......................'''
while('true'):
freq_item.append([])
cand_items.append([])
table=[0 for x in range(int(files[3]))]
for basket in basket_items:
for item in list(itertools.combinations(basket,k+2)):
item=sorted(item)
value=''
for i in range(len(item)):
value+=str(indexed[item[i]])
value=int(value)
table[hashing(value)]+=1
bitmap=[0]*int(files[3])
for i,bucket_size in enumerate(table):
if bucket_size>=int(files[2]):
bitmap[i]=1
for item in list(itertools.combinations(freq_item[0],k+2)):
if (k+2)==2:
item=sorted(item)
value=''
for i in range(len(item)):
value+=str(indexed[item[i]])
value=int(value)
bucket=hashing(value)
if bitmap[bucket]==1:
cand_items[k].append(item)
else:
continue
else:
count=0
item=sorted(item)
value=''
for i in range(len(item)):
value+=str(indexed[item[i]])
value=int(value)
bucket=hashing(value)
for items in list(itertools.combinations(item,k+1)):
items=sorted(items)
if items in freq_item[k]:
count+=1
if count==(k+2) and bitmap[bucket]==1:
item=sorted(item)
cand_items[k].append(item)
count=[0]*len(cand_items[k])
for basket in basket_items:
for index,each_item in enumerate(cand_items[k]):
if [i for i in each_item for b_item in basket if i==b_item]==list(each_item):
count[index]+=1
for i in range(len(count)):
if count[i]>=int(files[2]):
freq_item[k+1].append(cand_items[k][i])
if not freq_item[k+1]:
break
else:
print("\nFrequent itemsets of size %d"%(k+2))
for eachitem in freq_item[k+1]:
out=''
eachitem=list(eachitem)
for item in eachitem:
out+=''.join(item)+','
out=out.rstrip(',')
print(out)
k+=1
apriori()