def test_recommendations_ranges(self):
		ranking = recommendations.get_recommendations(data.critics, pick_a_name())
		for score in ranking:
			(score[0]).should.be.within(0, 5)
			(score[1]).should.be.within(TITLES)
		l = len(ranking)
		(l).should.be.within(0, 3)
Exemple #2
0
def index_recommendation():
    # build the ingredient recommendations page
    ingredient_input = request.args.get('ingredient_input')
    seed_recipe, unknown_ingredients = get_ingredients(ingredient_input)
    # flavor_type = request.args.get('inlineRadioOptions')
    flavor_type = 'any'
    ningredients = int(request.args.get('ingredient_number'))
    ingredients = get_recommendations(seed_recipe, flavor_type, ningredients)
    unknown_list = []
    if len(unknown_ingredients):
        # html_alert += '<div class="alert alert-warning" role="alert">'
        # html_alert += '<strong>Warning:</strong> Could not find the ingredients '
        for i, ingredient in enumerate(unknown_ingredients):
            string = ingredient
            if i == len(unknown_ingredients) - 1:
                string += '. '
            else:
                string += ', '
            unknown_list.append(unicode(string))
    print unknown_list
    if len(unknown_list) > 0:
        warning_message = True
    else:
        warning_message = False
    return render_template('recommendation.html', ingredients=ingredients, seed_recipe=seed_recipe,
                           unknown_ingredients=unknown_list, warning_message=warning_message)
 def test_get_recommendations(self):
     """Tests that get_recommendations finds the correct weighted results."""
     expected_results = [
         (3.3477895267131013, 'The Night Listener'),
         (2.8325499182641614, 'Lady in the Water'),
         (2.5309807037655645, 'Just My Luck')]
     results = recommendations.get_recommendations(recommendations.critics, 'Toby')
     self.assertEqual(results, expected_results)
Exemple #4
0
 def test_recommendations_ranges(self):
     ranking = recommendations.get_recommendations(data.critics,
                                                   pick_a_name())
     for score in ranking:
         (score[0]).should.be.within(0, 5)
         (score[1]).should.be.within(TITLES)
     l = len(ranking)
     (l).should.be.within(0, 3)
Exemple #5
0
def recommend():
    """
    total = E(score*similarity)
    simSums = E(similarity)
    score = total/simSums

    """
    display_top_matchers(critics, 'Toby')
    pprint(get_recommendations(critics, 'Toby'))
def run_examples():
	import random
	user = USER_DICT.keys()[random.randint(0, len(USER_DICT) - 1)]
	print user
	top = recommendations.top_matches(USER_DICT, user)
	print top
	recs = recommendations.get_recommendations(USER_DICT, user)[:10]
	print recs
	url = recs[0][1]
	more_top = recommendations.top_matches(recommendations.transform_prefs(USER_DICT), url)
	print more_top
Exemple #7
0
def run_examples():
    import random
    user = USER_DICT.keys()[random.randint(0, len(USER_DICT) - 1)]
    print user
    top = recommendations.top_matches(USER_DICT, user)
    print top
    recs = recommendations.get_recommendations(USER_DICT, user)[:10]
    print recs
    url = recs[0][1]
    more_top = recommendations.top_matches(
        recommendations.transform_prefs(USER_DICT), url)
    print more_top
Exemple #8
0
def recommender():
    """docstring"""
    user_movies = [
        request.args['movie1'], request.args['movie2'], request.args['movie3']
    ]
    user_rating = [
        request.args['rating1'], request.args['rating2'],
        request.args['rating3']
    ]

    movies = get_recommendations(user_movies, user_rating)
    title = "The next movie you want to watch is: "
    return render_template('recommendations.html',
                           movies_html=movies,
                           title=title)
    user_path = "cache/delicious_users"
    if os.path.exists(user_path ):
        users = load(open(user_path,"r"))
    else:    
        print "fetching usernames"
        users = get_similar_users(u"python",count = 5)
        users.append("xiaohan2012")#add myself,hehe!
        dump(users,open(user_path,"w"))

    print "user count: %d" %len(users)
    
    prefs_path = "cache/delicious_prefs"
    if os.path.exists(prefs_path ):
        prefs = load(open(prefs_path ,"r"))
        print len(prefs)
    else:
        print "fetching user post info"
        prefs = get_prefs(users)
        dump(prefs,open(prefs_path ,"w"))
    ratio = [sum(prefs[user].values())/len(prefs[user].values()) for user in prefs]
    ratio.sort(reverse = True)
    
    from recommendations import top_matches,get_recommendations
    import random
    #user = random.choice((prefs.keys()))
    print user
    user = "******"
    print top_matches(user,prefs)
    print get_recommendations(user,prefs)
    print "It is empty, I think we might have encountered data sparsity problem, haha"
    return userDict


def fillItems(userDict):
    allItems = {}
    for user in userDict:
        for _ in range(3):
            try:
                posts = get_userposts(user)
                break
            except:
                print 'Failed user ' + user + ', retrying...'
                time.sleep(4)
        for post in posts:
            url = post['url']
            userDict[user][url] = 1.0
            allItems[url] = 1
    for ratings in userDict.values():
        for item in allItems:
            if item not in ratings:
                ratings[item] = 0.0


