lolamontes69

Ch2 Ex4-Programming Collective Intelligence

May 20th, 2013
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.08 KB | None | 0 0
  1. import recommendations as recommendations
  2.  
  3. def _wrap_with(code):
  4.     def inner(text, bold=False):
  5.         c = code
  6.         if bold:
  7.             c = "1;%s" % c
  8.         return "\033[%sm%s\033[0m" % (c, text)
  9.     return inner
  10.     # This makes colored text
  11.  
  12. def unescape(s):
  13.     allowed = '&0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; '
  14.     for a in s:
  15.         if a not in allowed:
  16.             s.replace(a,"")
  17.     s = s.replace(chr(96), '')
  18.     s = s.replace("&lt;", "<")
  19.     s = s.replace("&gt;", ">")
  20.     # this has to be last:
  21.     s = s.replace("&amp;", "&")
  22.     return s
  23.     # This strips naughty non-regular characters
  24.  
  25. def convertId_to_title(werec, n=5):
  26.     white = _wrap_with('37')
  27.     count2 = 0
  28.     for a in range(len(werec)):
  29.         if count2 == n: continue
  30.         else:
  31.             try:
  32.                 print white(booktitles[werec[a][1]])
  33.                 count2 += 1
  34.             except:
  35.                 print "BOOK ID",werec[a][1],"NOT IN DATABASE"
  36.    
  37. def create_maindic(booktitles, filename='/BX-Dump/BX-Book-Ratings.csv'):
  38.     # {UserId: {BookId: Rating,....
  39.     critics = {}
  40.     fin = open(filename)
  41.     for line in fin:
  42.         book = line.strip().split('";"')
  43.         userId = book[0].strip('"')
  44.         if userId not in critics:
  45.             stripped = book[2].strip('"')
  46.             rated = int(stripped)
  47.             critics[userId] = {}
  48.             # Filter out bookIds not in BX-Books.csv
  49.             if book[1] in booktitles:
  50.                 critics[userId][book[1]] = rated
  51.         else:
  52.             stripped = book[2].strip('"')
  53.             rated = int(stripped)
  54.             # Filter out bookIds not in BX-Books.csv
  55.             if book[1] in booktitles:
  56.                 critics[userId][book[1]] = rated
  57.     return critics
  58.  
  59. def create_titlesdic(filename='/BX-Dump/BX-Books.csv'):
  60.     # {bookId: title, .....
  61.     booktitles = {}
  62.     fin = open(filename)
  63.     for line in fin:
  64.         book1 = unescape(line.strip())
  65.         book = book1.split('";"')
  66.         booktitles[book[0].strip('"')] = book[1].strip('"')
  67.     return booktitles
  68.  
  69. def print_RecommendedCritics(critics, userId='60255'):
  70.     cyan = _wrap_with('36')
  71.     print "\n-----Similar Critics using Top Match and sim_pearson-----\n"
  72.     top = recommendations.topMatches(critics, userId, n=5)
  73.     for toppy in top: print cyan(toppy[1]),"with a score of",cyan(toppy[0])
  74.     return top
  75.  
  76. def print_UBRecommendations(critics, userId='60255'):
  77.     werec = recommendations.getRecommendations(critics, userId)[0:30]
  78.     print "\n---------User-based Recommendations using 60255----------\n"
  79.     # Print out n recommendations
  80.     convertId_to_title(werec, 5)
  81.  
  82. def find_users_favoritebooks(critics, userId='60255'):
  83.     # {rating: [bookId, ....
  84.     scores2 = {}
  85.     for rating1 in critics[userId]:
  86.         if critics[userId][rating1] not in scores2:
  87.             scores2[critics[userId][rating1]] = [rating1]
  88.         else:
  89.             scores2[critics[userId][rating1]].append(rating1)
  90.     return scores2
  91.  
  92. def getn_similarcritics(prefs,person,n=5):
  93.     dict1 = {}
  94.     high = 0
  95.     # Compare critics to person and add to dict1
  96.     for b in prefs:
  97.         if b != person:
  98.             crit2 = str(b)
  99.             pear = recommendations.sim_pearson(prefs, person, crit2)
  100.             if pear not in dict1:
  101.                 dict1[pear] = [person, crit2]
  102.     # return top n critics
  103.     res = dict1.keys()
  104.     res.sort()
  105.     res.reverse()
  106.     listout = []
  107.     for a in range(n):
  108.         listout.append(dict1[res[a]][1])
  109.     return listout
  110.  
  111. def getRecommendations1(prefs, person, similarity=recommendations.sim_pearson):
  112.     totals = {}
  113.     simSums = {}
  114.  
  115.     others = getn_similarcritics(prefs,person)
  116.     for other in others:
  117.         sim = similarity(prefs, person, other)
  118.  
  119.         # ignore scores of zero or lower
  120.         if sim <= 0: continue
  121.         for item in prefs[other]:
  122.  
  123.             # only score movies I haven't seen yet
  124.             if item not in prefs[person] or prefs[person][item] == 0:
  125.  
  126.                 # Similarity * Score
  127.                 totals.setdefault(item,0)
  128.                 totals[item] += prefs[other][item]*sim
  129.  
  130.                 # Sum of similarities
  131.                 simSums.setdefault(item,0)
  132.                 simSums[item] += sim
  133.  
  134.     # Create the normalized list
  135.     rankings = [(total/simSums[item],item) for item, total in totals.items()]
  136.  
  137.     # Return the sorted list
  138.     rankings.sort()
  139.     rankings.reverse()
  140.     return rankings
  141.  
  142. if __name__ == "__main__":
  143.     blue = _wrap_with('34')
  144.     white = _wrap_with('37')
  145.     cyan = _wrap_with('36')
  146.     print blue("Creating Booktitles dictionary...")
  147.     booktitles = create_titlesdic()                      # CREATE THE BOOKTITLES DICTIONARY
  148.     print blue("Creating Critics dictionary...")
  149.     critics = create_maindic(booktitles)                 # CREATE THE MAIN DICTIONARY CRITICS
  150.     print blue("Finding Similar Critics...")
  151.     userId = raw_input('Enter userId eg 60255 > ')
  152.     top = print_RecommendedCritics(critics, userId)     # PRINT SOME SIMILAR CRITICS
  153.     print "\n\n",blue("Getting recommendations from these critics..."),"\n"
  154.     for toppy in top:                                    # Get some user based recommendations
  155.         a = toppy[1]                                     #    from similar critics
  156.         print "User-based recommendations from",a,"\n"
  157.         toprecs = getRecommendations1(critics, a)[0:5]   # finds critics similar to these and gets 5 recommendations
  158.         for film in toprecs:
  159.             print white(booktitles[film[1]])
  160.         print "\n--------------------------------------------------------\n"
  161.     print_UBRecommendations(critics, userId)            # PRINT SOME USER BASED RECOMMENDATIONS
  162.     scores2 = find_users_favoritebooks(critics, userId) # FIND USER '60255' FAVORITE BOOKS
  163.  
  164.     # MAKE SOME ITEM BASED RECOMMENDATIONS FROM USERS FAVORITE BOOKS
  165.     print " \n----------------Item based recommendations---------------"
  166.     # First make a list of ratings from scores2   ---- [rating, ....
  167.     topchoices = scores2.keys()
  168.     topchoices.sort()
  169.     topchoices.reverse()
  170.     count2 = 0
  171.     # Get Item based recommendations based upon the 3 favorite books of '60255'
  172.     for a22 in topchoices:
  173.         for b22 in scores2[a22]:
  174.             if count2 == 5:
  175.                 continue
  176.             else:
  177.                 try:
  178.                     # Get 5 item based recommendations for each book
  179.                     bookdic = recommendations.transformPrefs(critics)
  180.                     werec1 = recommendations.topMatches(bookdic, b22)
  181.                     print "\nRecommendations based upon users rating of >",cyan(booktitles[b22]),"\n"
  182.                     # Convert BookIds to booktitles
  183.                     convertId_to_title(werec1, 10)
  184.                     count2 += 1
  185.                 except: print "BOOK ID",b22,"NOT IN DATABASE"
  186.  
  187.  
  188. """ Finds 5 similar crtics.
  189.    Makes recomendations in different ways.
  190.    Both user based (eg User based recommendations from similar critics,
  191.    and item-based (eg Item-based recommendations based upon a users favorites.
  192. """
Advertisement
Add Comment
Please, Sign In to add comment