association rules algorithm recommender systems with python

Solutions on MaxInterview for association rules algorithm recommender systems with python by the best coders in the world

showing results for - "association rules algorithm recommender systems with python"
Valentina
23 Oct 2017
1from apyori import apriori
2from apyori import load_transactions
3
4
5class Recommender():
6    def __init__(self, inputFile):
7        self.AssociationRulesDictionary = {} # holds final output
8        self.dataFile = inputFile # input datafile in csv form
9        self.association_rules = [] # holds output from Apriori algo
10
11    def computeRules(self):
12        """
13        Computes all association rules.
14        :return:
15        """
16        with open(self.dataFile ) as fileObj:
17
18            transactions = list(load_transactions(fileObj, delimiter=","))
19
20            # remove empty strings if any
21            transactions_filtered = []
22            for li in transactions:
23                li = list(filter(None, li))
24                transactions_filtered.append(li)
25
26            # Following line does all computations
27            # lift > 1 shows that there is a positive correlation within the itemset, i.e., items in the
28            # itemset, are more likely to be bought together.
29            # lift < 1 shows that there is a negative correlation within the itemset, i.e., items in the
30            # itemset, are unlikely to be bought together.
31            # hence we have set min_lift=1.0 to ignore all rules with lift < 1.0
32            self.association_rules = apriori(transactions_filtered, min_support=0.01, min_confidence=0.01, min_lift=1.0,
33                                        max_length=None)
34
35    def extractRules(self):
36
37        for item in self.association_rules:
38            # first index of the inner list
39            # Contains base item and add item
40
41            if len(item[0]) < 2:
42                continue
43
44            for k in item[2]:
45
46                baseItemList = list(k[0])
47                # if base item set is empty then go to the next record.
48                if not baseItemList:
49                    continue
50
51                # sort the baseItemList before adding it as a key to the AssociationRules dictionary
52                baseItemList.sort()
53                baseItemList_key = tuple(baseItemList)
54
55                if baseItemList_key not in self.AssociationRulesDictionary.keys():
56                    self.AssociationRulesDictionary[baseItemList_key] = []
57
58                self.AssociationRulesDictionary[baseItemList_key].append((list(k[1]), k[3]))
59
60                # if something goes wrong, then use the following print block to print values
61                #print("Base item: ", baseItemList_key)
62                #print("Target item: ", list(k[1]))
63                #print("Confidence: " + str(k[2]))
64                #print("Lift: " + str(k[3]))
65
66        # sort the rules in descending order of lift values.
67        for ruleList in self.AssociationRulesDictionary:
68            self.AssociationRulesDictionary[ruleList].sort(key=lambda x: x[1], reverse=True)
69
70
71    def recommend(self, itemList, Num=1):
72        """
73        itemList is a list of items selected by user
74        Num is total recommendations required.
75        :param item:
76        :return:
77        """
78
79        # convert itemList to itemTuple as our dictionary key is a sorted tuple
80        itemList.sort()
81        itemTuple = tuple(itemList)
82
83        if itemTuple not in self.AssociationRulesDictionary.keys():
84            return []
85
86        return self.AssociationRulesDictionary[itemTuple][:Num]
87
88    def studyRules(self):
89        """
90        This is a template method for computation and rule extraction.
91        :return:
92        """
93        self.computeRules()
94        self.extractRules()
95
96    def showDeals(self, itemList, Num=1):
97        """
98        we are converting the recommendations into deals. The lift value is used to calculate discount percentage
99        discount percentage = 10 * lift
100        itemList is a list of items selected by user
101        Num is total deals required.
102        :return:
103        """
104        recommendations = self.recommend(itemList, Num)
105
106        for item in recommendations:
107            print( "If you buy ", item[0], " along with ", itemList, " then you will get ", round((item[1] * 10), 2), \
108                   "% discount on total cost!!" )
109
110
111Alexa = Recommender("store_data.csv")
112
113Alexa.studyRules()
114
115print (Alexa.recommend(['red wine'], 1))
116
117Alexa.showDeals(['red wine'], 2)
118
119
120
121
122
similar questions