Spaces:
Runtime error
Runtime error
Model file uploaded
Browse files
model.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pickle
|
| 2 |
+
import pandas as pd
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def generate_recomendation(user_id, top):
|
| 6 |
+
"""
|
| 7 |
+
Genera recomendaciones para un usuario utilizando el modelo SVD
|
| 8 |
+
|
| 9 |
+
Args:
|
| 10 |
+
- svd_model: modelo SVD previamente entrenado
|
| 11 |
+
- user_id: id del usuario para el cual se generarán las recomendaciones
|
| 12 |
+
- top: cantidad de recomendaciones a generar (default=4)
|
| 13 |
+
- df: DataFrame con columnas 'userId', 'movieId', 'score', 'title'
|
| 14 |
+
|
| 15 |
+
Returns:
|
| 16 |
+
- lista de títulos de películas recomendadas
|
| 17 |
+
"""
|
| 18 |
+
user_id = int(user_id)
|
| 19 |
+
top = int(top)
|
| 20 |
+
|
| 21 |
+
# Cargamos el modelo entrenado
|
| 22 |
+
fc_model_dir = "fc_model_svd_v1.pkl"
|
| 23 |
+
with open(f'{fc_model_dir}', 'rb') as file:
|
| 24 |
+
svd_model = pickle.load(file)
|
| 25 |
+
|
| 26 |
+
# Cargamos el dataset para el modelo
|
| 27 |
+
df = pd.read_parquet("fc_model.parquet")
|
| 28 |
+
|
| 29 |
+
# Obtener las películas que el usuario no ha visto aún
|
| 30 |
+
movies_seen = set(df[df['userId'] == user_id]['movieId'])
|
| 31 |
+
movies_all = set(df['movieId'])
|
| 32 |
+
movies_unseen = list(movies_all - movies_seen)
|
| 33 |
+
|
| 34 |
+
# Obtener las recomendaciones
|
| 35 |
+
predicted_ratings = [svd_model.predict(user_id, movie_id).est for movie_id in movies_unseen]
|
| 36 |
+
|
| 37 |
+
# Ordenar las películas según su predicción de rating
|
| 38 |
+
movie_rating = list(zip(movies_unseen, predicted_ratings))
|
| 39 |
+
movie_rating.sort(key=lambda x: x[1], reverse=True)
|
| 40 |
+
|
| 41 |
+
# Obtener los títulos de las películas recomendadas
|
| 42 |
+
recommended_movies = movie_rating[:top]
|
| 43 |
+
recommended_titles = [df[df['movieId'] == movie_id]['title'].iloc[0] for movie_id, _ in recommended_movies]
|
| 44 |
+
list_recommended_titles = [movie.title() for movie in recommended_titles]
|
| 45 |
+
return f"Las {top} películas que pueden gustarle al usuario {user_id} son: {', '.join(list_recommended_titles)}"
|
| 46 |
+
|
| 47 |
+
# print(generate_recomendation(543,top=3))
|