mahout 推薦系統示例代碼

jopen 11年前發布 | 63K 次閱讀 推薦引擎 Mahout

建立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

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!