python db Django 協調フィルタリング GAE


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  1. #models.py
  2. class User(db.Model):
  3. name=db.StringProperty(required=True)
  4.  
  5. class Product(db.Model):
  6. product=db.StringProperty(required=True)
  7.  
  8. class UserRate(db.Model):
  9. ref_user=db.ReferenceProperty(User,collection_name='users')
  10. ref_product=db.ReferenceProperty(Product,collection_name='products')
  11. rating=db.IntegerProperty(required=True)
  12.  
  13. #views.py
  14. def makeMap(item1,item2):
  15. item_list =[item1,item2]
  16. products = db.GqlQuery("SELECT * FROM Product WHERE product IN :list",list = item_list)
  17. map_product={}
  18. for product in products:
  19. map_user={}
  20. # print product.product
  21. key=product.key()
  22. # print key
  23. userrates=db.GqlQuery("SELECT * FROM UserRate WHERE ref_product =:1",key)
  24. for u in userrates:
  25. # print u.ref_user.name
  26. map_user[u.ref_user.name]=u.rating
  27. # print map_user[u.ref_user.name]
  28. map_product[product.product]=map_user
  29. # print map_product
  30. # print '<br><br>'
  31. return map_product
  32.  
  33. def sim_pearson(item1,item2):
  34. si={}
  35. prefs=makeMap(item1,item2)
  36. # print "prefs="
  37. # print prefs
  38. for person in prefs[item1]:
  39. if person in prefs[item2]: si[person]=1
  40. n=len(si)
  41. # print "<br>n="
  42. # print n
  43. if n==0: return 0
  44. sum1=float(sum([prefs[item1][it] for it in si]))
  45. sum2=float(sum([prefs[item2][it] for it in si]))
  46. # print "<br>sum1="
  47. # print sum1
  48. # print "<br>sum2="
  49. # print sum2
  50. sum1Sq=float(sum([pow(prefs[item1][it],2) for it in si]))
  51. sum2Sq=float(sum([pow(prefs[item2][it],2) for it in si]))
  52. # print "<br>sum1Sq="
  53. # print sum1Sq
  54. # print "<br>sum2Sq="
  55. # print sum2Sq
  56. pSum=float(sum([prefs[item1][it]*prefs[item2][it] for it in si]))
  57. # print "<br>pSum ="
  58. # print pSum
  59. num=pSum-(sum1*sum2/n)
  60. # print "<br>num ="
  61. # print num
  62. den=sqrt((sum1Sq-pow(sum1,2)/n)*(sum2Sq-pow(sum2,2)/n))
  63. # print (sum1Sq-pow(sum1,2)/n)
  64. # print (sum2Sq-pow(sum2,2)/n)
  65. # print "<br>den="
  66. # print den
  67. if den == 0: return 0
  68. r=num/den
  69. # print "<br>r="
  70. # print r
  71. return r

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.