""" John Rachlin DS 2000: Intro to Programming with Data Filename: recommend_start.py Description: Algorithms for finding recommendations are quite rich with possibilities, even when all you have is a single rating and the name of a movie! Algorithmic Approach: FIND THE MOST SIMILAR USER For a given user find another user who is most similar and take recommendations from that user. How is similarity defined? Ultimately, anyway you like. But we'll define it as the NUMBER of movies they BOTH liked (rated 5 or higher)' """ class Recommender: """ A recommendation engine class """ def __init__(self): self.likes = {} # user -> {set of liked movies} def load_movie_likes(self, filename, min_rating=5): """ Read ratings data from """ with open(filename) as infile: infile.readline() # skip header for line in infile: #print(line) vals = line.split(',') name = vals[0] movie = vals[1] rating = float(vals[2]) # add name, movie to ratings if name not in self.likes: self.likes[name] = set() if rating >= min_rating: self.likes[name].add(movie) def recommend(self, to_user, from_user): """ Make recommendations for based on some other user - perhaps a friend? """ recs = self.likes[from_user] - self.likes[to_user] return recs def get_movie_recommendations(self, name): """ Get movie recommendations for a particular user using MSU (Most Similar User) algorithm name - The name of the user we are recommending movies for return - a set of movie recommendations """ # What movies does like? likes = self.likes[name] # Find max overlap max_overlap = 0 most_similar_user = '' for other, other_likes in self.likes.items(): overlap = len(likes & other_likes) if name != other and overlap > max_overlap: most_similar_user = other max_overlap = overlap # return recommendations - the movies that the most # similar user likes - movie that the target named user likes print(f"{most_similar_user} likes {max_overlap} movies in common with {name}") return self.recommend(name, most_similar_user) def main(): engine = Recommender() engine.load_movie_likes('movies.csv') #recs = engine.recommend("Rachlin", "Asteroid") #print("Asteroid recommends to John: ", recs) name = "Rachlin" recs = engine.get_movie_recommendations(name) print(f"Recommendations for {name}: ", recs) if __name__ == '__main__': main()