if __name__ == '__main__':
    delusers = initializeUserDict('programming')
    fillItems(delusers)
    user = delusers.keys()[random.randint(0, len(delusers) - 1)]
    print user
    print top_matches(delusers, user)[0:5]
    print get_recommendations(delusers, user)[0:5]
Exemple #11
0
import recommendations

critics = recommendations.critics

# print(critics['Lisa Rose'])
#
# print("Similarity using Euclidean Distance: \n")
# # Using Euclidean Distance
# for critic in critics:
#     print("Similarity with " + critic + " : " + str(recommendations.sim_distance("Lisa Rose", critic, critics)))
#
# print("Similarity using Pearson Correlation: \n")
# # Using Correlation
# for critic in critics:
#     print("Similarity with " + critic + " : " + str(recommendations.sim_pearson("Lisa Rose", critic, critics)))

print("Top 5 Matches for Lisa")
print(recommendations.top_matches("Lisa Rose", critics))

print("Recommendations for Toby")
print(recommendations.get_recommendations("Toby", critics))

movies = recommendations.flip_params(critics)

print("If you like superman returns then")
print(recommendations.top_matches("Superman Returns", movies))
Exemple #12
0
from recommendations import sim_distance, sim_pearson, top_matchs, get_recommendations, get_profile
import csv_test, json, ast
from pymongo import MongoClient

client = MongoClient()
db = client.studentShareTest

csv_test.saveStudents()

studJson = csv_test.getStudents()
modelsJson = csv_test.getModels()

prefs = {stud["registry"] : stud["grades"] for stud in studJson}

db.workData.delete_many({})
for stud in studJson:
	if stud == "_id":
		continue

	workData = {"name" : stud["name"]}
	workData["registry"] = stud["registry"]
	workData["warningSubjects"] = get_recommendations(prefs, stud["registry"], top_match = True)
	workData["recommendedSubjects"] = get_recommendations(prefs, stud["registry"], reverse = True, top_match = True)
	workData["topMatchs"] = top_matchs(prefs, stud["registry"])
	workData["profile"] = get_profile(stud["grades"])
		
	db.workData.insert_one(workData)
Exemple #13
0
def get_precomputed_recommendedations(prefs, similar, user):
    similar_prefs = {}
    for other in similar:
        similar_prefs[other] = prefs[other]
    similar_prefs[user] = prefs[user]
    return recommendations.get_recommendations(similar_prefs, user)
        users = load(open(user_path, "r"))
    else:
        print "fetching usernames"
        users = get_similar_users(u"python", count=5)
        users.append("xiaohan2012")  #add myself,hehe!
        dump(users, open(user_path, "w"))

    print "user count: %d" % len(users)

    prefs_path = "cache/delicious_prefs"
    if os.path.exists(prefs_path):
        prefs = load(open(prefs_path, "r"))
        print len(prefs)
    else:
        print "fetching user post info"
        prefs = get_prefs(users)
        dump(prefs, open(prefs_path, "w"))
    ratio = [
        sum(prefs[user].values()) / len(prefs[user].values()) for user in prefs
    ]
    ratio.sort(reverse=True)

    from recommendations import top_matches, get_recommendations
    import random
    #user = random.choice((prefs.keys()))
    print user
    user = "******"
    print top_matches(user, prefs)
    print get_recommendations(user, prefs)
    print "It is empty, I think we might have encountered data sparsity problem, haha"
Exemple #15
0
# Library imports
import recommendations, deliciousrec

# Initialize delicious users
delusers=deliciousrec.initialize_user_dict('programming')
# Add myself to the dataset
delusers['rogerfernandezg']={}
# Fills delicious users with data from delicious
deliciousrec.fill_items(delusers)
# Show recommendations for specific user
user=delusers.keys()[1]
print recommendations.top_matches(delusers,user)[0:10]
url=recommendations.get_recommendations(delusers,user)[0][1]
print recommendations.top_matches(recommendations.transform_prefs(delusers),url)
#!/usr/bin/env python

import recommendations

pearson_result = recommendations.get_recommendations(
  recommendations.critics, 
  'Toby'
)
print "sim_pearson  :", pearson_result

distance_result = recommendations.get_recommendations(
  recommendations.critics, 
  'Toby',
  sim_func = recommendations.sim_distance
)
print "sim_distance :", distance_result

def get_precomputed_recommendedations(prefs, similar, user):
	similar_prefs = {}
	for other in similar:
		similar_prefs[other] = prefs[other]
	similar_prefs[user] = prefs[user]
	return recommendations.get_recommendations(similar_prefs, user)
Exemple #18
0
# Lib imports
import recommendations, time

# Function's execution
t1 = time.time()
prefs=recommendations.load_movie_lens()
t2 = time.time()
print "Recomendations: {}".format(recommendations.get_recommendations(prefs,'87')[0:30])
t3 = time.time()
itemsim=recommendations.calculate_similar_items(prefs,50)
t4 = time.time()
print "Recommended items: {}".format(recommendations.get_recommended_items(prefs,itemsim,'87')[0:30])
t5 = time.time()
print "\nExecution times"
print "-----------------"
print "Load dataset: {} seconds".format(t2-t1)
print "User based filtering: {} seconds".format(t3-t2)
print "Calculate similar item: {} seconds".format(t4-t3)
print "Item based filtering: {} seconds".format(t5-t4)