协同过滤算法代码实现java
时间: 2023-10-14 07:25:17 浏览: 124
协同过滤算法是一种推荐算法,可以根据用户历史行为数据,向用户推荐可能感兴趣的物品。以下是一个简单的基于用户的协同过滤算法的 Java 实现示例:
```java
public class CollaborativeFiltering {
// 用户评分矩阵,rows 表示用户,columns 表示物品
private double[][] ratings;
// 相似度阈值
private static final double SIMILARITY_THRESHOLD = 0.5;
public CollaborativeFiltering(double[][] ratings) {
this.ratings = ratings;
}
// 计算用户之间的相似度
private double similarity(int user1, int user2) {
double sum1 = 0, sum2 = 0, sum3 = 0;
for (int i = 0; i < ratings[user1].length; i++) {
if (ratings[user1][i] != 0 && ratings[user2][i] != 0) {
double r1 = ratings[user1][i], r2 = ratings[user2][i];
sum1 += r1 * r2;
sum2 += r1 * r1;
sum3 += r2 * r2;
}
}
double denominator = Math.sqrt(sum2) * Math.sqrt(sum3);
return denominator == 0 ? 0 : sum1 / denominator;
}
// 获取和指定用户最相似的 k 个用户
private List<Integer> getMostSimilarUsers(int user, int k) {
Map<Integer, Double> similarities = new HashMap<>();
for (int i = 0; i < ratings.length; i++) {
if (i != user) {
double similarity = similarity(user, i);
if (similarity > SIMILARITY_THRESHOLD) {
similarities.put(i, similarity);
}
}
}
return similarities.entrySet().stream()
.sorted(Map.Entry.<Integer, Double>comparingByValue().reversed())
.limit(k)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
}
// 推荐物品给指定用户
public List<Integer> recommend(int user, int k) {
List<Integer> mostSimilarUsers = getMostSimilarUsers(user, k);
Map<Integer, Double> scores = new HashMap<>();
for (int i = 0; i < ratings[user].length; i++) {
if (ratings[user][i] == 0) {
double numerator = 0, denominator = 0;
for (int j : mostSimilarUsers) {
if (ratings[j][i] != 0) {
double similarity = similarity(user, j);
numerator += similarity * ratings[j][i];
denominator += similarity;
}
}
double score = denominator == 0 ? 0 : numerator / denominator;
scores.put(i, score);
}
}
return scores.entrySet().stream()
.sorted(Map.Entry.<Integer, Double>comparingByValue().reversed())
.map(Map.Entry::getKey)
.collect(Collectors.toList());
}
}
```
使用示例:
```java
double[][] ratings = new double[][]{
{5, 3, 0, 1},
{4, 0, 0, 1},
{1, 1, 0, 5},
{0, 0, 4, 4},
{0, 1, 5, 4},
};
CollaborativeFiltering cf = new CollaborativeFiltering(ratings);
List<Integer> recommendations = cf.recommend(0, 2);
System.out.println(recommendations); // [2]
```
以上示例实现了基于用户的协同过滤算法,给出了用户 0 可能感兴趣的物品推荐列表。
阅读全文