mahout 推荐系统示例代码
建立java工程,导入需要的jar包
import java.io.*; import java.util.*; import org.apache.mahout.cf.taste.impl.model.file.*; import org.apache.mahout.cf.taste.impl.neighborhood.*; import org.apache.mahout.cf.taste.impl.recommender.*; import org.apache.mahout.cf.taste.impl.similarity.*; import org.apache.mahout.cf.taste.model.*; import org.apache.mahout.cf.taste.neighborhood.*; import org.apache.mahout.cf.taste.recommender.*; import org.apache.mahout.cf.taste.similarity.*; public class TestMahout { // private TestMahout(){}; public static void main(String args[]) throws Exception { // 1,构建模型 DataModel dataModel = new FileDataModel(new File("d://test.txt")); // 2,计算相似度 UserSimilarity userSimilarity = new PearsonCorrelationSimilarity(dataModel); // 3,查找k紧邻 UserNeighborhood userNeighborhood = new NearestNUserNeighborhood(2, userSimilarity, dataModel); // 4,构造推荐引擎 Recommender recommender = new GenericUserBasedRecommender(dataModel, userNeighborhood, userSimilarity); // 为用户i推荐两个Item for (int i = 1; i < 6; i++) { System.out.println("recommand for user:" + i); Listrecommendations = recommender.recommend(i, 2); for (RecommendedItem recommendation : recommendations) { System.out.println(recommendation); } } } }
运行结果:
recommand for user:1
RecommendedItem[item:104, value:4.257081]
RecommendedItem[item:106, value:4.0]
recommand for user:2
recommand for user:3
RecommendedItem[item:106, value:4.0]
RecommendedItem[item:103, value:2.5905366]
recommand for user:4
RecommendedItem[item:102, value:3.0]
recommand for user:5
本文由用户 jopen 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
转载本站原创文章,请注明出处,并保留原始链接、图片水印。
本站是一个以用户分享为主的开源技术平台,欢迎各类分享!