| 40 | |
| 41 | # create a function that generates recommendations |
| 42 | def recommend(title): |
| 43 | # get the row in the dataframe for this movie |
| 44 | idx = movie2idx[title] |
| 45 | if type(idx) == pd.Series: |
| 46 | idx = idx.iloc[0] |
| 47 | # print("idx:", idx) |
| 48 | |
| 49 | # calculate the pairwise similarities for this movie |
| 50 | query = X[idx] |
| 51 | scores = cosine_similarity(query, X) |
| 52 | |
| 53 | # currently the array is 1 x N, make it just a 1-D array |
| 54 | scores = scores.flatten() |
| 55 | |
| 56 | # get the indexes of the highest scoring movies |
| 57 | # get the first K recommendations |
| 58 | # don't return itself! |
| 59 | recommended_idx = (-scores).argsort()[1:6] |
| 60 | |
| 61 | # return the titles of the recommendations |
| 62 | return df['title'].iloc[recommended_idx] |
| 63 | |
| 64 | |
| 65 | print("\nRecommendations for 'Scream 3':") |