对于没有偏好值的数据,或者偏好值为喜欢、不喜欢的情况下,我们可以使用布尔推荐,数据模型如右图。
package recommender;
import java.util.List;
import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.common.FastByIDMap;
import org.apache.mahout.cf.taste.impl.common.FastIDSet;
import org.apache.mahout.cf.taste.impl.common.LongPrimitiveIterator;
import org.apache.mahout.cf.taste.impl.model.GenericBooleanPrefDataModel;
import org.apache.mahout.cf.taste.impl.neighborhood.NearestNUserNeighborhood;
import org.apache.mahout.cf.taste.impl.recommender.GenericBooleanPrefUserBasedRecommender;
import org.apache.mahout.cf.taste.impl.similarity.LogLikelihoodSimilarity;
import org.apache.mahout.cf.taste.model.DataModel;
import org.apache.mahout.cf.taste.neighborhood.UserNeighborhood;
import org.apache.mahout.cf.taste.recommender.RecommendedItem;
import org.apache.mahout.cf.taste.recommender.Recommender;
import org.apache.mahout.cf.taste.similarity.UserSimilarity;
/**
* 无偏好值推荐(布尔推荐)
* @progect Mahout_0.12.2
* @file BoolRemmender.java
* @author holif
* @date 2017年1月8日
*/
public class BoolRemmender {
public static void main(String[] args) throws TasteException {
//用户与物品关系数组 5个用户与7本书之间的对应关系 用1表示喜欢 0行与0列均不参与计算
long predata[][] = {{},{0,1,1,1,0,0,0,0},{0,1,0,1,1,0,0,1},
{0,1,1,1,1,1,0,1},{0,0,1,1,0,0,1,1},
{0,1,0,1,0,1,1,1}};
//创建用于存储用户与物品列表的映射
FastByIDMap<FastIDSet> preferences = new FastByIDMap<FastIDSet>();
for (int usid =1;usid<=5;usid++) {
//存储该用户喜欢的书籍的bookid
FastIDSet set = new FastIDSet();
for (int bookid =1; bookid<=7;bookid++) {
if(predata[usid][bookid]==1){
set.add(bookid);
}
}
if (!set.isEmpty()) {
preferences.put(usid, set);
}
}
//创建Boolean数据模型
DataModel model = new GenericBooleanPrefDataModel(preferences);
//由于没有偏好值 所以使用基于对数似然比计算相似度
UserSimilarity similarity = new LogLikelihoodSimilarity(model);
UserNeighborhood neighborhood = new NearestNUserNeighborhood(10,similarity, model);
Recommender recommender = new GenericBooleanPrefUserBasedRecommender(
model, neighborhood, similarity);
LongPrimitiveIterator iter = model.getUserIDs();
while (iter.hasNext()) {
long usid = iter.nextLong();
List<RecommendedItem> list = recommender.recommend(usid, 5);
//只推荐用户未表达喜欢的书
//List<RecommendedItem> list = recommender.recommend(usid, 5, false);
System.out.print("usid[" + usid + "]");
for (RecommendedItem recommendedItem : list) {
System.out.print(recommendedItem);
}
System.out.println();
}
}
}
推荐评估见: 创建一个推荐程序