Return to Snippet

Revision: 9610
at November 14, 2008 01:18 by tamuratetsuya


Initial Code
#models.py
class User(db.Model):
    name=db.StringProperty(required=True)

class Product(db.Model):
    product=db.StringProperty(required=True)

class UserRate(db.Model):
    ref_user=db.ReferenceProperty(User,collection_name='users')
    ref_product=db.ReferenceProperty(Product,collection_name='products')
    rating=db.IntegerProperty(required=True)

#views.py
def makeMap(item1,item2):
    item_list =[item1,item2]
    products = db.GqlQuery("SELECT * FROM Product WHERE product IN :list",list = item_list)
    map_product={}
    for product in products:
        map_user={}
#        print product.product
        key=product.key()
#        print key
        userrates=db.GqlQuery("SELECT * FROM UserRate WHERE ref_product =:1",key)
        for u in userrates:
#            print u.ref_user.name
            map_user[u.ref_user.name]=u.rating
#            print map_user[u.ref_user.name]
        map_product[product.product]=map_user
#        print map_product
#        print '<br><br>'
    return map_product

def sim_pearson(item1,item2):
    si={}
    prefs=makeMap(item1,item2)
#    print "prefs="
#    print prefs
    for person in prefs[item1]:
        if person in prefs[item2]: si[person]=1
    n=len(si)
#    print "<br>n="
#    print n  
    if n==0: return 0
    sum1=float(sum([prefs[item1][it] for it in si]))
    sum2=float(sum([prefs[item2][it] for it in si]))
#    print "<br>sum1="
#    print sum1
#    print "<br>sum2="
#    print sum2  
    sum1Sq=float(sum([pow(prefs[item1][it],2) for it in si]))
    sum2Sq=float(sum([pow(prefs[item2][it],2) for it in si]))
#    print "<br>sum1Sq="
#    print sum1Sq
#    print "<br>sum2Sq="
#    print sum2Sq
    pSum=float(sum([prefs[item1][it]*prefs[item2][it] for it in si]))
#    print "<br>pSum ="
#    print pSum
    num=pSum-(sum1*sum2/n)
#    print "<br>num  ="
#    print num
    den=sqrt((sum1Sq-pow(sum1,2)/n)*(sum2Sq-pow(sum2,2)/n))
#    print (sum1Sq-pow(sum1,2)/n)
#    print (sum2Sq-pow(sum2,2)/n)
#    print "<br>den="
#    print den
    if den == 0: return 0
    r=num/den
#    print "<br>r="
#    print r
    return r

Initial URL

                                

Initial Description

                                

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

Initial Tags
python, django

Initial Language
Python