gpt4 book ai didi

c# - 如何用这种方法计算几本书的接近度?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:09:47 25 4
gpt4 key购买 nike

您是否见过 Netflix 如何根据您以前看过并喜欢看的电影向您推荐某些电影?除了一套书,我正在尝试做同样的事情。

我有 53 本书和 32 个用户。 32 位用户对每本书的评分从 5 到 -5,其中 5 是我喜欢它。用于计算两本书相互比较“相似”程度的公式如下:

Similarity function

x1*y1 表示用户 1 对书 x 和书 y 的评分,x2*y2 表示第 2 个用户对相同 2 本书的评分,对所有用户继续。

传入此方法的数组是主数组。主数组的每个元素对应一个用户,用户数组中的每个元素对应一本书。 (32个用户数组,每个用户数组本身就是一个53元素的数组)

保存每个用户评分的数组是有序的,compValuehold[0][0] 代表第一个用户对第一本书的评分,compValuehold[0][2] 表示第一个用户对第二本书的评分等

 public static void DisplayRatings(double[][] compValuehold)
{

double eachUserProduct = 0;
double denominatorXSum = 0;
double denominatorYSum = 0;
double Score = 0;
int counterForScore = 0;
double[] calculatedValues = new double[52];



//this for loop should calculate each book's ratings and store it
//in an array
for (int i = 0; i < 52; i++)
{

for (int j = 0; j < 32; j++)
{
eachUserProduct += compValuehold[j][i] * compValuehold[j][i + 1];
denominatorXSum += compValuehold[j][i] * compValuehold[j][i];
denominatorYSum += compValuehold[j][i + 1] * compValuehold[j][i + 1];

}

denominatorXSum = Math.Sqrt(denominatorXSum);
denominatorYSum = Math.Sqrt(denominatorYSum);
Score = eachUserProduct / (denominatorXSum * denominatorYSum);
calculatedValues[counterForScore] = Score;
counterForScore += 1;
denominatorXSum = 0;
denominatorYSum = 0;
eachUserProduct = 0;

}

}

我能够编写代码将第一本书与其余书籍进行比较。 我的问题是我需要为每本书找出哪本书最相似。这意味着要多次计算该公式。我不知道如何对所有书籍执行此操作。

最佳答案

看起来你正在做的是确定 Cosine Similarity “书籍向量”的集合,其中每个向量由每个用户对特定书籍的评分组成。

尝试在一个函数中完成所有这些可能会让您在调试时头疼;我建议将您的问题分解成更易于管理的部分:

  • 编写一个函数,为特定书籍创建书籍向量。
    • 在您的情况下,这将从您的 compValuehold 矩阵中提取给定列
  • 编写一个函数来计算两本书向量之间的相似度。
  • 遍历所有成对的书籍,计算每对的相似度。
    • (注意 similarity(a, b) == similarity(b, a))

如果您在某处想出更好的比较书籍的方法,这种方法还可以更轻松地更改相似度函数。

这是前两个子问题的示例实现(请记住,它们不是特别有效):

static int[] GetBookVector(int[][] ratingMatrix, int bookIndex)
{
int[] book = new int[ratingMatrix.Length];
for (int i = 0; i < ratingMatrix.Length; i++)
{
book[i] = ratingMatrix[i][bookIndex];
}

return book;
}

static double Similarity(int[] v1, int[] v2)
{
if (v1.Length != v2.Length)
{
throw new ArgumentException("Vectors must be of the same length.");
}

int numerator = 0;
double v1Norm = 0;
double v2Norm = 0;
for (int i = 0; i < v1.Length; i++)
{
numerator += v1[i] * v2[i];
v1Norm += v1[i] * v1[i];
v2Norm += v2[i] * v2[i];
}

v1Norm = Math.Sqrt(v1Norm);
v2Norm = Math.Sqrt(v2Norm);

return (numerator / (v1Norm * v2Norm));
}

关于c# - 如何用这种方法计算几本书的接近度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15671394/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com