mahout+eclipse推荐系统开发学习之helloworld

推荐入门--HelloWorld

    1·下载最新版本的mahout,本例使用0.9版本 下载地址 http://mirror.esocc.com/apache/mahout/0.9/
    2·新建一个普通的java项目,导入以下依赖包(所有依赖包都在mahout安装目录的lib文件夹下)
     mahout+eclipse推荐系统开发学习之helloworld_第1张图片
    3·新建以下java类:
package com.xinyuan.hello;

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.*;
import java.io.*;
import java.util.*;
public class RecommenderIntro {
	private RecommenderIntro(){};
	
	public static void main (String args[])throws Exception{
                // step:1 构建模型 2 计算相似度 3 查找k紧邻 4 构造推荐引擎
		DataModel  model =new FileDataModel(new File(System.getProperty("user.dir")+"/data/hello.txt"));//文件名一定要是绝对路径
		UserSimilarity similarity =new PearsonCorrelationSimilarity(model);
		UserNeighborhood neighborhood =new NearestNUserNeighborhood(2,similarity,model);
		Recommender recommender= new GenericUserBasedRecommender(model,neighborhood,similarity);
		List<RecommendedItem> recommendations =recommender.recommend(1, 2);//为用户1推荐两个ItemID
		for(RecommendedItem recommendation :recommendations){
			System.out.println(recommendation);
		}
		
	}
}
    4·在项目目录中添加数据文件hello.txt
1,101,5
1,102,3
1,103,2.5
2,101,2
2,102,2.5
2,103,5
2,104,2
3,101,2.5
3,104,4
3,105,4.5
3,107,5
4,101,5
4,103,3
4,104,4.5
4,106,4
5,101,4
5,102,3
5,103,2
5,104,4
5,105,3.5
5,106,4
    5·添加log4j的配置文件 log4j.properties
# Configure logging for testing: optionally with log file
log4j.rootLogger=WARN, stdout
# log4j.rootLogger=WARN, stdout, logfile

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n

log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=target/spring.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
执行结果:
mahout+eclipse推荐系统开发学习之helloworld_第2张图片

你可能感兴趣的:(Mahout,推荐系统)