-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmovie_recommender_engine.py
75 lines (54 loc) · 1.99 KB
/
movie_recommender_engine.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
"""
Content Base Recommender Engine
based on dataset we have, this engine recommend 10 similar movies to
the movie title that the user provide to the app
"""
import os
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
# helpers
def get_title_from_index(index):
return df[df.index == index]["title"].values[0]
def get_index_from_title(title):
return df[df.title == title]["index"].values[0]
# path file
file_path = os.path.join(os.getcwd(), 'projects',
'movie_recommender_engine', 'movie_dataset.csv')
# dataframe
df = pd.read_csv(file_path)
# determine the features we want
features = ["keywords", "cast", "genres", "director"]
# new column in dataframe contains combinations of features
for feature in features:
# fill the null values with empty string
df[feature] = df[feature].fillna('')
# combine the features in to one string
def combine_features(row):
try:
# return f"{row["keyword"]} {row["cast"]} {row["genres"]} {row["director"]}"
return row["keywords"] + " " + row["cast"] + " " + row["genres"] + " " + row["director"]
except:
print("Error: ", row)
# add new column to dataframe
df["combined_features"] = df.apply(combine_features, axis=1)
# create combine metrix
cv = CountVectorizer()
count_matrix = cv.fit_transform(df["combined_features"])
cosine_sim = cosine_similarity(count_matrix)
# get movietitle from its title
movie_user_likes = input("please type the name of your favourite movie: ")
# titles in datasets are captalized
movie_index = get_index_from_title(movie_user_likes.title())
similar_movies = list(enumerate(cosine_sim[movie_index]))
# sort similar movies
sorted_similar_movies = sorted(
similar_movies, key=lambda x: x[1], reverse=True)
# printing first 10 similar movies
i = 0
for elements in sorted_similar_movies:
print(get_title_from_index(elements[0]))
i = i + 1
if i > 10:
break