Skip to content

Commit 50e73d0

Browse files
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
1 parent 12e5cb3 commit 50e73d0

File tree

1 file changed

+23
-6
lines changed

1 file changed

+23
-6
lines changed

machine_learning/apriori_algorithm.py

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,9 @@ def load_data() -> list[list[str]]:
2525
class Apriori:
2626
"""Apriori algorithm class with support, confidence, and lift filtering."""
2727

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+
):
2931
self.transactions = [set(t) for t in transactions]
3032
self.min_support = min_support
3133
self.min_confidence = min_confidence
@@ -38,7 +40,9 @@ def __init__(self, transactions, min_support=0.25, min_confidence=0.5, min_lift=
3840

3941
def _get_support(self, itemset: frozenset) -> float:
4042
"""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+
)
4246

4347
def confidence(self, antecedent: frozenset, consequent: frozenset) -> float:
4448
"""Calculate confidence of a rule A -> B."""
@@ -60,7 +64,11 @@ def find_frequent_itemsets(self):
6064
item_counts[frozenset([item])] += 1
6165

6266
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+
}
6472
self.itemsets.append(current_itemsets)
6573

6674
k = 2
@@ -71,10 +79,17 @@ def find_frequent_itemsets(self):
7179
for j in range(i + 1, len(keys)):
7280
union = keys[i] | keys[j]
7381
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+
):
7586
candidates.add(union)
7687

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+
}
7893
if not freq_candidates:
7994
break
8095

@@ -117,4 +132,6 @@ def generate_association_rules(self):
117132
print("\nAssociation Rules:")
118133
for rule in model.rules:
119134
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

Comments
 (0)