Spaces:
Runtime error
Runtime error
Download app.py from lsquaremaster/collaborative-filtering: direct link, hf CLI and curl.
- Browser
- Download file 1.64 kB
-
https://huggingface.co/spaces/lsquaremaster/collaborative-filtering/resolve/main/app.py
- Command line
-
hf download hf://spaces/lsquaremaster/collaborative-filtering/app.py
-
curl -L -o app.py https://huggingface.co/spaces/lsquaremaster/collaborative-filtering/resolve/main/app.py
1.64 kB
| import numpy as np | |
| import gradio as gr | |
| # Create a toy user-movie ratings matrix (replace this with your real data) | |
| # Rows represent users, columns represent movies | |
| # Use NaN for missing ratings | |
| ratings_matrix = np.array([ | |
| [5, 3, 0, 0, 2], | |
| [4, 0, 0, 0, 1], | |
| [1, 1, 0, 0, 0], | |
| [1, 0, 0, 0, 0], | |
| [0, 1, 5, 4, 0], | |
| ]) | |
| # Collaborative filtering model function | |
| def collaborative_filtering(user_id): | |
| # Get the ratings of the user | |
| user_ratings = ratings_matrix[user_id] | |
| # Calculate the similarity between the user and all other users | |
| similarities = [] | |
| for other_user_ratings in ratings_matrix: | |
| similarity = np.dot(user_ratings, other_user_ratings) / ( | |
| np.linalg.norm(user_ratings) * np.linalg.norm(other_user_ratings) | |
| ) | |
| similarities.append(similarity) | |
| # Find the most similar user (excluding the user itself) | |
| most_similar_user_id = np.argmax(similarities) | |
| # Get the movie ratings of the most similar user | |
| movie_ratings = ratings_matrix[most_similar_user_id] | |
| # Predict the ratings for the user based on the most similar user's ratings | |
| predicted_ratings = np.where(user_ratings == 0, movie_ratings, 0) | |
| # Get the indices of the top recommended movies | |
| top_movie_indices = np.argsort(predicted_ratings)[::-1][:5] | |
| return top_movie_indices.tolist() | |
| # Create a Gradio interface | |
| iface = gr.Interface( | |
| fn=collaborative_filtering, | |
| inputs="number", | |
| outputs="text", | |
| title="Movie Recommendation System", | |
| description="Enter a user ID (0-4) to get movie recommendations.", | |
| ) | |
| # Launch the Gradio interface | |
| iface.launch() | |