-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathContentBasedFiltering.py
More file actions
334 lines (182 loc) · 7.27 KB
/
ContentBasedFiltering.py
File metadata and controls
334 lines (182 loc) · 7.27 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
#!/usr/bin/env python
# coding: utf-8
# # Content Based Filtering
# This algorithm recommends movies which are similar to the ones that user liked before.
#
# For example, if a person has liked the movie “Inception”, then this algorithm will recommend movies that fall under the same genre.
# 
# ### Dataset
# This dataset (ml-latest) describes 5-star rating and free-text tagging activity from [MovieLens](http://movielens.org), a movie recommendation service.
#
# It contains 22884377 ratings and 586994 tag applications across 34208 movies which was created by 247753 users.
# ## Preprocessing
# First, let's import all the required modules:
# In[1]:
import pandas as pd
import numpy as np
from surprise import accuracy
from math import sqrt
from sklearn.metrics import mean_squared_error
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
# In[2]:
movies_df = pd.read_csv(r'C:\Users\P Sai Deekshith\Recommender Systems\ml-100k\movies.csv')
ratings_df = pd.read_csv(r'C:\Users\P Sai Deekshith\Recommender Systems\ml-100k\ratings.csv')
# In[3]:
movies_df.head()
# In[4]:
ratings_df.head()
# Extract the year from Title column to a separate column:
# In[5]:
movies_df['year'] = movies_df.title.str.extract('(\(\d\d\d\d\))',expand=False)
movies_df['year'] = movies_df.year.str.extract('(\d\d\d\d)',expand=False)
movies_df['title'] = movies_df.title.str.replace('(\(\d\d\d\d\))', '')
movies_df['title'] = movies_df['title'].apply(lambda x: x.strip())
movies_df.head(50)
# Splitting the genre:
# In[6]:
movies_df['genres'] = movies_df.genres.str.split('|')
movies_df.head()
# #### On Hot Encoding
# In[7]:
moviesWithGenres_df = movies_df.copy()
for index, row in movies_df.iterrows():
for genre in row['genres']:
moviesWithGenres_df.at[index, genre] = 1
moviesWithGenres_df = moviesWithGenres_df.fillna(0)
moviesWithGenres_df.head()
# Removing timestamp column from ratings dataframe:
# In[8]:
ratings_df = ratings_df.drop('timestamp', 1)
ratings_df.head()
# ### User Input:
# In[9]:
# userInput = [
# {'title':'Breakfast Club, The', 'rating':5},
# {'title':'Toy Story', 'rating':3.5},
# {'title':'Jumanji', 'rating':2},
# {'title':'Pulp Fiction', 'rating':5},
# {'title':'Akira', 'rating':4.5}
# ]
# inputMovies = pd.DataFrame(userInput)
# inputMovies
userInput = [
{'title':'Grumpier Old Men', 'rating':3.180094},
{'title':'Toy Story', 'rating':3.894802},
{'title':'Jumanji', 'rating':3.221086},
{'title':'Waiting to Exhale', 'rating':2.879727},
{'title':'Father of the Bride Part II', 'rating':3.080811}
]
inputMovies = pd.DataFrame(userInput)
inputMovies
# 1 3.894802
# 2 3.221086
# 3 3.180094
# 4 2.879727
# 5 3.080811
# Making a DataFrame out of UserInput by adding movieId to it.
# In[10]:
inputId = movies_df[movies_df['title'].isin(inputMovies['title'].tolist())]
inputMovies = pd.merge(inputId, inputMovies)
inputMovies = inputMovies.drop('genres', 1).drop('year', 1)
inputMovies.head()
# Creating a boolean matrix for the userInput based on the genre:
# In[11]:
userMovies = moviesWithGenres_df[moviesWithGenres_df['movieId'].isin(inputMovies['movieId'].tolist())]
userMovies = userMovies.reset_index(drop=True)
userGenreTable = userMovies.drop('movieId', 1).drop('title', 1).drop('genres', 1).drop('year', 1)
userGenreTable
# We have to learn from input's preference and try to predict the ratings.
#
# We can do this by using the input's ratings and multiplying them into the input's genre table and summing up the resulting table by column.
# This is called dot product between a matrix and a vector.
#
#
# In[12]:
inputMovies['rating']
# In[13]:
userProfile = userGenreTable.transpose().dot(inputMovies['rating'])
userProfile
# Now, we have formed the User's Profile.
# Extracting the genre table from the original dataframe.
# In[14]:
genreTable = moviesWithGenres_df.set_index(moviesWithGenres_df['movieId'])
genreTable = genreTable.drop('movieId', 1).drop('title', 1).drop('genres', 1).drop('year', 1)
genreTable.head()
# Computing the weighted verage of every movie based on the input profile:
# In[15]:
recommendationTable_df = ((genreTable*userProfile).sum(axis=1))/(userProfile.sum())
recommendationTable_df.head()
# In[16]:
recommendationTable_df = recommendationTable_df.sort_values(ascending=False)
recommendationTable_df.head()
# ### The Final Recommendation Table
# In[17]:
movies_df = movies_df.loc[movies_df['movieId'].isin(recommendationTable_df.head(100).keys())]
movies_df.head(20)
# ### Evaluation
# We use RMSE(Root Mean Square Error) to evaluate the recommendations.
# Lower values of RMSE indicate better fit. RMSE is a good measure of how accurately the model predicts the response, and it is the most important criterion for fit if the main purpose of the model is prediction.
# 
# In[18]:
recommended_rating = pd.DataFrame(recommendationTable_df)
recommended_rating['movieId'] = recommended_rating.index
recommended_rating.reset_index(drop=True, inplace=True)
recommendationTable_df.reset_index(drop=True, inplace=True)
recommended_rating['recommended_ratings'] = recommendationTable_df
recommended_rating.head()
# In[19]:
recommended_rating.drop([0], axis=1, inplace=True)
recommended_rating.head()
# In[20]:
finalEvaluationTable = recommended_rating
finalEvaluationTable['recommended_ratings'] *= 5
finalEvaluationTable.head()
# In[21]:
finalEvaluationTable = finalEvaluationTable.sort_values('movieId')
finalEvaluationTable.head()
# In[22]:
true_ratings = ratings_df.groupby(ratings_df['movieId']).mean()
true_ratings.drop('userId', axis=1, inplace=True)
true_ratings.head()
# In[23]:
recommendedMovieId = finalEvaluationTable['movieId']
# In[24]:
true_ratings['movieId'] = true_ratings.index
true_ratings.reset_index(drop=True, inplace=True)
true_ratings = true_ratings[true_ratings.movieId.isin(recommendedMovieId)]['rating']
true_ratings.head()
# In[25]:
true_ratings = pd.DataFrame(true_ratings)
true_ratings.reset_index(drop=True, inplace=True)
true_ratings.head()
# In[26]:
finalEvaluationTable.head()
finalEvaluationTable.reset_index(drop=True, inplace=True)
finalEvaluationTable['true_ratings'] = true_ratings
#finalEvaluationTable.reset_index(drop=True, inplace=True)
finalEvaluationTable.dropna(inplace=True)
finalEvaluationTable.head()
# In[27]:
#finalEvaluationTable = finalEvaluationTable[finalEvaluationTable.movieId.isin(inputMovies.movieId)]
# In[30]:
def rmseContentBased():
rmse = sqrt(mean_squared_error(finalEvaluationTable['true_ratings'], finalEvaluationTable['recommended_ratings']))
print("The RMSE value is : " + str(rmse))
return rmse
# In[33]:
#rmseContentBased()
# ### Advantages and Disadvantages of Content-Based Filtering
#
# ##### Advantages
#
# - Learns user's preferences
# - Highly personalized for the user
#
# ##### Disadvantages
#
# - Doesn't take into account what others think of the item, so low quality item recommendations might happen
# - Extracting data is not always intuitive
# - Determining what characteristics of the item the user dislikes or likes is not always obvious
#
# In[ ]: