Building Recommender Engine in Python
Building ourselves an engine that recommends us content
Recommendations are everywhere, they are used in social apps, video apps, ecommerce and more. The goal of recommender engine is to recommend you feed based on your interests and increase engagement.
The foundation of recommender engine:
- Extracting the nearest neighbors
- Building a K-nearest neighbors' classifier
- Computing similarity scores
- Finding similar users using collaborative filtering
We will build a movie recommendation system that will use ratings.json to find movie recommendation.
Let’s create a Python file and import the packages
import argparse
import json
import numpy as np
from compute_scores import pearson_score
from collaborative_filtering import find_similar_usersDefine a function to parse the input arguments. The input argument is the name of the user
def build_arg_parser():
parser = argparse.ArgumentParser(description='Find recommendations
for the given user')
parser.add_argument('--user', dest='user', required=True,
help='Input user')
return parserDefine a function to get the movie recommendations for a given user. If the user doesn’t exist in the dataset, the code will raise an error
# Get movie recommendations for the input user
def get_recommendations(dataset, input_user):
if input_user not in dataset:
raise TypeError('Cannot find ' + input_user + ' in the
dataset')Define the variables to track the scores
overall_scores = {}
similarity_scores = {}Compute a similarity score between the input user and all the other users in the dataset
for user in [x for x in dataset if x != input_user]:
similarity_score = pearson_score(dataset, input_user, user)If the similarity score is less than 0, you can continue with the next user in the dataset
if similarity_score <= 0:
continueExtract a list of movies that have been rated by the current user but haven’t been rated by the input user
filtered_list = [x for x in dataset[user] if x not in \
dataset[input_user] or dataset[input_user][x] == 0]For each item in the filtered list, keep a track of the weighted rating based on the similarity score. Also keep a track of the similarity scores
for item in filtered_list:
overall_scores.update({item: dataset[user][item] *
similarity_score})
similarity_scores.update({item: similarity_score})If there are no such movies, then we cannot recommend anything
if len(overall_scores) == 0:
return ['No recommendations possible']Normalize the scores based on the weighted scores
# Generate movie ranks by normalization
movie_scores = np.array([[score/similarity_scores[item], item]
for item, score in overall_scores.items()])Sort the scores and extract the movie recommendations
# Sort in decreasing order
movie_scores = movie_scores[np.argsort(movie_scores[:, 0])[::-1]]
# Extract the movie recommendations
movie_recommendations = [movie for _, movie in movie_scores]
return movie_recommendationsDefine the main function and parse the input arguments to extract the name of the input user
if __name__=='__main__':
args = build_arg_parser().parse_args()
user = args.userLoad the movie ratings data from the file ratings.json
ratings_file = 'ratings.json'
with open(ratings_file, 'r') as f:
data = json.loads(f.read())Extract the movie recommendations and print the output
print("\nMovie recommendations for " + user + ":")
movies = get_recommendations(data, user)
for i, movie in enumerate(movies):
print(str(i+1) + '. ' + movie)RUN BASH SCRIPT
$ python3 movie_recommender.py --user "Chris Duncan"
The movies in the output are the actual recommendations by the system, based on previous preferences observed for Julie Hammel. Potentially, the system could continue to get better simply by observing more and more data points.