协同过滤算法 Java代码示例
时间: 2024-04-23 15:19:42 浏览: 145
协同过滤算法是一种常用的推荐算法,它通过分析用户的历史行为和与其他用户的相似度来进行推荐。下面是一个简单的协同过滤算法的Java代码示例:
```java
import java.util.*;
public class CollaborativeFiltering {
// 用户评分数据
private static int[][] ratings = {
{4, 5, 0, 2, 1},
{0, 2, 4, 0, 5},
{1, 0, 3, 4, 2},
{5, 1, 2, 0, 4},
{2, 4, 1, 5, 0}
};
// 计算用户之间的相似度
private static double similarity(int user1, int user2) {
double dotProduct = 0.0;
double norm1 = 0.0;
double norm2 = 0.0;
for (int i = 0; i < ratings[user1].length; i++) {
dotProduct += ratings[user1][i] * ratings[user2][i];
norm1 += Math.pow(ratings[user1][i], 2);
norm2 += Math.pow(ratings[user2][i], 2);
}
return dotProduct / (Math.sqrt(norm1) * Math.sqrt(norm2));
}
// 根据用户相似度进行推荐
private static List<Integer> recommend(int user) {
List<Integer> recommendations = new ArrayList<>();
double[] similarities = new double[ratings.length];
for (int i = 0; i < ratings.length; i++) {
if (i != user) {
similarities[i] = similarity(user, i);
}
}
for (int i = 0; i < ratings[user].length; i++) {
if (ratings[user][i] == 0) {
double weightedSum = 0.0;
double similaritySum = 0.0;
for (int j = 0; j < ratings.length; j++) {
if (j != user && ratings[j][i] != 0) {
weightedSum += ratings[j][i] * similarities[j];
similaritySum += similarities[j];
}
}
if (similaritySum != 0) {
double recommendation = weightedSum / similaritySum;
recommendations.add((int) Math.round(recommendation));
}
}
}
return recommendations;
}
public static void main(String[] args) {
int user = 0;
List<Integer> recommendations = recommend(user);
System.out.println("用户 " + user + " 的推荐结果:");
for (int recommendation : recommendations) {
System.out.println(recommendation);
}
}
}
```
这段代码实现了一个简单的协同过滤算法,其中包括计算用户之间的相似度和根据相似度进行推荐的功能。你可以根据自己的需求进行修改和扩展。
阅读全文