Apriori算法python实现
时间: 2023-10-12 14:15:46 浏览: 73
非常感谢您的提问!关于 Apriori 算法的 Python 实现,这是一个比较常见的数据挖掘算法,可以在 GitHub 上找到一些实现代码。下面是一个例子:
```
import itertools
def generate_candidates(itemset, k):
return set([i.union(j) for i in itemset for j in itemset if len(i.union(j)) == k])
def support_prune(dataset, candidates, threshold):
frequent = dict()
for candidate in candidates:
support = sum(1 for row in dataset if candidate.issubset(row))
if support/len(dataset) >= threshold:
frequent[candidate] = support
return frequent
def apriori(dataset, threshold):
itemset = [set([item]) for row in dataset for item in row]
k = 1
frequent = dict()
while True:
candidates_k = generate_candidates(itemset, k)
frequent_k = support_prune(dataset, candidates_k, threshold)
if not frequent_k:
break
frequent.update(frequent_k)
itemset = frequent_k.keys()
k += 1
return frequent
transactions = [['Bread', 'Milk'], ['Bread', 'Diapers', 'Beer', 'Eggs'],
['Milk', 'Diapers', 'Beer', 'Cola'],
['Bread', 'Milk', 'Diapers', 'Beer'],
['Bread', 'Milk', 'Diapers', 'Cola']]
frequent_itemsets = apriori(transactions, 0.4)
for itemset, support in frequent_itemsets.items():
print(str(itemset) + ': ' + str(round(support/len(transactions), 2)))
```
希望这个简单的实现能够帮助到您!
阅读全文