協同過濾算法是一種推薦算法,用于根據用戶的歷史行為和其他用戶的行為,預測用戶對特定項目的興趣程度。下面是一個簡單的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實現示例。實際應用中,還可以使用更復雜的相似度度量方法、考慮評分偏差等因素來提高推薦的準確性。