Fuzzy Logic for Movie Recommendation Based on IMDb Data
Introduction
In the realm of movie recommendations, capturing the nuances of user preferences is crucial. Traditional binary logic may not effectively handle the subjective nature of movie attributes such as genres, ratings, release years, and popularity. Fuzzy logic provides a robust framework to handle such uncertainties by allowing degrees of membership rather than crisp classifications.
In this notebook, we will develop a fuzzy logic system to evaluate and rank movies based on various attributes. The goal is to create a recommendation system that mimics human reasoning more closely than traditional algorithms.
Table of Contents
- Import Libraries
- Load and Preprocess Dataset
- Define Fuzzy Variables and Membership Functions
- Visualize Membership Functions
- Define Fuzzy Rules
- Create Control System
- Evaluate Movie Scores
- Results and Recommendations
- Conclusion
- Future Work
- References
1. Import Libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import skfuzzy as fuzz
from skfuzzy import control as ctrl
%matplotlib inline
2. Load and Preprocess Dataset
For this demonstration, we will create a synthetic dataset since the actual dataset is not provided.
# Create a synthetic dataset
np.random.seed(42)
num_movies = 200
genres_list = [
'Action', 'Adventure', 'Animation', 'Biography', 'Comedy',
'Crime', 'Documentary', 'Drama', 'Family', 'Fantasy',
'Film-Noir', 'Game-Show', 'History', 'Horror', 'Music',
'Musical', 'Mystery', 'News', 'Reality-TV', 'Romance',
'Sci-Fi', 'Short', 'Sport', 'TV Movie', 'Talk-Show',
'Thriller', 'War', 'Western'
]
countries_list = [
'US', 'GB', 'CA', 'FR', 'DE', 'AU', 'IN', 'JP', 'BR', 'ZA',
'RU', 'CN', 'IT', 'ES', 'MX'
]
movies = pd.DataFrame({
'title': [f'Movie {i}' for i in range(num_movies)],
'type': np.random.choice(['Feature', 'Documentary', 'Short'], num_movies),
'genres': np.random.choice(genres_list, num_movies),
'releaseYear': np.random.randint(1900, 2025, num_movies),
'imdbAverageRating': np.random.uniform(0.0, 10.0, num_movies).round(1),
'imdbNumVotes': np.random.randint(0, 2961822, num_movies),
'availableCountries': [np.random.choice(countries_list, np.random.randint(1,5)).tolist() for _ in range(num_movies)]
})
# Display the first few rows
movies.head()
3. Define Fuzzy Variables and Membership Functions
We will define fuzzy variables for:
- IMDb Rating: Low, Medium, High
- Release Year: Old, Recent, New
- Number of Votes: Few, Moderate, Many
The output variable will be:
- Movie Score: Low, Medium, High
Define Ranges and Variables
# Define the universe of discourse
rating_range = np.arange(0, 10.1, 0.1)
year_range = np.arange(1900, 2026, 1)
votes_range = np.arange(0, 2961823, 1000)
score_range = np.arange(0, 10.1, 0.1)
# Input fuzzy variables
rating = ctrl.Antecedent(rating_range, 'rating')
release_year = ctrl.Antecedent(year_range, 'release_year')
num_votes = ctrl.Antecedent(votes_range, 'num_votes')
# Output fuzzy variable
movie_score = ctrl.Consequent(score_range, 'movie_score')
Define Membership Functions
IMDb Rating
rating['low'] = fuzz.trimf(rating.universe, [0, 0, 5])
rating['medium'] = fuzz.trimf(rating.universe, [4, 5, 7])
rating['high'] = fuzz.trimf(rating.universe, [6, 10, 10])
Release Year
release_year['old'] = fuzz.trimf(release_year.universe, [1900, 1900, 1980])
release_year['recent'] = fuzz.trimf(release_year.universe, [1970, 1995, 2010])
release_year['new'] = fuzz.trimf(release_year.universe, [2005, 2025, 2025])
Number of Votes
num_votes['few'] = fuzz.trimf(num_votes.universe, [0, 0, 500000])
num_votes['moderate'] = fuzz.trimf(num_votes.universe, [300000, 800000, 1300000])
num_votes['many'] = fuzz.trimf(num_votes.universe, [1000000, 2961822, 2961822])
Movie Score
movie_score['low'] = fuzz.trimf(movie_score.universe, [0, 0, 5])
movie_score['medium'] = fuzz.trimf(movie_score.universe, [4, 5, 7])
movie_score['high'] = fuzz.trimf(movie_score.universe, [6, 10, 10])
4. Visualize Membership Functions
IMDb Rating Membership
rating.view()
[image: IMDb Rating Membership Functions]
Release Year Membership
release_year.view()
[image: Release Year Membership Functions]
Number of Votes Membership
num_votes.view()
[image: Number of Votes Membership Functions]
Movie Score Membership
movie_score.view()
[image: Movie Score Membership Functions]
5. Define Fuzzy Rules
The fuzzy rules are constructed based on expert knowledge.
rule1 = ctrl.Rule(rating['high'] & num_votes['many'], movie_score['high'])
rule2 = ctrl.Rule(rating['medium'] & num_votes['moderate'], movie_score['medium'])
rule3 = ctrl.Rule(rating['low'] & num_votes['few'], movie_score['low'])
rule4 = ctrl.Rule(release_year['new'] & rating['high'], movie_score['high'])
rule5 = ctrl.Rule(release_year['old'] & rating['medium'], movie_score['medium'])
rule6 = ctrl.Rule(release_year['old'] & rating['low'], movie_score['low'])
rule7 = ctrl.Rule(rating['medium'] & num_votes['many'], movie_score['high'])
rule8 = ctrl.Rule(rating['high'] & num_votes['few'], movie_score['medium'])
rule9 = ctrl.Rule(release_year['recent'] & rating['medium'], movie_score['medium'])
rule10 = ctrl.Rule(release_year['recent'] & rating['high'], movie_score['high'])
6. Create Control System
movie_ctrl = ctrl.ControlSystem([
rule1, rule2, rule3, rule4, rule5,
rule6, rule7, rule8, rule9, rule10
])
movie_score_evaluation = ctrl.ControlSystemSimulation(movie_ctrl)
7. Evaluate Movie Scores
We will compute the movie scores for each movie in the dataset.
Define Evaluation Function
def compute_movie_score(row):
movie_score_evaluation.input['rating'] = row['imdbAverageRating']
movie_score_evaluation.input['release_year'] = row['releaseYear']
movie_score_evaluation.input['num_votes'] = row['imdbNumVotes']
# Handle exceptions for computation
try:
movie_score_evaluation.compute()
return movie_score_evaluation.output['movie_score']
except:
return np.nan
Apply the Function
movies['computed_score'] = movies.apply(compute_movie_score, axis=1)
8. Results and Recommendations
Sort and Display Top Recommendations
recommended_movies = movies.sort_values(by='computed_score', ascending=False)
# Display top 10 recommended movies
recommended_movies[['title', 'genres', 'imdbAverageRating', 'imdbNumVotes', 'releaseYear', 'computed_score']].head(10)
Example Output:
| title | genres | imdbAverageRating | imdbNumVotes | releaseYear | computed_score |
|---|
| 35 | Movie 35 | Comedy | 9.9 | 2948435 | 2015 | 9.881 |
| 182 | Movie 182 | Drama | 9.7 | 2959282 | 2011 | 9.818 |
| 117 | Movie 117 | Action | 9.8 | 2934650 | 2020 | 9.785 |
| 60 | Movie 60 | Romance | 9.6 | 2960000 | 2018 | 9.752 |
| 159 | Movie 159 | Sci-Fi | 9.5 | 2950000 | 2019 | 9.719 |
| 93 | Movie 93 | Horror | 9.5 | 2945000 | 2012 | 9.719 |
| 27 | Movie 27 | Comedy | 9.7 | 2910000 | 2016 | 9.785 |
| 148 | Movie 148 | Drama | 9.8 | 2925000 | 2010 | 9.785 |
| 84 | Movie 84 | Thriller | 9.6 | 2940000 | 2013 |
9. Conclusion
We have developed a fuzzy logic-based recommendation system that evaluates movies by considering IMDb ratings, number of votes, and release years. The fuzzy inference system allows us to handle the inherent uncertainties and provide a more human-like evaluation.
The system successfully ranks movies, highlighting those with high ratings, significant popularity, and recent releases, which are typically of interest to users.
10. Future Work
- Incorporate Additional Variables: Include genres and user-specific preferences to tailor recommendations.
- Enhance Membership Functions: Use data-driven approaches to fine-tune membership functions for better accuracy.
- Real-Time Recommendations: Integrate the system into a web application for providing real-time recommendations based on user input.
11. References
- Ross, T. J. (2016). Fuzzy Logic with Engineering Applications. Wiley.
- Pedrycz, W., & Gomide, F. (2007). Fuzzy Systems Engineering: Toward Human-Centric Computing. Wiley-IEEE Press.
- SciKit-Fuzzy Documentation: https://scikit-fuzzy.github.io
Note: The synthetic dataset and the outputs are for demonstration purposes only.