请使用java语言举一个推荐算法的代码例子
时间: 2024-05-05 09:18:11 浏览: 137
推荐算法java版
当然可以!以下是一个简单的基于协同过滤的推荐算法示例,使用Java语言:
```java
public class CollaborativeFiltering {
private double similarityThreshold;
public CollaborativeFiltering(double similarityThreshold) {
this.similarityThreshold = similarityThreshold;
}
public List<Integer> recommend(List<User> users, int targetUserId) {
User targetUser = null;
for (User user : users) {
if (user.getId() == targetUserId) {
targetUser = user;
break;
}
}
if (targetUser == null) {
throw new IllegalArgumentException("The target user does not exist.");
}
List<Integer> recommendedItems = new ArrayList<>();
for (User user : users) {
if (user != targetUser) {
double similarity = computeSimilarity(targetUser, user);
if (similarity > similarityThreshold) {
for (Integer item : user.getRatedItems()) {
if (!targetUser.getRatedItems().contains(item)) {
recommendedItems.add(item);
}
}
}
}
}
return recommendedItems;
}
private double computeSimilarity(User user1, User user2) {
double sumOfProducts = 0.0;
double sumSquaredUser1 = 0.0;
double sumSquaredUser2 = 0.0;
Map<Integer, Double> ratingMapUser1 = user1.getRatingMap();
Map<Integer, Double> ratingMapUser2 = user2.getRatingMap();
for (Integer itemId : ratingMapUser1.keySet()) {
if (ratingMapUser2.containsKey(itemId)) {
double rating1 = ratingMapUser1.get(itemId);
double rating2 = ratingMapUser2.get(itemId);
sumOfProducts += rating1 * rating2;
}
}
for (Double rating : ratingMapUser1.values()) {
sumSquaredUser1 += Math.pow(rating, 2);
}
for (Double rating : ratingMapUser2.values()) {
sumSquaredUser2 += Math.pow(rating, 2);
}
double denominator = Math.sqrt(sumSquaredUser1) * Math.sqrt(sumSquaredUser2);
return (denominator == 0) ? 0 : sumOfProducts / denominator;
}
}
class User {
private int id;
private Map<Integer, Double> ratingMap;
public User(int id) {
this.id = id;
this.ratingMap = new HashMap<>();
}
public User(int id, Map<Integer, Double> ratingMap) {
this.id = id;
this.ratingMap = ratingMap;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Map<Integer, Double> getRatingMap() {
return ratingMap;
}
public void setRatingMap(Map<Integer, Double> ratingMap) {
this.ratingMap = ratingMap;
}
public void addRating(int itemId, double rating) {
ratingMap.put(itemId, rating);
}
public List<Integer> getRatedItems() {
return new ArrayList<>(ratingMap.keySet());
}
}
```
这是一个基于协同过滤的推荐算法,它在整个数据集中搜索与目标用户的评级相似的用户,并推荐目标用户没有评级的项目。该算法使用相似性阈值来过滤出相似用户。
阅读全文