-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
75 lines (61 loc) · 2.61 KB
/
app.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
from flask import Flask, request, render_template
import pandas as pd
import numpy as np
from scipy.sparse import csr_matrix
from sklearn.neighbors import NearestNeighbors
app = Flask(__name__)
movies = pd.read_csv("./dataset/movies.csv")
ratings = pd.read_csv("./dataset/ratings.csv")
final_dataset = ratings.pivot(
index='movieId', columns='userId', values='rating')
final_dataset.fillna(0, inplace=True)
no_user_voted = ratings.groupby('movieId')['rating'].agg('count')
no_movies_voted = ratings.groupby('userId')['rating'].agg('count')
final_dataset = final_dataset.loc[:,
no_movies_voted[no_movies_voted > 50].index]
csr_data = csr_matrix(final_dataset.values)
final_dataset.reset_index(inplace=True)
knn = NearestNeighbors(metric='cosine', algorithm='brute',
n_neighbors=20, n_jobs=-1)
knn.fit(csr_data)
def get_movie_recommendation(movie_name):
n_movies_to_reccomend = 10
movie_list = movies[movies['title'].str.contains(movie_name)]
if len(movie_list):
movie_idx = movie_list.iloc[0]['movieId']
movie_idx = final_dataset[final_dataset['movieId']
== movie_idx].index[0]
distances, indices = knn.kneighbors(
csr_data[movie_idx], n_neighbors=n_movies_to_reccomend+1)
rec_movie_indices = sorted(list(zip(indices.squeeze().tolist(
), distances.squeeze().tolist())), key=lambda x: x[1])[:0:-1]
recommend_frame = []
for val in rec_movie_indices:
movie_idx = final_dataset.iloc[val[0]]['movieId']
idx = movies[movies['movieId'] == movie_idx].index
recommend_frame.append(
{'Title': movies.iloc[idx]['title'].values[0], 'Distance': val[1]})
df = pd.DataFrame(recommend_frame, index=range(
1, n_movies_to_reccomend+1))
return df
else:
return "No movie found. Please Try again"
@app.route('/')
def index():
return render_template('index.html')
@app.route('/', methods=['POST'])
def recommendation():
text = request.form['title']
text = text.title()
try:
result = get_movie_recommendation(text)
name = []
distance = []
for i in range(len(result)):
name.append(result.iloc[i][0])
distance.append(result.iloc[i][1])
return render_template('recommendation.html', movie_names=name, movie_date=distance, title=text)
except AttributeError:
return render_template('error.html', title=text)
if __name__ == '__main__':
app.run(debug=True)