mahout入门之编写第一个基于用户的推荐程序

首先创建一个java工程,导入必要的jar包,工程结构类似下图:


mahout入门之编写第一个基于用户的推荐程序_第1张图片

intro.txt测试数据如下:

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

每一行三列分别是:用户ID,物品ID,偏好值。

MyFirstRecommender代码如下:

package com.besttone.mahout.demo.recommender;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.mahout.cf.taste.common.TasteException;
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 MyFirstRecommender {

	/**
	 * @param args
	 * @throws IOException
	 * @throws TasteException
	 */
	public static void main(String[] args) throws IOException, TasteException {
		// TODO Auto-generated method stub
		// 装载数据文件,实现存储,并为计算提供所需的用户ID,物品ID,偏好值
		DataModel dataModel = new FileDataModel(new File(
				MyFirstRecommender.class.getResource("intro.txt").getPath()));
		// 相似度 度量方式,采用皮尔逊相关系数度量,也可以采用其他度量方式
		UserSimilarity similarity = new PearsonCorrelationSimilarity(dataModel);

		// 用户邻居,与给定用户最相似的一组用户
		UserNeighborhood neighborhood = new NearestNUserNeighborhood(2,
				similarity, dataModel);
		// 输出与userid=1最相似的两个userid
		// long[] neighborhoods = neighborhood.getUserNeighborhood(1);
		// for (long l : neighborhoods) {
		// System.out.println(l);
		// }
		// 推荐引擎,合并这些组件,实现推荐
		Recommender recommender = new GenericUserBasedRecommender(dataModel,
				neighborhood, similarity);

		// 为userID为1的用户推荐2个item
		List<RecommendedItem> items = recommender.recommend(1, 2);
		// 输出推荐的物品
		for (RecommendedItem recommendedItem : items) {
			System.out.println(recommendedItem);

		}


	}

}


你可能感兴趣的:(mahout入门之编写第一个基于用户的推荐程序)