Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Recommender Systems by User-based Collaborative Filtering #483

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
using Algorithms.RecommenderSystem;
using NUnit.Framework;
using System.Collections.Generic;

namespace Algorithms.Tests.RecommenderSystem
{
[TestFixture]
public class CollaborativeFilteringTests
{
private CollaborativeFiltering recommender = new();
private Dictionary<string, Dictionary<string, double>> testRatings = null!;

[SetUp]
public void Setup()
{
recommender = new CollaborativeFiltering();

testRatings = new Dictionary<string, Dictionary<string, double>>
{
["user1"] = new()
{
["item1"] = 5.0,
["item2"] = 3.0,
["item3"] = 4.0
},
["user2"] = new()
{
["item1"] = 4.0,
["item2"] = 2.0,
["item3"] = 5.0
},
["user3"] = new()
{
["item1"] = 3.0,
["item2"] = 4.0,
["item4"] = 3.0
}
};
}

[Test]
[TestCase("item1", 4.0, 5.0)]
[TestCase("item2", 2.0, 4.0)]
public void CalculateSimilarity_WithValidInputs_ReturnsExpectedResults(
string commonItem,
double rating1,
double rating2)
{
var user1Ratings = new Dictionary<string, double> { [commonItem] = rating1 };
var user2Ratings = new Dictionary<string, double> { [commonItem] = rating2 };

var similarity = recommender.CalculateSimilarity(user1Ratings, user2Ratings);

Assert.That(similarity, Is.InRange(-1.0, 1.0));
}

[Test]
public void CalculateSimilarity_WithNoCommonItems_ReturnsZero()
{
var user1Ratings = new Dictionary<string, double> { ["item1"] = 5.0 };
var user2Ratings = new Dictionary<string, double> { ["item2"] = 4.0 };

var similarity = recommender.CalculateSimilarity(user1Ratings, user2Ratings);

Assert.That(similarity, Is.EqualTo(0));
}

[Test]
public void PredictRating_WithNonexistentItem_ReturnsZero()
{
var predictedRating = recommender.PredictRating("nonexistentItem", "user1", testRatings);

Assert.That(predictedRating, Is.EqualTo(0));
}
}
}
82 changes: 82 additions & 0 deletions Algorithms/RecommenderSystem/CollaborativeFiltering.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
using System;
using System.Collections.Generic;
using System.Linq;

namespace Algorithms.RecommenderSystem
{
public class CollaborativeFiltering
{
/// <summary>
/// Method to calculate similarity between two users using Pearson correlation.
/// </summary>
/// <param name="user1Ratings">Rating of User 1.</param>
/// <param name="user2Ratings">Rating of User 2.</param>
/// <returns>double value to reflect the index of similarity between two users.</returns>
public double CalculateSimilarity(Dictionary<string, double> user1Ratings, Dictionary<string, double> user2Ratings)
{
var commonItems = user1Ratings.Keys.Intersect(user2Ratings.Keys).ToList();
if (commonItems.Count == 0)
{
return 0;
}

var user1Scores = commonItems.Select(item => user1Ratings[item]).ToArray();
var user2Scores = commonItems.Select(item => user2Ratings[item]).ToArray();

var avgUser1 = user1Scores.Average();
var avgUser2 = user2Scores.Average();

double numerator = 0;
double sumSquare1 = 0;
double sumSquare2 = 0;
double epsilon = 1e-10;

for (var i = 0; i < commonItems.Count; i++)
{
var diff1 = user1Scores[i] - avgUser1;
var diff2 = user2Scores[i] - avgUser2;

numerator += diff1 * diff2;
sumSquare1 += diff1 * diff1;
sumSquare2 += diff2 * diff2;
}

var denominator = Math.Sqrt(sumSquare1 * sumSquare2);
return Math.Abs(denominator) < epsilon ? 0 : numerator / denominator;
}

/// <summary>
/// Predict a rating for a specific item by a target user.
/// </summary>
/// <param name="targetItem">The item for which the rating needs to be predicted.</param>
/// <param name="targetUser">The user for whom the rating is being predicted.</param>
/// <param name="ratings">
/// A dictionary containing user ratings where:
/// - The key is the user's identifier (string).
/// - The value is another dictionary where the key is the item identifier (string), and the value is the rating given by the user (double).
/// </param>
/// <returns>The predicted rating for the target item by the target user.
/// If there is insufficient data to predict a rating, the method returns 0.
/// </returns>
public double PredictRating(string targetItem, string targetUser, Dictionary<string, Dictionary<string, double>> ratings)
{
var targetUserRatings = ratings[targetUser];
double totalSimilarity = 0;
double weightedSum = 0;
double epsilon = 1e-10;

foreach (var otherUser in ratings.Keys.Where(u => u != targetUser))
{
var otherUserRatings = ratings[otherUser];
if (otherUserRatings.ContainsKey(targetItem))
{
var similarity = CalculateSimilarity(targetUserRatings, otherUserRatings);
totalSimilarity += Math.Abs(similarity);
weightedSum += similarity * otherUserRatings[targetItem];
}
}

return Math.Abs(totalSimilarity) < epsilon ? 0 : weightedSum / totalSimilarity;
}
}
}
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,8 @@ find more than one implementation for the same objective but using different alg
* [Josephus Problem](./Algorithms/Numeric/JosephusProblem.cs)
* [Newton's Square Root Calculation](./Algorithms/NewtonSquareRoot.cs)
* [SoftMax Function](./Algorithms/Numeric/SoftMax.cs)
* [RecommenderSystem](./Algorithms/RecommenderSystem)
* [CollaborativeFiltering](./Algorithms/RecommenderSystem/CollaborativeFiltering)
* [Searches](./Algorithms/Search)
* [A-Star](./Algorithms/Search/AStar/)
* [Binary Search](./Algorithms/Search/BinarySearcher.cs)
Expand Down