from apyori import apriori
from apyori import load_transactions
class Recommender():
def __init__(self, inputFile):
self.AssociationRulesDictionary = {}
self.dataFile = inputFile
self.association_rules = []
def computeRules(self):
"""
Computes all association rules.
:return:
"""
with open(self.dataFile ) as fileObj:
transactions = list(load_transactions(fileObj, delimiter=","))
transactions_filtered = []
for li in transactions:
li = list(filter(None, li))
transactions_filtered.append(li)
self.association_rules = apriori(transactions_filtered, min_support=0.01, min_confidence=0.01, min_lift=1.0,
max_length=None)
def extractRules(self):
for item in self.association_rules:
if len(item[0]) < 2:
continue
for k in item[2]:
baseItemList = list(k[0])
if not baseItemList:
continue
baseItemList.sort()
baseItemList_key = tuple(baseItemList)
if baseItemList_key not in self.AssociationRulesDictionary.keys():
self.AssociationRulesDictionary[baseItemList_key] = []
self.AssociationRulesDictionary[baseItemList_key].append((list(k[1]), k[3]))
for ruleList in self.AssociationRulesDictionary:
self.AssociationRulesDictionary[ruleList].sort(key=lambda x: x[1], reverse=True)
def recommend(self, itemList, Num=1):
"""
itemList is a list of items selected by user
Num is total recommendations required.
:param item:
:return:
"""
itemList.sort()
itemTuple = tuple(itemList)
if itemTuple not in self.AssociationRulesDictionary.keys():
return []
return self.AssociationRulesDictionary[itemTuple][:Num]
def studyRules(self):
"""
This is a template method for computation and rule extraction.
:return:
"""
self.computeRules()
self.extractRules()
def showDeals(self, itemList, Num=1):
"""
we are converting the recommendations into deals. The lift value is used to calculate discount percentage
discount percentage = 10 * lift
itemList is a list of items selected by user
Num is total deals required.
:return:
"""
recommendations = self.recommend(itemList, Num)
for item in recommendations:
print( "If you buy ", item[0], " along with ", itemList, " then you will get ", round((item[1] * 10), 2), \
"% discount on total cost!!" )
Alexa = Recommender("store_data.csv")
Alexa.studyRules()
print (Alexa.recommend(['red wine'], 1))
Alexa.showDeals(['red wine'], 2)