我在餐馆之间使用adjusted cosine similarity开发item-based collaborative filter以产生推荐 . 我设置了一切并且运行良好,但是当我尝试模拟可能的测试场景时,我得到了一些有趣的结果 .
我将从我的测试数据开始 . 我有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, grab 这个并插入 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,-1)是不正确的 . 相反,在这种情况下使用不同的措施 . 例如,简单(非调整)余弦相似性将得到“1”,这是您可能期望的 .