Skip to content

Instantly share code, notes, and snippets.

@sn1p3r46
Created January 28, 2016 13:37
Show Gist options
  • Save sn1p3r46/3ec7f886ed121c73086e to your computer and use it in GitHub Desktop.
Save sn1p3r46/3ec7f886ed121c73086e to your computer and use it in GitHub Desktop.
a compact apriori pythonian version
from collections import defaultdict
from itertools import imap, combinations
def get_frequent_items_sets(transactions,min_support,steps=0):
frequent_itemsets = []
items = defaultdict(lambda: 0)
[inc(items,item,1) for transaction in transactions for item in transaction]
items = set(item for item, support in items.iteritems()
if support >= min_support)
[frequent_itemsets.append(item) for item in items]
transactions = [set(filter(lambda v: v in items, y)) for y in transactions]
count = 2
while bool(len(items)) and count != steps:
candidates = combinations([i for i in items],count)
items = defaultdict(lambda: 0)
[inc(items,candidate,1) for candidate in candidates for transaction in transactions if transaction.issuperset(candidate)]
[frequent_itemsets.append(item) for item,support in items.iteritems() if support >= min_support]
items = set(element for tupl in items.iterkeys() for element in tupl)
count+=1
return frequent_itemsets
def inc(dic,key,val):
dic[key]+=val
#[transaction.remove(element) for item,support in items.iteritems() for element in item if support < minimum_support and element in transaction]
@sn1p3r46
Copy link
Author

sn1p3r46 commented Apr 7, 2016

Apriori Python Compact Implementation

AUTHOR: Andrea Galloni (Twitter or Web)

E-Mail: andreagalloni92{at}gmail[dot]com


A compact implementation of the notorious Apriori algorithm, this implementation would like to show the compactness of Python2.7 codestyle when needed.


The whole code in this repository comes without any kind of warranty or license, use it at your own risk.

If you have some improvements or suggestions, please create a pull request or write to me at: andreagalloni92{at}gmail[dot]com

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment