Advertisement
Guest User

sadness

a guest
Dec 7th, 2016
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. import operator
  2. import numpy
  3.  
  4. def average(itemlist, dictratings):
  5. '''Returns a list consisting of the average ratings for each
  6. item'''
  7.  
  8. lst = []
  9. for num in range(len(itemlist)):
  10. nlst = []
  11. for v in dictratings.values():
  12. nlst.append(v[num])
  13. leng = len([num for num in nlst if num != 0])
  14. avg = sum(nlst) / float(leng)
  15. lst.append(avg)
  16. ans = list(zip(itemlist, lst))
  17. averageList = sorted(ans, key = operator.itemgetter(1), reverse=True)
  18. return averageList
  19.  
  20.  
  21. def similarities(name, dictratings):
  22. '''Returns a list of tuples, sorted based on how similar
  23. others are to the given name
  24. '''
  25. print dictratings
  26. orig = dictratings[name]
  27.  
  28. lst = []
  29. dictratings.pop(name)
  30. for a,b in dictratings.iteritems():
  31. dp = numpy.dot(orig, b)
  32. tp = (a, float(dp))
  33. lst.append(tp)
  34. similarList = sorted(lst, key = operator.itemgetter(1), reverse=True)
  35. # return similarList
  36.  
  37.  
  38. def recommended(simlist, itemlist, dictratings, n):
  39. '''Returns the recommended list, which is weighted based on
  40. how similar the tastes of person is to others
  41. '''
  42.  
  43. nsimlist = simlist[:n]
  44.  
  45. lst = []
  46. for elem in nsimlist:
  47. vec = dictratings[elem[0]]
  48. c = elem[1]
  49. slst = [c*b for b in dictratings[elem[0]]]
  50. lst.append(slst)
  51.  
  52. # print elem[0]
  53. # print vec
  54. # print c
  55. #
  56.  
  57.  
  58. leng = len(lst[0])
  59. finlst = []
  60. zlst = []
  61. for num in range(leng):
  62. sum = 0
  63. zcount = 0
  64. for sublst in lst:
  65. sum += sublst[num]
  66. if sublst[num] != 0:
  67. zcount += 1
  68. finlst.append(sum)
  69. zlst.append(zcount)
  70.  
  71. ans = [a/b for a,b in zip(finlst, zlst)]
  72. finans = [(a,b) for a,b in zip(itemlist, ans)]
  73. recommendList = sorted(finans, key=operator.itemgetter(1), reverse=True)
  74. return recommendList
  75.  
  76.  
  77. itemlist = ['IlForno', 'TheCommons', 'DivinityCafe', 'PandaExpress', 'TheSkillet', 'Tandoor', 'McDonalds']
  78. 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]}
  79. simlist = similarities("Xiawei", dictratings)
  80. n = 3
  81.  
  82. print similarities("SoonLee", dictratings)
  83. # print recommended(simlist, itemlist, dictratings, n)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement