B- Describe the used algorithm
C- An Idea to extend this work for collaborative filtering approach.
D- Conclusion
code:
Your session crashed after using all available RAM.
View runtime logs
Skip to main content
dataMining RecommenderSystem.ipynb
dataMining RecommenderSystem.ipynb_Notebook unstarred
All changes saved
reading dataset and printing sample data
[12]
1s
first steps: finding simple rating avg, getting min num of votes required, then filtering to an new dataframe copy
[13]
0s
Calculate mean of vote average column
C = metadata['vote_average'].mean()
print(C)
Calculate the minimum number of votes required to be in the chart, m
m = metadata['vote_count'].quantile(0.90)
print(m)
Filter out all qualified movies into a new DataFrame
q_movies = metadata.copy().loc[metadata['vote_count'] >= m]
q_movies.shape
5.9834
630.2
(100, 24)
defining a function to create a weighted avg based on count and avg rating, saved in score field, and sorted top to bottom.
[14]
0s
Function that computes the weighted rating of each movie
def weighted_rating(x, m=m, C=C):
v = x['vote_count']
R = x['vote_average']
# Calculation based on the IMDB formula
return (v/(v+m) * R) + (m/(m+v) * C)
Define a new feature 'score' and calculate its value with weighted_rating()
#Sort movies based on score calculated above
q_movies = q_movies.sort_values('score', ascending=False)
#Print the top 3 movies
q_movies[['title', 'vote_count', 'vote_average', 'score']].head(3)
Developing content based system using tf-idf vector, removing stop words, and transform into a vector
[15]
0s
#Print plot overviews of the first 3 movies.
metadata['overview'].head(3)
#Import TfIdfVectorizer from scikit-learn
from sklearn.feature_extraction.text import TfidfVectorizer
#Define a TF-IDF Vectorizer Object. Remove all english stop words such as 'the', 'a'
tfidf = TfidfVectorizer(stop_words='english')
#Replace NaN with an empty string
metadata['overview'] = metadata['overview'].fillna('')
#Construct the required TF-IDF matrix by fitting and transforming the data
tfidf_matrix = tfidf.fit_transform(metadata['overview'])
Assistant
User
rewrite using 3 paragraphs, make them short and breif. make the last one talk about collaborative filtering
Assistant
The code implements a content-based recommendation system starting with preprocessing movie metadata. It calculates the mean vote average and sets a 90th-percentile vote count threshold to filter significant movies. A weighted rating formula is used to prioritize movies based on votes and ratings, and the movies are sorted accordingly.
For the recommendation system, the overview text is transformed into a TF-IDF matrix, removing stop words, and cosine similarity is computed. Additional features like keywords, cast, crew, and genres are incorporated into a combined "soup" feature, which is then vectorized and used to recompute cosine similarity. The system can recommend movies similar to a given title based on these similarity scores.
To enhance this system with collaborative filtering, user interaction data such as movie ratings can be collected to build a user-movie interaction matrix. Techniques like user-based or item-based collaborative filtering, as well as matrix factorization methods like SVD, can be employed to predict movie preferences. A hybrid model combining both content-based and collaborative filtering approaches could provide more accurate and personalized recommendations.
User
make this more simple:
SUMMARY:
this project implements a content-based only recommendation system starting with preprocessing movie metadata. It calculates the mean vote average and sets a percentile vote count threshold to filter significant movies. A weighted rating formula is used to prioritize movies based on votes and ratings, and the movies are sorted accordingly.
for the recommendation system, the overview text is transformed into a TF-IDF matrix, removing stop words, and cosine similarity is computed. Additional features like keywords, cast, crew, and genres are incorporated into a combined “soup” feature, which is then vectorized and used to recompute cosine similarity. The system can recommend movies similar to a given title based on these similarity scores.
to enhance this system with collaborative filtering, user interaction data such as movie ratings can be collected to build a user-movie interaction matrix. Techniques like user-based or item-based collaborative filtering, it can be employed to predict movie preferences. A hybrid model combining can provide more accurate/personalised recommendations.
Assistant
SUMMARY:
This project implements a content-based recommendation system by first preprocessing movie metadata. It calculates the average vote score and sets a vote count threshold to filter significant movies. A weighted rating formula then prioritizes and sorts the movies based on votes and ratings.
The system transforms the movie overviews into a TF-IDF matrix, removing stop words, and computes cosine similarity. Additional features like keywords, cast, crew, and genres are combined into a "soup" feature, vectorized, and used to recompute cosine similarity. It recommends movies similar to a given title based on these similarity scores.
To improve the system with collaborative filtering, user interaction data like movie ratings can be collected to build a user-movie interaction matrix. Techniques such as user-based or item-based collaborative filtering can predict movie preferences. A hybrid model combining both methods can offer more accurate and personalized recommendations.
#Output the shape of tfidf_matrix
tfidf_matrix.shape
tfidf.get_feature_names()[5000:5003]
(1000, 9397)
applying cosine similarity on vector matrix and constructing a transpose representation matrix
[16]
0s
Import linear_kernel
from sklearn.metrics.pairwise import linear_kernel
#Construct a reverse map of indices and movie titles
indices = pd.Series(metadata.index, index=metadata['title']).drop_duplicates()
cosine_sim[1] # long output of sim vector
implementing a function to find recommendation based on movie title, returns top 10 similar movies based on cosine similarity.
[17]
0s
Function that takes in movie title as input and outputs most similar movies
def get_recommendations(title, cosine_sim=cosine_sim):
# Get the index of the movie that matches the title
idx = indices[title]
code
# Get the pairwsie similarity scores of all movies with that movie
sim_scores = list(enumerate(cosine_sim[idx]))
# Sort the movies based on the similarity scores
sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)
# Get the scores of the 10 most similar movies
sim_scores = sim_scores[1:11]
# Get the movie indices
movie_indices = [i[0] for i in sim_scores]
# Return the top 10 most similar movies
return metadata['title'].iloc[movie_indices]
get_recommendations('Jumanji')
8 Sudden Death
363 Maverick
976 D3: The Mighty Ducks
954 Picnic
96 Shopping
894 My Favorite Year
839 Small Faces
591 Window to Paris
717 Getting Away with Murder
309 The Swan Princess
Name: title, dtype: object
Adding more data: Preparing keywords & credits datasets
[18]
2s
Merge keywords and credits into your main metadata dataframe
adding the new features to the existing metadata dataframe, formating them in a usable format, then cleaning strings from extra unnedded characters.
[19]
1s
Parse the stringified features into their corresponding python objects
from ast import literal_eval
Import Numpy
import numpy as np
features = ['cast', 'crew', 'keywords', 'genres']
for feature in features:
metadata[feature] = metadata[feature].apply(literal_eval)
def get_director(x):
joining all new features in a soup then trasforming into count vector, then testing with a movie title
[20]
def create_soup(x):
return ' '.join(x['keywords']) + ' ' + ' '.join(x['cast']) + ' ' + x['director'] + ' ' + ' '.join(x['genres'])
Reset index of your main DataFrame and construct reverse mapping as before
metadata = metadata.reset_index()
indices = pd.Series(metadata.index, index=metadata['title'])
get_recommendations('Jumanji', cosine_sim2)
552 The Pagemaster
59 The Indian in the Cupboard
898 The Wizard of Oz
239 Gordy
740 Kim
571 Andre
867 The Land Before Time III: The Time of the Grea...
989 Escape to Witch Mountain
450 Free Willy
700 Flipper
Name: title, dtype: object
Colab paid products - Cancel contracts here
0s
completed at 4:05 PM
Reset index of your main DataFrame and construct reverse mapping as before metadata = metadata.reset_index() indices = pd.Series(metadata.index, index=metadata['title'])
A. Insights from the Code
Data Preprocessing:
Dataset Loading and Inspection:
The code begins by loading a movie metadata CSV file using Pandas and displays a sample of the data.
Basic Statistics:
The mean vote average and the 90th percentile of vote counts are calculated, which helps in determining the threshold for significant movies.
Filtering:
The dataset is filtered to include only those movies that have a vote count above the 90th percentile. This reduces the dataset to a smaller, more manageable size.
Weighted Rating:
Custom Weighted Score Function:
A custom weighted rating based on the IMDB formula for calculating movie scores is implemented.
Sorting:
The movies are sorted in descending order based on their weighted scores.
Content-Based Recommendation System:
TF-IDF Vectorization:
The 'overview' text of the movies is transformed into a TF-IDF matrix while removing English stop words.
Cosine Similarity:
The cosine similarity matrix is computed from the TF-IDF matrix, facilitating the comparison of documents.
Content-Based Filtering Function:
A function is implemented to recommend movies similar to a given movie based on the cosine similarity scores of their TF-IDF representations.
Extended Feature Usage:
Additional Features:
Keywords, credits, cast, crew, and genres are extracted and merged with the main dataset.
String Parsing and Cleaning:
Additional features are cleaned and parsed to be in a usable format.
Enhanced Soup Feature:
A soup of relevant text data is created, effectively combining several features into one.
Count Vectorization:
The combined features are transformed into a count vector matrix and cosine similarity is recomputed based on this matrix.
Testing:
The system is tested with a sample movie title to get recommendations.
B. Algorithm Description
1. Data Preprocessing:
Loads data, calculates the mean and the 90th percentile of vote counts, and filters out the significant movies.
2. Weighted Rating Calculation:
Uses the weighted rating formula:
[
\text{Score} = \left( \frac{v}{v + m} \cdot R \right) + \left( \frac{m}{v + m} \cdot C \right)
]
where (v) is the number of votes, (R) is the average rating, (m) is the minimum votes for chart inclusion, and (C) is the mean rating.
3. Vectorization and Similarity Computation:
Uses TF-IDF vectorization for the 'overview' text.
Uses Cosine Similarity to compute the similarity matrix.
4. Recommendation Function:
Finds the most similar movies to a given movie based on the cosine similarity scores.
5. Additional Features Integration:
Incorporates extra features (keywords, cast, crew, genres) into a combined feature vector (soup).
Recomputes the cosine similarity matrix based on the combined feature vector.
C. Extension Idea for Collaborative Filtering
To extend this recommendation system to a collaborative filtering approach, we can integrate user interaction data:
Data Collection:
Collect user ratings for movies, which could be done using a user-movie matrix where users are represented in rows and movies in columns.
Model Implementation:
Implement collaborative filtering techniques such as:
User-based Collaborative Filtering: Find similarities between users based on their movie ratings.
Item-based Collaborative Filtering: Find similarities between movies based on user ratings.
Matrix Factorization:
Use advanced matrix factorization techniques like Singular Value Decomposition (SVD) or Alternating Least Squares (ALS) to decompose the user-item rating matrix and make predictions.
Hybrid System:
Combine the content-based filtering (as implemented) with collaborative filtering to leverage the strengths of both methods. The hybrid system can adjust the weights assigned to each method based on performance metrics.
D. Conclusion
The code provides a robust implementation of a content-based recommendation system, starting from data preprocessing to advanced techniques for combining multiple features into a unified recommendation system. By leveraging text vectorization (TF-IDF) and cosine similarity, it can recommend similar movies based on content. The system efficiently integrates additional metadata to improve recommendations.
To further enhance the recommendation engine, a collaborative filtering approach can be adopted. This can be achieved by incorporating user ratings and using matrix factorization techniques. A hybrid recommendation system, combining both content-based and collaborative filtering methods, can provide more accurate and personalized recommendations.
In essence, the code showcases a scalable and explainable process for building recommendation systems, setting a solid foundation for further enhancements and extensions.