Introduction

Welcome back! You've journeyed through the basics of recommendation systems, starting with baseline predictions and learning about similarity measures like Pearson Correlation. Understanding user similarity is crucial in recommendation systems, enabling more accurate predictions of unknown ratings. In this lesson, we will build upon that knowledge and focus on a practical approach to predicting user ratings using weighted averages combined with Pearson similarity. This technique allows us to make personalized recommendations by accounting for the weighted influence of similar users' ratings. By the end of the lesson, you’ll be able to effectively predict a user's rating for an item—a vital skill in crafting sophisticated recommendation systems.

Recap: Using Pearson Similarity

Before diving into this lesson's main topic, let's quickly revisit the Pearson correlation function we discussed in the previous lesson. This function is key in determining how similar two users are based on their rating patterns.

Here's the function we'll use:

import numpy as np

def pearson_correlation(ratings1, ratings2):
    n = len(ratings1)
    assert n == len(ratings2)

    mean1 = np.mean(ratings1)
    mean2 = np.mean(ratings2)

    diff1 = ratings1 - mean1
    diff2 = ratings2 - mean2

    numerator = np.sum(diff1 * diff2)
    denominator = np.sqrt(np.sum(diff1 ** 2) * np.sum(diff2 ** 2))

    if denominator == 0:
        return 0
    else:
        return numerator / denominator

This function calculates how closely two sets of user ratings align. Higher values indicate greater similarity, which will be important for today's task: predicting ratings based on these similarities.

Reading the User-Item Rating Matrix

To make predictions, we first need to read and interpret our user-item rating data. This data is stored in a file named user_items_matrix.txt. Let's explore how the file is structured and how to load this information.

The file is organized with each line representing a user's rating for a specific item. It has three comma-separated values: User, Item, and Rating. Here's an example:

User1,ItemA,5
User1,ItemB,4
User2,ItemA,3

We'll use Python to read this data into a user-item dictionary, allowing us to easily access any user's ratings:

def read_users_items_matrix(file_path):
    users_items_matrix = {}
    with open(file_path, 'r') as file:
        for line in file:
            user, item, rating = line.strip().split(',')
            if user not in users_items_matrix:
                users_items_matrix[user] = {}
            users_items_matrix[user][item] = int(rating)
    return users_items_matrix

# Example usage:
file_path = 'user_items_matrix.txt'
users_items_matrix = read_users_items_matrix(file_path)

The code reads the file line by line, splitting each line into user, item, and rating, and then stores this data in a dictionary users_items_matrix. This structure allows for easy retrieval and manipulation of ratings, facilitating our upcoming calculations.

Calculating Non-weighted Average Rating

Before making predictions using weighted averages, it's beneficial to understand non-weighted averages, which are simpler aggregates of ratings for a specific item across all users.

Let's look at how to compute this:

def calculate_non_weighted_average(target_item, user_ratings):
    ratings = [ratings[target_item] for ratings in user_ratings.values() if target_item in ratings]
    if not ratings:
        return None
    return np.mean(ratings)

# Example usage:
non_weighted_average = calculate_non_weighted_average('ItemC', users_items_matrix)
print(f"Non-Weighted Average Rating for ItemC: {non_weighted_average}")

This function, calculate_non_weighted_average, gathers all ratings for a specified item (e.g., 'ItemC') from the user-item matrix and calculates the average. It's a straightforward method but does not consider user similarity, unlike the weighted prediction—which we’ll explore next.

Formula
Preparing to Predict Ratings Using Weighted Average

To predict ratings using the weighted average approach, an essential preparatory step involves transforming the ratings of the target user into an array. This array will exclude the item that we aim to predict. This simplification allows us to focus on the set of ratings that are pivotal for calculating similarity with other users.

Here's how you can derive the target_ratings variable:

def generate_target_ratings(target_user, target_item, user_ratings):
    # Extract the ratings of the target user, excluding the target item
    target_ratings = np.array([rating for item, rating in user_ratings[target_user].items() if item != target_item])
    return target_ratings

# Example usage:
target_user = 'User3'
target_item = 'ItemC'
target_ratings = generate_target_ratings(target_user, target_item, users_items_matrix)

By processing the target_ratings, you establish the foundation for calculating Pearson similarity with other users, a crucial factor in making an informed prediction.

Predicting Rating Using Weighted Average

Now, let's move to the core of this lesson: predicting ratings using a weighted average that's informed by Pearson similarity. This method considers the similarity between users when calculating the predicted rating. Here’s a detailed implementation of this approach with explanations:

def weighted_rating_prediction(target_user, target_item, user_ratings):
    weighted_sum = 0
    sum_of_weights = 0
    
    # Retrieve the target user's ratings, excluding the target item
    target_ratings = np.array([rating for item, rating in user_ratings[target_user].items() if item != target_item])
    
    for user, ratings in user_ratings.items():
        # Skip the target user as we don't compare them to themselves
        if user != target_user and target_item in ratings:
            # Retrieve and prepare the other user's ratings, excluding the target item
            other_ratings = np.array([rating for item, rating in ratings.items() if item != target_item])
            
            # Calculate Pearson similarity between the target user and the other user
            similarity = pearson_correlation(target_ratings, other_ratings)
            
            # Accumulate weighted sum of ratings and running total of similarities
            weighted_sum += similarity * ratings[target_item]
            sum_of_weights += abs(similarity)

    # Return zero if there are no weights to prevent division by zero
    if sum_of_weights == 0:
        return 0
    else:
        # Compute and return the final weighted average rating prediction
        return weighted_sum / sum_of_weights

# Example usage and output:
predicted_rating = weighted_rating_prediction('User3', 'ItemC', users_items_matrix)
print(f"Predicted Rating for User3 on ItemC (Weighted Average): {predicted_rating}")

This function, weighted_rating_prediction, predicts the rating for a specified user ('User3') on a target item ('ItemC') by:

  1. Gathering Similarity Scores: Evaluating the closeness between the target user and each other user, expressed as a Pearson correlation score.
  2. Calculating a Weighted Sum: Using the similarity scores as weights, sum the product of each user's similarity and their rating for the target item.
  3. Normalizing by Sum of Similarity Weights: Divide the weighted sum by the sum of the similarity scores to produce a personalized rating prediction.

This method is more nuanced as it adjusts ratings based on the closeness of users' preferences, thus providing more personalized recommendations.

Example Data and Interpreting Results
Summary and Preparation for Practice

You’ve now learned to predict user ratings using a weighted average approach informed by user similarity. This lesson has enhanced your understanding of model-based recommendation systems, allowing you to make predictions that better reflect individual user preferences.

As you move into the practice exercises, take the opportunity to apply these techniques to different datasets and observe how recommendations alter based on user similarity. You are building the foundational knowledge to create effective recommendation systems.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal