jchen8000 commited on
Commit
48de9e2
·
verified ·
1 Parent(s): 68a2379

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +94 -1
app.py CHANGED
@@ -121,11 +121,97 @@ def recommend_movies_cf(movie_title):
121
  format_string = "{:>5.2f} {:<20}"
122
  return "Score Title\n" + "\n".join([format_string.format(score, title) for title, score in recommendations])
123
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
  # Create a list of movie titles for the dropdown
125
  movie_list = random.sample(movies['title'].tolist(), input_count)
126
  total_movies = len(movies)
127
 
128
- # Update the Gradio interface
129
  with gr.Blocks() as iface:
130
  with gr.Tab("Content-Based Filtering"):
131
  gr.Interface(fn=recommend_movies_cb,
@@ -141,5 +227,12 @@ with gr.Blocks() as iface:
141
  title="Movie Recommender - Item-Based Collaborative Filtering",
142
  description="Select a movie to get recommendations based on collaborative filtering.")
143
 
 
 
 
 
 
 
 
144
  # Launch the app
145
  iface.launch()
 
121
  format_string = "{:>5.2f} {:<20}"
122
  return "Score Title\n" + "\n".join([format_string.format(score, title) for title, score in recommendations])
123
 
124
+ ######################################
125
+ #
126
+ # Collaborative Filtering with Neural Network (Item-based)
127
+ #
128
+ ######################################
129
+
130
+ # Normalize the ratings
131
+ scaler = MinMaxScaler()
132
+ movie_user_matrix_scaled = scaler.fit_transform(movie_user_matrix)
133
+
134
+ # Define the autoencoder model
135
+ input_dim = movie_user_matrix.shape[1]
136
+ encoding_dim = 32
137
+
138
+ input_layer = Input(shape=(input_dim,))
139
+ encoded = Dense(64, activation='relu')(input_layer)
140
+ encoded = Dense(encoding_dim, activation='relu')(encoded)
141
+ decoded = Dense(64, activation='relu')(encoded)
142
+ decoded = Dense(input_dim, activation='sigmoid')(decoded)
143
+
144
+ autoencoder = Model(input_layer, decoded)
145
+ autoencoder.compile(optimizer='adam', loss='mean_squared_error')
146
+
147
+ # Train the autoencoder
148
+ autoencoder.fit(movie_user_matrix_scaled, movie_user_matrix_scaled,
149
+ epochs=50, batch_size=64, shuffle=True, validation_split=0.2,
150
+ verbose=0)
151
+
152
+
153
+
154
+
155
+ # Use the trained autoencoder to predict the complete matrix
156
+ predicted_matrix_scaled = autoencoder.predict(movie_user_matrix_scaled)
157
+ predicted_matrix = scaler.inverse_transform(predicted_matrix_scaled)
158
+
159
+ # Create a DataFrame with the predicted matrix
160
+ predicted_matrix_df = pd.DataFrame(predicted_matrix, index=movie_user_matrix.index, columns=movie_user_matrix.columns)
161
+
162
+ # Compute the cosine similarity between movies using the predicted matrix
163
+ movie_similarity_cfnn = cosine_similarity(predicted_matrix)
164
+
165
+ # Create a DataFrame with movie similarities
166
+ movie_similarity_cfnn_df = pd.DataFrame(movie_similarity, index=movie_user_matrix.index, columns=movie_user_matrix.index)
167
+
168
+ # Function to get movie recommendations using item-based collaborative filtering
169
+ def get_cfnn_recommendations(movie_title, movie_similarity_df=movie_similarity_cfnn_df, movies=movies, n=result_count):
170
+ # Get the movieId for the input movie title
171
+ movie_id = movies[movies['title'] == movie_title]['movieId'].values[0]
172
+
173
+ # Check if the movie is in our similarity matrix
174
+ if movie_id not in movie_similarity_df.index:
175
+ return []
176
+
177
+ # Get the row of similarity scores for this movie
178
+ similar_scores = movie_similarity_df.loc[movie_id]
179
+
180
+ # Sort the scores in descending order
181
+ similar_scores = similar_scores.sort_values(ascending=False)
182
+
183
+ # Get the indices of the top-n most similar movies (excluding the input movie itself)
184
+ similar_movie_indices = similar_scores.index[1:n+1]
185
+
186
+ # Get the titles and similarity scores of the recommended movies
187
+ recommendations = []
188
+ for idx in similar_movie_indices:
189
+ title = movies.loc[movies['movieId'] == idx, 'title'].values[0]
190
+ score = similar_scores[idx]
191
+ recommendations.append((title, score))
192
+
193
+ return recommendations
194
+
195
+ # Function for Gradio interface
196
+ def recommend_movies_cfnn(movie_title):
197
+ if movie_title not in movies['title'].values:
198
+ return f"Movie '{movie_title}' not found in the dataset."
199
+
200
+ recommendations = get_cfnn_recommendations(movie_title)
201
+ format_string = "{:>5.2f} {:<20}"
202
+ return "Score Title\n" + "\n".join([format_string.format(score, title) for title, score in recommendations])
203
+
204
+
205
+ ######################################
206
+ #
207
+ # Gradio interface
208
+ #
209
+ ######################################
210
+
211
  # Create a list of movie titles for the dropdown
212
  movie_list = random.sample(movies['title'].tolist(), input_count)
213
  total_movies = len(movies)
214
 
 
215
  with gr.Blocks() as iface:
216
  with gr.Tab("Content-Based Filtering"):
217
  gr.Interface(fn=recommend_movies_cb,
 
227
  title="Movie Recommender - Item-Based Collaborative Filtering",
228
  description="Select a movie to get recommendations based on collaborative filtering.")
229
 
230
+ with gr.Tab("Collaborative Filtering with Neural Network"):
231
+ gr.Interface(fn=recommend_movies_cfnn,
232
+ inputs=gr.Dropdown(movie_list, label=f"Select a Movie (Total movies: {total_movies}, randomly list {input_count} for demo purpose.)"),
233
+ outputs=[gr.Textbox(label="Recommended Movies:")],
234
+ title="Movie Recommender - Item-Based Collaborative Filtering",
235
+ description="Select a movie to get recommendations based on collaborative filtering.")
236
+
237
  # Launch the app
238
  iface.launch()