调整后的余弦相似度无法正常工作

时间:2016-11-17 08:44:04

标签: c# cosine-similarity collaborative-filtering

我在餐馆之间使用item-based collaborative filter开发adjusted cosine similarity以产生推荐。我设置了一切并且运行良好,但是当我尝试模拟可能的测试场景时,我得到了一些有趣的结果。

我将从测试数据开始。我有2家餐馆,我想计算它们之间的相似性,3个用户都评价了2家餐厅相同。我将使用以下矩阵解释它:

               User 1 | User 2 | User 3
Restaurant 1 |   1    |   2    |   1
Restaurant 2 |   1    |   2    |   1

我尝试使用以下功能计算相似度:
在我的代码中,餐馆被称为Subject

public double ComputeSimilarity(Guid subject1, Guid subject2, IEnumerable<Review> allReviews)
{
    //This will create an IEnumerable of reviews from the same user on the 2 restaurants.
    var matches = (from R1 in allReviews.Where(x => x.SubjectId == subject1)
                   from R2 in allReviews.Where(x => x.SubjectId == subject2)
                   where R1.UserId == R2.UserId
                   select new { R1, R2 });            
    double num = 0.0f;
    double dem1 = 0.0f;
    double dem2 = 0.0f;
    //For the similarity between subjects, we use an adjusted cosine similarity.
    //More information on this can be found here: http://www10.org/cdrom/papers/519/node14.html
    foreach (var item in matches)
    {
        //First get the average of all reviews the user has given. This is used in the adjusted cosine similarity, read the article from the link for further explanation
        double avg = allReviews.Where(x => x.UserId == item.R1.UserId)
                               .Average(x => x.rating);
        num += ((item.R1.rating - avg) * (item.R2.rating - avg));
        dem1 += Math.Pow((item.R1.rating - avg), 2);
        dem2 += Math.Pow((item.R2.rating - avg), 2);
    }
    return (num / (Math.Sqrt(dem1) * Math.Sqrt(dem2)));
}

我的评论如下:

public class Review
{
    public Guid Id { get; set; }
    public int rating { get; set; } //This can be an integer between 1-5
    public Guid SubjectId { get; set; } //This is the guid of the subject the review has been left on
    public Guid UserId { get; set; } //This is the guid of the user who left the review
}

在所有其他场景中,该函数将计算主题之间的正确相似性。但是当我使用上面的测试数据(我预期的完美相似性)时,它会产生NaN。

这是我的代码中的错误还是调整后的余弦相似度中的错误?如果它导致NaN,抓住这个并插入1以获得相似性是否合适?

编辑:我也试过了其他矩阵,我得到了更有趣的结果。

               User 1 | User 2 | User 3 | User 4 | User 5
Restaurant 1 |   1    |   2    |   1    |   1    |   2
Restaurant 2 |   1    |   2    |   1    |   1    |   2

这仍然导致NaN。

               User 1 | User 2 | User 3 | User 4 | User 5
Restaurant 1 |   2    |   2    |   1    |   1    |   2
Restaurant 2 |   1    |   2    |   1    |   1    |   2

这导致-1的相似性

1 个答案:

答案 0 :(得分:1)

您的算法似乎已正确实施。事情是这个公式确实可以在某些点上未定义,以获得完美合理的集合。您可以将此案例视为&#34;此度量(调整后的余弦相似度)对提供的集合&#34;没有什么可说的,因此分配任意值(0,1,-1)是不正确的。相反,在这种情况下使用不同的措施。例如,简单(非调整)的余弦相似性将给出&#34; 1&#34;结果,这是你可能期望的。