mahout 推荐系统示例代码

jopen 6年前

建立java工程,导入需要的jar包

 mahout 推荐系统示例代码

 

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);              List recommendations = 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