ALS算法做协同过滤大致就是建立用户商品矩阵,根据评分值以解数独的形式解出来
import java.text.SimpleDateFormatimport java.util.Dateimport org.apache.spark.mllib.recommendation.{ALS, Rating }import org.apache.spark.{SparkContext, SparkConf}/** * Created by hadoop on 2015/7/20. */object MLlibCF { def main(args: Array[String]) { val time = new SimpleDateFormat("MMddHHmm").format(new Date()) val sparkConf = new SparkConf().setAppName("MLlibCF-"+time) sparkConf.set("mapreduce.framework.name", "yarn") sparkConf.set("spark.rdd.compress", "true")//是否需要压缩序列化的rdd分区,牺牲cpu时间提高空间利用率 sparkConf.set("spark.serializer","org.apache.spark.serializer.KryoSerializer")//配置序列化的接口 sparkConf.set("spark.storage.memoryFraction", "0.2") sparkConf.set("spark.scheduler.mode", "FAIR") sparkConf.set("spark.ui.port", "4042") sparkConf.set("spark.akka.frameSize", "100") val sc = new SparkContext(sparkConf) val data = sc.textFile("hdfs://namenode:9000/data/test_in/mahout1.txt", 1) //对读取的文件进行预处理,并放入Rating容器中 val ratings = data.map(_.split(",") match{ case(Array(user, product, rate)) => Rating(user.toInt, product.toInt, rate.toDouble) }) //需要求出的值 val user1 = sc.parallelize(List("1,105","1,106","2,105","2,107","3,102")).map( _.split(",") match { case (Array(user, product)) => (user.toInt, product.toInt) }) val rank = 10 val numIterations = 20 //建立ALS模型 val model = ALS.train(ratings, rank, numIterations, 0.01) //读取需要的值 val predictions = model.predict(user1).map{ case Rating(user, product, rate) => ((user, product), rate) } predictions.saveAsTextFile("hdfs://10.207.0.217:9000/data/test_out/zk/MLlib-"+time) }}