mahout協同過濾,連資料庫資料,實現推薦
阿新 • • 發佈:2019-01-25
根據使用者協同過濾,根據使用者的相似度,推薦相應的item。
pom.xml加入核心的幾個依賴
<!-- https://mvnrepository.com/artifact/org.apache.mahout/mahout-core --> <dependency> <groupId>org.apache.mahout</groupId> <artifactId>mahout-core</artifactId> <version>0.9</version> </dependency> <dependency> <groupId>org.apache.mahout</groupId> <artifactId>mahout-integration</artifactId> <version>0.9</version> </dependency> <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-simple --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.7.25</version> </dependency>
java程式碼:
/** * * @param userId 使用者id * @param n 返回推薦條數 * @return 陣列,kl_id * @throws TasteException * @throws ClassNotFoundException */ public int[] recommendByUser(Integer userId, int n) throws TasteException, ClassNotFoundException { Class.forName("com.mysql.jdbc.Driver"); MysqlDataSource dataSource = new MysqlDataSource(); dataSource.setServerName("");//本地為localhost dataSource.setUser("root"); dataSource.setPassword("mysql"); dataSource.setDatabaseName("knowledgeManagement");//資料庫名 /* preferenceTable:表名 userIDColumn:userId的欄位名 itemIDColumn:itemId的欄位名 preferenceColumn:偏好值欄位名 timestampColumn:時間記錄欄位//可為空 */ JDBCDataModel dataModel = new MySQLJDBCDataModel(dataSource , "kl_rating_comment" , "user_id" , "kl_id","kl_rating","kl_comment_time"); //獲取模型 DataModel model = dataModel; //計算相似度 UserSimilarity similarity = new PearsonCorrelationSimilarity(model); //計算閾值,選擇鄰近的2個使用者 UserNeighborhood neighborhood = new NearestNUserNeighborhood(2 ,similarity,model); //推薦集合 Recommender recommender = new GenericUserBasedRecommender(model,neighborhood,similarity); //推薦數量 為n的一個合集,這裡數量可以修改 List<RecommendedItem> recommendedItems = recommender.recommend(userId,n); int kl_idArray[] = new int[recommendedItems.size()]; for (int i=0;i<recommendedItems.size();i++){ kl_idArray[i] = (int) recommendedItems.get(i).getItemID(); } //下面是測試用的程式碼 for (RecommendedItem recommendation : recommendedItems) { System.out.println(recommendation); } System.out.println("-------------"); for (int i= 0;i<kl_idArray.length;i++){ System.out.println(kl_idArray[i]); } return kl_idArray; }