package cn.netkiller.mahout;
import java.io.File;
import java.util.List;
import org.apache.mahout.cf.taste.impl.model.file.FileDataModel;
import org.apache.mahout.cf.taste.impl.neighborhood.NearestNUserNeighborhood;
import org.apache.mahout.cf.taste.impl.recommender.GenericUserBasedRecommender;
import org.apache.mahout.cf.taste.impl.similarity.PearsonCorrelationSimilarity;
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;
public class App {
public App() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
// 從檔案加載數據
DataModel model = new FileDataModel(new File("target/classes/test.csv"));
// 指定用戶相似度計算方法,這裡採用皮爾森相關度
UserSimilarity similarity = new PearsonCorrelationSimilarity(model);
// 指定用戶鄰居數量,這裡為2
UserNeighborhood neighborhood = new NearestNUserNeighborhood(2, similarity, model);
// 構建基于用戶的推薦系統
Recommender recommender = new GenericUserBasedRecommender(model, neighborhood, similarity);
// 得到指定用戶的推薦結果,這裡是得到用戶1的兩個推薦
List<RecommendedItem> recommendations = recommender.recommend(1, 2);
// 打印推薦結果
for (RecommendedItem recommendation : recommendations) {
System.out.println(recommendation);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
1,101,5.0
1,102,3.0
1,103,2.5
2,101,2.0
2,102,2.5
2,103,5.0
2,104,2.0
3,101,2.5
3,104,4.0
3,105,4.5
3,107,5.0
4,101,5.0
4,103,3.0
4,104,4.5
4,106,4.0
5,101,4.0
5,102,3.0
5,103,2.0
5,104,4.0
5,105,3.5
5,106,4.0