基于java语言生成协同过滤算法
时间: 2024-05-01 15:05:02 浏览: 120
下面是一个基于Java语言的简单示例,实现了基于用户的协同过滤算法:
```java
import java.util.*;
public class UserBasedCF {
// 计算余弦相似度
private static double cosineSimilarity(double[] v1, double[] v2) {
double dotProduct = 0;
double norm1 = 0;
double norm2 = 0;
for (int i = 0; i < v1.length; i++) {
dotProduct += v1[i] * v2[i];
norm1 += v1[i] * v1[i];
norm2 += v2[i] * v2[i];
}
return dotProduct / (Math.sqrt(norm1) * Math.sqrt(norm2));
}
// 基于用户的协同过滤算法
public static List<Integer> userBasedCF(double[][] userItemMatrix, int targetUser, int K) {
List<Integer> recommendations = new ArrayList<>();
// 计算目标用户和其他用户的相似度
List<double[]> similarities = new ArrayList<>();
for (int userId = 0; userId < userItemMatrix.length; userId++) {
if (userId != targetUser) {
double similarity = cosineSimilarity(userItemMatrix[targetUser], userItemMatrix[userId]);
similarities.add(new double[]{userId, similarity});
}
}
// 按相似度从高到低排序,选择前K个最相似的用户
similarities.sort((a, b) -> Double.compare(b[1], a[1]));
List<double[]> neighbors = similarities.subList(0, K);
// 获取邻居用户喜欢的物品列表
Set<Integer> items = new HashSet<>();
for (double[] neighbor : neighbors) {
int neighborId = (int) neighbor[0];
for (int itemId = 0; itemId < userItemMatrix[0].length; itemId++) {
if (userItemMatrix[neighborId][itemId] > 0) {
items.add(itemId);
}
}
}
// 计算推荐分数
Map<Integer, Double> scores = new HashMap<>();
for (int item : items) {
if (userItemMatrix[targetUser][item] == 0) {
double score = 0;
for (double[] neighbor : neighbors) {
int neighborId = (int) neighbor[0];
score += neighbor[1] * userItemMatrix[neighborId][item];
}
scores.put(item, score);
}
}
// 按推荐分数从高到低排序,并返回推荐结果
recommendations.addAll(scores.keySet());
recommendations.sort((a, b) -> Double.compare(scores.get(b), scores.get(a)));
return recommendations;
}
public static void main(String[] args) {
// 示例数据: 5个用户,4个物品
double[][] userItemMatrix = {
{5, 3, 0, 0},
{4, 0, 4, 1},
{1, 1, 0, 5},
{0, 0, 4, 4},
{0, 1, 5, 4}
};
// 对用户0进行推荐,选择最相似的2个用户
List<Integer> recommendations = userBasedCF(userItemMatrix, 0, 2);
System.out.println("Recommendations for user 0: " + recommendations);
}
}
```
在以上代码中,cosineSimilarity函数用于计算余弦相似度,userBasedCF函数实现了基于用户的协同过滤算法。其中,targetUser表示目标用户的编号,K表示选择最相似的K个用户。函数返回推荐结果,包含物品编号。
阅读全文