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 to determining how similar two users are based on their rating patterns.

Here's the function we'll use:

#include <vector>
#include <numeric>
#include <cmath>

// Function to calculate Pearson correlation
double pearsonCorrelation(const std::vector<double>& ratings1, const std::vector<double>& ratings2) {
    size_t n = ratings1.size();
    if (n == 0 || n != ratings2.size()) return 0.0;

    double mean1 = std::accumulate(ratings1.begin(), ratings1.end(), 0.0) / n;
    double mean2 = std::accumulate(ratings2.begin(), ratings2.end(), 0.0) / n;

    double numerator = 0.0, denom1 = 0.0, denom2 = 0.0;
    for (size_t i = 0; i < n; ++i) {
        double diff1 = ratings1[i] - mean1;
        double diff2 = ratings2[i] - mean2;
        numerator += diff1 * diff2;
        denom1 += diff1 * diff1;
        denom2 += diff2 * diff2;
    }

    double denominator = std::sqrt(denom1) * std::sqrt(denom2);
    if (denominator == 0.0) return 0.0;
    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 read this data into a user-item map, allowing us to easily access any user's ratings:

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <unordered_map>
#include <map>

// Type aliases for clarity
using ItemRatings = std::map<std::string, double>;
using RatingsMap = std::unordered_map<std::string, ItemRatings>;

// Reads the user-item matrix from a file
RatingsMap readUsersItemsMatrix(const std::string& filePath) {
    RatingsMap usersItemsMatrix;
    std::ifstream file(filePath);
    std::string line;
    while (std::getline(file, line)) {
        std::istringstream iss(line);
        std::string user, item, ratingStr;
        if (std::getline(iss, user, ',') &&
            std::getline(iss, item, ',') &&
            std::getline(iss, ratingStr)) {
            double rating = std::stod(ratingStr);
            usersItemsMatrix[user][item] = rating;
        }
    }
    return usersItemsMatrix;
}

// Example usage:
int main() {
    std::string filePath = "../data/user_items_matrix.txt";
    RatingsMap usersItemsMatrix = readUsersItemsMatrix(filePath);
    // ... further code
    return 0;
}

The code reads the file line by line, splitting each line into user, item, and rating, and then stores this data in a map, usersItemsMatrix. 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:

#include <vector>
#include <iostream>

// Function to calculate non-weighted average rating for an item
double calculateNonWeightedAverage(const std::string& targetItem, const RatingsMap& userRatings) {
    std::vector<double> ratings;
    for (const auto& [user, ratingsMap] : userRatings) {
        auto it = ratingsMap.find(targetItem);
        if (it != ratingsMap.end()) {
            ratings.push_back(it->second);
        }
    }
    if (ratings.empty()) return 0.0;
    double sum = 0.0;
    for (double r : ratings) sum += r;
    return sum / ratings.size();
}

// Example usage:
int main() {
    std::string filePath = "../data/user_items_matrix.txt";
    RatingsMap usersItemsMatrix = readUsersItemsMatrix(filePath);
    double nonWeightedAverage = calculateNonWeightedAverage("ItemC", usersItemsMatrix);
    std::cout << "Non-Weighted Average Rating for ItemC: " << nonWeightedAverage << std::endl;
    return 0;
}

This function, calculateNonWeightedAverage, 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 a vector. This vector 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 targetVec variable:

#include <vector>
#include <string>

// Extract the ratings of the target user, excluding the target item
std::vector<double> generateTargetRatings(const std::string& targetUser,
                                         const std::string& targetItem,
                                         const RatingsMap& userRatings) {
    std::vector<double> targetVec;
    const auto& ratings = userRatings.at(targetUser);
    for (const auto& [item, rating] : ratings) {
        if (item != targetItem) {
            targetVec.push_back(rating);
        }
    }
    return targetVec;
}

// Example usage:
int main() {
    std::string filePath = "../data/user_items_matrix.txt";
    RatingsMap usersItemsMatrix = readUsersItemsMatrix(filePath);
    std::vector<double> targetRatings = generateTargetRatings("User3", "ItemC", usersItemsMatrix);
    // ... further code
    return 0;
}

By processing the targetVec, 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:

#include <cmath>
#include <vector>
#include <string>
#include <unordered_map>
#include <map>

// Prediction function
double weightedRatingPrediction(const std::string& targetUser,
                                const std::string& targetItem,
                                const RatingsMap& userRatings) {
    double weightedSum = 0.0, sumOfWeights = 0.0;
    
    // Use the function from the previous section to get target ratings
    std::vector<double> targetVec = generateTargetRatings(targetUser, targetItem, userRatings);

    for (const auto& [user, ratings] : userRatings) {
        if (user == targetUser || ratings.count(targetItem) == 0) continue;

        // Create other user's ratings vector (all items except target item)
        std::vector<double> otherVec;
        for (const auto& [item, rating] : ratings) {
            if (item != targetItem) {
                otherVec.push_back(rating);
            }
        }
        
        double similarity = pearsonCorrelation(targetVec, otherVec);
        weightedSum += similarity * ratings.at(targetItem);
        sumOfWeights += std::abs(similarity);
    }

    return (sumOfWeights == 0.0) ? 0.0 : weightedSum / sumOfWeights;
}

// Example usage and output:
int main() {
    std::string filePath = "../data/user_items_matrix.txt";
    RatingsMap usersItemsMatrix = readUsersItemsMatrix(filePath);
    double predicted_rating = weightedRatingPrediction("User3", "ItemC", usersItemsMatrix);
    std::cout << "Predicted Rating for User3 on ItemC (Weighted Average): " 
              << predicted_rating << "\n";
    return 0;
}

This function, weightedRatingPrediction, 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 the 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 change 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