协同过滤算法是一种推荐算法,用于根据用户的历史行为和其他用户的行为,预测用户对特定项目的兴趣程度。下面是一个简单的Java实现示例:
int[][] ratings = {
{5, 3, 0, 1},
{4, 0, 0, 1},
{1, 1, 0, 5},
{1, 0, 0, 4},
{0, 1, 5, 4},
{5, 0, 0, 0}
};
double getEuclideanDistance(int[] userA, int[] userB) {
double sum = 0.0;
for (int i = 0; i < userA.length; i++) {
if (userA[i] != 0 && userB[i] != 0) {
sum += Math.pow(userA[i] - userB[i], 2);
}
}
return Math.sqrt(sum);
}
int findMostSimilarUser(int[] user, int[][] ratings) {
int mostSimilarUser = -1;
double minDistance = Double.MAX_VALUE;
for (int i = 0; i < ratings.length; i++) {
if (i != user && ratings[i] != user) {
double distance = getEuclideanDistance(user, ratings[i]);
if (distance < minDistance) {
minDistance = distance;
mostSimilarUser = i;
}
}
}
return mostSimilarUser;
}
double predictRating(int user, int item, int[][] ratings) {
int mostSimilarUser = findMostSimilarUser(user, ratings);
double sum = 0.0;
int count = 0;
for (int i = 0; i < ratings[mostSimilarUser].length; i++) {
if (ratings[mostSimilarUser][i] != 0 && ratings[user][i] != 0 && i != item) {
sum += ratings[mostSimilarUser][i];
count++;
}
}
double averageRating = sum / count;
return averageRating;
}
以上是一个简单的协同过滤算法的Java实现示例。实际应用中,还可以使用更复杂的相似度度量方法、考虑评分偏差等因素来提高推荐的准确性。