Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import operator
- import numpy
- def average(itemlist, dictratings):
- '''Returns a list consisting of the average ratings for each
- item'''
- lst = []
- for num in range(len(itemlist)):
- nlst = []
- for v in dictratings.values():
- nlst.append(v[num])
- leng = len([num for num in nlst if num != 0])
- avg = sum(nlst) / float(leng)
- lst.append(avg)
- ans = list(zip(itemlist, lst))
- averageList = sorted(ans, key = operator.itemgetter(1), reverse=True)
- return averageList
- def similarities(name, dictratings):
- '''Returns a list of tuples, sorted based on how similar
- others are to the given name
- '''
- print dictratings
- orig = dictratings[name]
- lst = []
- dictratings.pop(name)
- for a,b in dictratings.iteritems():
- dp = numpy.dot(orig, b)
- tp = (a, float(dp))
- lst.append(tp)
- similarList = sorted(lst, key = operator.itemgetter(1), reverse=True)
- # return similarList
- def recommended(simlist, itemlist, dictratings, n):
- '''Returns the recommended list, which is weighted based on
- how similar the tastes of person is to others
- '''
- nsimlist = simlist[:n]
- lst = []
- for elem in nsimlist:
- vec = dictratings[elem[0]]
- c = elem[1]
- slst = [c*b for b in dictratings[elem[0]]]
- lst.append(slst)
- # print elem[0]
- # print vec
- # print c
- #
- leng = len(lst[0])
- finlst = []
- zlst = []
- for num in range(leng):
- sum = 0
- zcount = 0
- for sublst in lst:
- sum += sublst[num]
- if sublst[num] != 0:
- zcount += 1
- finlst.append(sum)
- zlst.append(zcount)
- ans = [a/b for a,b in zip(finlst, zlst)]
- finans = [(a,b) for a,b in zip(itemlist, ans)]
- recommendList = sorted(finans, key=operator.itemgetter(1), reverse=True)
- return recommendList
- itemlist = ['IlForno', 'TheCommons', 'DivinityCafe', 'PandaExpress', 'TheSkillet', 'Tandoor', 'McDonalds']
- dictratings = {'JoJo': [0, 0, 0, 1, 1, 3, 1], 'SoonLee': [1, 0, 3, -3, -1, 5, 0], 'Lee': [1, 3, 5, 0, 3, 3, 0], 'Bruce': [3, 3, 5, 3, 1, 3, 1], 'Xiawei': [0, 5, 5, -5, 1, 0, -3], 'Shirley': [3, 3, 5, 0, 0, 1, -1]}
- simlist = similarities("Xiawei", dictratings)
- n = 3
- print similarities("SoonLee", dictratings)
- # print recommended(simlist, itemlist, dictratings, n)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement