Menu

Creating the Recommendation Function

Creating the Recommendation Function

This lesson brings all components together into a single function that generates movie recommendations. The function first finds similar movies using KNN and then ranks them using a hybrid score.

Code:

def recommend_movie_knn(title, n=10, alpha=0.7, beta=0.3):

idx = movies[movies['clean_title'].str.contains(title, case=False)].index[0]

distances, indices = nn.kneighbors(tfidf_matrix[idx], n_neighbors=n+1)

results = []

for dist, i in zip(distances[0][1:], indices[0][1:]):

score = alpha * (1 - dist) + beta * (movies.iloc[i]['rating'] / 5)

results.append((movies.iloc[i]['title'],

movies.iloc[i]['genres'],

movies.iloc[i]['rating'],

score))

results = sorted(results, key=lambda x: x[3], reverse=True)

return pd.DataFrame(results, columns=['Title','Genres','Avg Rating','Hybrid Score'])

The hybrid score balances genre similarity and average rating. This ensures that recommendations are both relevant and popular, producing more meaningful results for users.