@@ -25,7 +25,9 @@ def load_data() -> list[list[str]]:
25
25
class Apriori :
26
26
"""Apriori algorithm class with support, confidence, and lift filtering."""
27
27
28
- def __init__ (self , transactions , min_support = 0.25 , min_confidence = 0.5 , min_lift = 1.0 ):
28
+ def __init__ (
29
+ self , transactions , min_support = 0.25 , min_confidence = 0.5 , min_lift = 1.0
30
+ ):
29
31
self .transactions = [set (t ) for t in transactions ]
30
32
self .min_support = min_support
31
33
self .min_confidence = min_confidence
@@ -38,7 +40,9 @@ def __init__(self, transactions, min_support=0.25, min_confidence=0.5, min_lift=
38
40
39
41
def _get_support (self , itemset : frozenset ) -> float :
40
42
"""Return support of an itemset."""
41
- return sum (1 for t in self .transactions if itemset .issubset (t )) / len (self .transactions )
43
+ return sum (1 for t in self .transactions if itemset .issubset (t )) / len (
44
+ self .transactions
45
+ )
42
46
43
47
def confidence (self , antecedent : frozenset , consequent : frozenset ) -> float :
44
48
"""Calculate confidence of a rule A -> B."""
@@ -60,7 +64,11 @@ def find_frequent_itemsets(self):
60
64
item_counts [frozenset ([item ])] += 1
61
65
62
66
total = len (self .transactions )
63
- current_itemsets = {k : v / total for k , v in item_counts .items () if v / total >= self .min_support }
67
+ current_itemsets = {
68
+ k : v / total
69
+ for k , v in item_counts .items ()
70
+ if v / total >= self .min_support
71
+ }
64
72
self .itemsets .append (current_itemsets )
65
73
66
74
k = 2
@@ -71,10 +79,17 @@ def find_frequent_itemsets(self):
71
79
for j in range (i + 1 , len (keys )):
72
80
union = keys [i ] | keys [j ]
73
81
if len (union ) == k :
74
- if all (frozenset (sub ) in current_itemsets for sub in combinations (union , k - 1 )):
82
+ if all (
83
+ frozenset (sub ) in current_itemsets
84
+ for sub in combinations (union , k - 1 )
85
+ ):
75
86
candidates .add (union )
76
87
77
- freq_candidates = {c : self ._get_support (c ) for c in candidates if self ._get_support (c ) >= self .min_support }
88
+ freq_candidates = {
89
+ c : self ._get_support (c )
90
+ for c in candidates
91
+ if self ._get_support (c ) >= self .min_support
92
+ }
78
93
if not freq_candidates :
79
94
break
80
95
@@ -117,4 +132,6 @@ def generate_association_rules(self):
117
132
print ("\n Association Rules:" )
118
133
for rule in model .rules :
119
134
antecedent , consequent , conf , lift = rule
120
- print (f"{ set (antecedent )} -> { set (consequent )} , conf={ conf :.2f} , lift={ lift :.2f} " )
135
+ print (
136
+ f"{ set (antecedent )} -> { set (consequent )} , conf={ conf :.2f} , lift={ lift :.2f} "
137
+ )
0 commit comments