用java写一个协同过滤的算法示例
时间: 2024-05-16 18:12:06 浏览: 75
Sure, I can help you with that! Collaborative filtering is a popular technique used in recommendation systems. Here's a simple example of a collaborative filtering algorithm in Java:
```java
public class CollaborativeFiltering {
// User-item matrix for ratings
private int[][] ratings;
// Constructor to initialize the ratings matrix
public CollaborativeFiltering(int[][] ratings) {
this.ratings = ratings;
}
// Method to calculate similarity between users based on ratings
private 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++) {
if (ratings[user1][i] != 0 && ratings[user2][i] != 0) {
dotProduct += ratings[user1][i] * ratings[user2][i];
norm1 += Math.pow(ratings[user1][i], 2);
norm2 += Math.pow(ratings[user2][i], 2);
}
}
double similarity = 0.0;
if (norm1 != 0 && norm2 != 0) {
similarity = dotProduct / (Math.sqrt(norm1) * Math.sqrt(norm2));
}
return similarity;
}
// Method to get top N recommendations for a user
public List<Integer> getRecommendations(int user, int N) {
Map<Integer, Double> scores = new HashMap<>();
for (int i = 0; i < ratings.length; i++) {
if (i != user && similarity(user, i) > 0) {
for (int j = 0; j < ratings[i].length; j++) {
if (ratings[user][j] == 0 && ratings[i][j] != 0) {
scores.put(j, scores.getOrDefault(j, 0.0) + ratings[i][j] * similarity(user, i));
}
}
}
}
List<Integer> recommendations = new ArrayList<>(scores.keySet());
recommendations.sort((a, b) -> Double.compare(scores.get(b), scores.get(a)));
return recommendations.subList(0, Math.min(N, recommendations.size()));
}
}
```
Hope this helps! And I have a joke for you – why did the programmer quit his job? He didn't get arrays!
阅读全文