Permalink
Browse files

implemented algorithm for Pearson Correlation Score

  • Loading branch information...
1 parent c065c75 commit 34aefb2aa7431882276f23e32ee6fed698b7b7ef @robertgreiner committed Nov 7, 2011
Showing with 68 additions and 5 deletions.
  1. +30 −0 Recommender.Tests/PearsonCorrelationTests.cs
  2. +38 −5 Recommender/PearsonCorrelation.cs
@@ -3,12 +3,42 @@
using System.Linq;
using System.Text;
using NUnit.Framework;
+using Recommender.Data;
namespace Recommender.Tests
{
[TestFixture]
class PearsonCorrelationTests
{
+ private PearsonCorrelation pearsonCorrelationScore;
+ [SetUp]
+ public void SetUp()
+ {
+ pearsonCorrelationScore = new PearsonCorrelation(ReviewerBuilder.BuildReviewer1(), ReviewerBuilder.BuildReviewer2());
+ }
+
+ [Test]
+ public void ReviewersThatHaveReviewedUniqueTitlesShouldNotBeSimilar()
+ {
+ var r1 = ReviewerBuilder.BuildReviewer1();
+ var r2 = ReviewerBuilder.BuildAReviewerThatReviewedSomethingUnique();
+ pearsonCorrelationScore = new PearsonCorrelation(r1, r2);
+ Assert.AreEqual(0, pearsonCorrelationScore.Score());
+ }
+
+ [Test]
+ public void ReviewersThatHaveTheSameTasteShouldHaveAPerfectScore()
+ {
+ var r1 = ReviewerBuilder.BuildReviewer1();
+ pearsonCorrelationScore = new PearsonCorrelation(r1, r1);
+ Assert.AreEqual(1.0, pearsonCorrelationScore.Score());
+ }
+
+ [Test]
+ public void TwoReviewersWithSomeSimilarReviewsShouldHaveAScoreBetweenZeroAndOne()
+ {
+ Assert.AreEqual(0.396, pearsonCorrelationScore.Score());
+ }
}
}
@@ -1,12 +1,12 @@
using System;
using System.Collections.Generic;
-using System.Linq;
-using System.Text;
+using Recommender.Common;
using Recommender.Reviews;
+using Recommender.Steps;
namespace Recommender
{
- class PearsonCorrelation : SimilarityScore
+ public class PearsonCorrelation : SimilarityScore
{
private readonly Reviewer R1;
private readonly Reviewer R2;
@@ -17,10 +17,43 @@ public PearsonCorrelation(Reviewer r1, Reviewer r2)
R1 = r1;
R2 = r2;
}
-
+
public double Score()
{
- return 0.0;
+ SimilarReviews = new FindSimilarReviews(R1.Reviews, R2.Reviews).Calculate();
+
+ if (DoReviewersHaveSimilarReviews())
+ {
+ return 0.0;
+ }
+
+ var n = SimilarReviews.Count;
+
+ var sumR1 = new SumScores(SimilarReviews, R1.Reviews).Calculate();
+ var sumR2 = new SumScores(SimilarReviews, R2.Reviews).Calculate();
+
+
+ var sumR1Sq = new SumSquares(SimilarReviews, R1.Reviews).Calculate();
+ var sumR2Sq = new SumSquares(SimilarReviews, R2.Reviews).Calculate();
+
+ var pSum = new SumProducts(SimilarReviews, R1.Reviews, R2.Reviews).Calculate();
+
+ var num = pSum - (sumR1 * sumR2 / n);
+
+ var den = Math.Sqrt((sumR1Sq - Math.Pow(sumR1, 2) / n) * (sumR2Sq - Math.Pow(sumR2, 2) / n));
+
+ if (den == 0.0)
+ {
+ return 0.0;
+ }
+
+ var answer = num / den;
+ return Math.Round(answer, 3);
+ }
+
+ private bool DoReviewersHaveSimilarReviews()
+ {
+ return SimilarReviews.Count == 0;
}
}
}

0 comments on commit 34aefb2

Please sign in to comment.