# Step 1: Import necessary libraries
import pandas as pd
from surprise import Dataset, Reader, SVD
from surprise.model_selection import cross_validate, train_test_split
from surprise import accuracy
# Step 2: Load the dataset
# Download the MovieLens dataset (https://grouplens.org/datasets/movielens/) and adjust the file paths accordingly
ratings_path = 'path/to/ratings.csv'
movies_path = 'path/to/movies.csv'
# Read the ratings and movies files
ratings = pd.read_csv(ratings_path)
movies = pd.read_csv(movies_path)
# Step 3: Preprocess and explore the dataset
# Check for missing values
ratings.isna().sum()
# Merge the movies and ratings datasets
merged_data = pd.merge(movies, ratings, on='movieId')
# Check the top-rated movies (minimum 100 ratings)
top_rated = merged_data.groupby('title').agg({'rating': ['count', 'mean']})
top_rated = top_rated[top_rated[('rating', 'count')] > 100].sort_values(('rating', 'mean'), ascending=False)
# Step 4: Create a collaborative filtering model (using matrix factorization)
reader = Reader(rating_scale=(1, 5))
data = Dataset.load_from_df(merged_data[['userId', 'movieId', 'rating']], reader)
# Use the Singular Value Decomposition (SVD) algorithm
algo = SVD()
# Step 5: Evaluate the model
cross_validation_results = cross_validate(algo, data, measures=['RMSE', 'MAE'], cv=5, verbose=True)
# Step 6: Build the recommender system
trainset = data.build_full_trainset()
algo.fit(trainset)
# Step 7: Test the recommender system
# Change user_id and movie_id to test the recommendations
user_id = 1
movie_id = 1
predicted_rating = algo.predict(user_id, movie_id)
print(f"Predicted rating for user {user_id} and movie {movie_id}: {predicted_rating.est}")
This script uses the Singular Value Decomposition (SVD) algorithm from the surprise library to create a collaborative filtering model. The recommender system can now predict a user's rating for a movie, which can be used to recommend movies to that user based on their predicted ratings.