协同过滤算法java实现
时间: 2023-11-18 19:07:32 浏览: 87
协同过滤算法是一种常见的推荐算法,其中最流行的是基于用户的协同过滤和基于物品的协同过滤。以下是一个简单的基于用户的协同过滤算法的Java实现:
```java
import java.util.*;
public class UserBasedCF {
// 用户数
private int userNum;
// 物品数
private int itemNum;
// 用户评分矩阵
private int[][] userItemMatrix;
// 相似度矩阵
private double[][] similarityMatrix;
// 构造函数
public UserBasedCF(int userNum, int itemNum, int[][] userItemMatrix) {
this.userNum = userNum;
this.itemNum = itemNum;
this.userItemMatrix = userItemMatrix;
similarityMatrix = new double[userNum][userNum];
}
// 计算用户相似度
public void computeSimilarity() {
for (int i = 0; i < userNum; i++) {
for (int j = i + 1; j < userNum; j++) {
double similarity = computeUserSimilarity(i, j);
similarityMatrix[i][j] = similarity;
similarityMatrix[j][i] = similarity;
}
}
}
// 计算用户之间的相似度
private double computeUserSimilarity(int user1, int user2) {
int commonNum = 0;
int sum1 = 0, sum2 = 0;
int sumSq1 = 0, sumSq2 = 0;
for (int i = 0; i < itemNum; i++) {
if (userItemMatrix[user1][i] > 0 && userItemMatrix[user2][i] > 0) {
commonNum++;
int rating1 = userItemMatrix[user1][i];
int rating2 = userItemMatrix[user2][i];
sum1 += rating1;
sum2 += rating2;
sumSq1 += rating1 * rating1;
sumSq2 += rating2 * rating2;
}
}
if (commonNum == 0) {
return 0;
}
double numerator = commonNum * (sum1 * sum2) - (sum1 * sum2);
double denominator = Math.sqrt((commonNum * sumSq1 - sum1 * sum1) * (commonNum * sumSq2 - sum2 * sum2));
if (denominator == 0) {
return 0;
}
return numerator / denominator;
}
// 预测用户对物品的评分
public double predictRating(int user, int item) {
double numerator = 0;
double denominator = 0;
for (int i = 0; i < userNum; i++) {
if (i != user && userItemMatrix[i][item] > 0) {
double similarity = similarityMatrix[user][i];
numerator += similarity * userItemMatrix[i][item];
denominator += similarity;
}
}
if (denominator == 0) {
return 0;
}
return numerator / denominator;
}
}
```
以上是一个简单的基于用户的协同过滤算法的Java实现。您可以根据您的需求进行修改和扩展。
阅读全文