Libimseti上的匿名用户推荐系统

时间:2022-06-09 17:53:34
<span style="font-size:18px;">/***
* @author YangXin
* @date 2016/2/19
* @info Libimseti上的匿名用户推荐系统
*/
package unitFive;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.model.GenericUserPreferenceArray;
import org.apache.mahout.cf.taste.impl.model.PlusAnonymousUserDataModel;
import org.apache.mahout.cf.taste.impl.model.file.FileDataModel;
import org.apache.mahout.cf.taste.model.DataModel;
import org.apache.mahout.cf.taste.model.PreferenceArray;
import org.apache.mahout.cf.taste.recommender.RecommendedItem;

public class LibimsetiWithAnonymousRecommender extends LibimsetiRecommender {
private final PlusAnonymousUserDataModel plusAnonymousModel;

//注这里的readResouceToTempFile待实现
public LibimsetiWithAnonymousRecommender() throws TasteException, IOException{
this(new FileDataModel(readResourceToTempFile("E:\\mahout项目\\examples\\ratings.dat")));
}

/***
* 此方法封装了如何将资源转换为加载的文件,此处未实现
* @param string
* @return
*/
private static File readResourceToTempFile(String string) {
// TODO Auto-generated method stub
return null;
}

public LibimsetiWithAnonymousRecommender(DataModel model) throws TasteException, IOException{
super(new PlusAnonymousUserDataModel(model));
plusAnonymousModel = (PlusAnonymousUserDataModel)getDataModel();
}

public synchronized List<RecommendedItem> recommend(PreferenceArray anonymouseUserPrefs, int howMany) throws TasteException{
plusAnonymousModel.setTempPrefs(anonymouseUserPrefs);
List<RecommendedItem> recommendations = recommend(PlusAnonymousUserDataModel.TEMP_USER_ID, howMany, null);
plusAnonymousModel.clearTempPrefs();
return recommendations;
}


public static void main(String[] args) throws Exception{
PreferenceArray anonymousPrefs = new GenericUserPreferenceArray(3);
anonymousPrefs.setUserID(0, PlusAnonymousUserDataModel.TEMP_USER_ID);
anonymousPrefs.setItemID(0, 123L);
anonymousPrefs.setValue(0, 1.0f);
anonymousPrefs.setItemID(1, 123L);
anonymousPrefs.setValue(1, 3.0f);
anonymousPrefs.setItemID(2, 123L);
anonymousPrefs.setValue(2, 2.0f);
LibimsetiWithAnonymousRecommender recommender = new LibimsetiWithAnonymousRecommender();
List<RecommendedItem> recommendations = recommender.recommend(anonymousPrefs, 10);
System.out.println(recommendations);
}
}
</span>