lolamontes69

Ch4 Ex5-Collective Intelligence (wordfreq bias)

Jun 27th, 2013
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.39 KB | None | 0 0
  1. """ Chapter 4 Exercise 5: Word frequency bias.
  2.  
  3.    The "word count" metric is biased to favor longer documents, since a long document has more words and can therefore contain the target words more often. Write a new metric that calculates frequency as a percentage of the number of words in the document.
  4. """
  5.  
  6.     def wordfreqscore(self,rows,wordids):
  7.         uniqueurls=set([row[0] for row in rows])
  8.         # Get total number of words in url
  9.         wordscount=dict([(u,self.con.execute('select count(*) from wordlocation where urlid=%d' % u).fetchone()[0]) for u in uniqueurls])
  10.         wordscount2 = {}
  11.         # Get total number of query words in url
  12.         for word in wordids:
  13.             wordscount1=dict([(u,self.con.execute('select count(*) from wordlocation where urlid=%d and wordid=%d' % (u, word)).fetchone()[0]) for u in uniqueurls])
  14.             for url in wordscount1:
  15.                 if url not in wordscount2:
  16.                     wordscount2[url]=wordscount1[url]
  17.                 else:
  18.                     wordscount2[url] = wordscount2[url]+wordscount1[url]
  19.         # Calculate percentage of query words in url and put in dictionary
  20.         for url in wordscount:
  21.             wordscount[url] = (wordscount2[url]/float(wordscount[url]))*100.0
  22.        
  23.         return self.normalizescores(wordscount)
  24.  
  25. """
  26.    Usage:
  27.        weights=[(1.0,self.wordfreqscore(rows, wordids))]
  28. """
Advertisement
Add Comment
Please, Sign In to add comment