Loading…
DS · Recommenders & reduction · Program 27 · Bonus
Content-based recommendation system.
1import pandas as pd2from sklearn.feature_extraction.text import TfidfVectorizer3from sklearn.metrics.pairwise import cosine_similarity4 5movies = pd.DataFrame({6 'Title': ['Inception', 'Interstellar', 'The Matrix', 'Titanic',7 'The Notebook', 'La La Land', 'Avengers', 'Iron Man',8 'Gravity', 'Pride and Prejudice'],9 'Genre': ['SciFi Thriller', 'SciFi Adventure', 'SciFi Action', 'Romance Drama',10 'Romance Drama', 'Romance Musical', 'Action Superhero', 'Action Superhero',11 'SciFi Thriller', 'Romance Drama'],12 'Description': [13 'A thief enters dreams to steal secrets and plant an idea in a mind',14 'Astronauts travel through a wormhole in space to save humanity',15 'A hacker learns reality is a simulation and fights the machines',16 'A love story aboard a ship that sinks in the ocean',17 'A young couple falls in love despite family and class differences',18 'A musician and an actress fall in love while chasing dreams in the city',19 'Superheroes team up to save the world from an alien invasion',20 'A billionaire engineer builds a powered suit and becomes a superhero',21 'Astronauts are stranded in space after an accident and fight to survive',22 'A love story about pride, class and family in old England']})23 24tfidf = TfidfVectorizer(stop_words='english').fit_transform(movies['Genre'] + ' ' + movies['Description'])25sim = cosine_similarity(tfidf)26 27scores = pd.Series(sim[1], index=movies['Title']).drop('Interstellar').sort_values(ascending=False)28print("Recommendations for 'Interstellar':\n", scores.head(3).round(3))Recommendations for 'Interstellar': Title Gravity 0.285 Avengers 0.106 The Matrix 0.064 dtype: float64
Run program 27 in your browser
Python 3.14 · Pyodide. Change the code or the input, run it, break it, and see what happens.