lolamontes69

Ch2 Ex3-Programming Collective Intelligence

May 19th, 2013
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.07 KB | None | 0 0
  1. import recommendations as recommendations
  2.  
  3. def getn_similarcritics(prefs,person,n=5):
  4.     dict1 = {}
  5.     high = 0
  6.     # Compare critics to person and add to dict1
  7.     for b in prefs:
  8.         if b != person:
  9.             crit2 = str(b)
  10.             pear = recommendations.sim_pearson(prefs, person, crit2)
  11.             if pear not in dict1:
  12.                 dict1[pear] = [person, crit2]
  13.  
  14.     # return top n critics
  15.     res = dict1.keys()
  16.     res.sort()
  17.     res.reverse()
  18.     listout = []
  19.     for a in range(n):
  20.         listout.append(dict1[res[a]][1])
  21.  
  22.     return listout
  23.  
  24.  
  25. def getRecommendations1(prefs, person, similarity=recommendations.sim_pearson):
  26.     totals = {}
  27.     simSums = {}
  28.  
  29.     others = getn_similarcritics(prefs,person)
  30.     for other in others:
  31.         sim = similarity(prefs, person, other)
  32.  
  33.         # ignore scores of zero or lower
  34.         if sim <= 0: continue
  35.         for item in prefs[other]:
  36.  
  37.             # only score movies I haven't seen yet
  38.             if item not in prefs[person] or prefs[person][item] == 0:
  39.  
  40.                 # Similarity * Score
  41.                 totals.setdefault(item,0)
  42.                 totals[item] += prefs[other][item]*sim
  43.  
  44.                 # Sum of similarities
  45.                 simSums.setdefault(item,0)
  46.                 simSums[item] += sim
  47.  
  48.     # Create the normalized list
  49.     rankings = [(total/simSums[item],item) for item, total in totals.items()]
  50.  
  51.     # Return the sorted list
  52.     rankings.sort()
  53.     rankings.reverse()
  54.     return rankings
  55.  
  56.  
  57. if __name__ == "__main__":
  58.     prefs = recommendations.loadMovieLens()
  59.     print getRecommendations1(prefs, '87')[0:30]
  60.  
  61.  
  62. """ User-based efficiency. The user-based filtering algorithm is inefficient because it compares a user to all other users every time a recommendation is needed. Write a function to precompute user similarities, and alter the recommendation code to use only the top five other users to get recomendations
  63.  
  64. person is the person to get recommendations for
  65. prefs  is the dataset
  66. n      is the number of critics to get recommendations from
  67.  
  68. """
Advertisement
Add Comment
Please, Sign In to add comment