Book recommender

In this example, I'll use a dataset from Kaggle that contains book ratings from the "Book-Crossings" dataset. This dataset includes user ratings for books.

  • Download the dataset: You can download the dataset from Kaggle. The dataset is available at this link: Book-Crossings Dataset on Kaggle. You'll need to create a Kaggle account and accept the dataset's terms and conditions to access it.
  • Run this code:
  • import pandas as pd
    
    # Load the dataset
    data = pd.read_csv('Ratings.csv', sep=',', error_bad_lines=False, encoding='latin-1')
    
    # Rename columns for clarity
    data.columns = ['user_id', 'book_id', 'rating']
    
    # Display the first few rows of the dataset
    print(data.head())
    
    # Keep only the first 1000 rows
    data = data.head(1000)
    
    user_item_matrix = data.pivot(index='user_id', columns='book_id', values='rating')
    user_item_matrix = user_item_matrix.fillna(0)
    
    from sklearn.metrics.pairwise import cosine_similarity
    
    # Calculate user-user similarity matrix
    user_similarity = cosine_similarity(user_item_matrix)
    
    # Create a DataFrame from the similarity matrix
    user_similarity_df = pd.DataFrame(user_similarity, index=user_item_matrix.index, columns=user_item_matrix.index)
    
    # Function to get book recommendations for a given user
    def get_book_recommendations(user_id, num_recommendations=5):
        # Get the user's similarity scores with other users
        user_similarities = user_similarity_df[user_id]
    
        # Get books that the user has not rated
        user_rated_books = user_item_matrix.loc[user_id]
        unrated_books = user_rated_books[user_rated_books == 0].index
    
        # Calculate the weighted sum of ratings for unrated books
        book_scores = user_item_matrix.T.dot(user_similarities)
        book_scores = book_scores[unrated_books]
    
        # Sort the books by score and get top recommendations
        top_recommendations = book_scores.sort_values(ascending=False).head(num_recommendations)
    
        return top_recommendations
    
    # Get book recommendations for a user (e.g., user_id=276726)
    user_id = 276726
    recommendations = get_book_recommendations(user_id)
    print("Top 5 Book Recommendations for User", user_id)
    print(recommendations)

results:

   user_id     book_id  rating
0   276725  034545104X       0
1   276726  0155061224       5
2   276727  0446520802       0
3   276729  052165615X       3
4   276729  0521795028       6

Top 5 Book Recommendations for User 276726
book_id
000225669X    0.0
3426671298    0.0
3426702266    0.0
342677609X    0.0
3440054594    0.0
dtype: float64

In this example, we first load and preprocess the Book-Crossings dataset, create a user-item matrix, and then use cosine similarity to calculate user-user similarity scores. Finally, we provide book recommendations for a specific user based on their similarity to other users.