【发布时间】:2019-11-11 01:01:01
【问题描述】:
我一直在使用数据集 Movielens(2000 万条记录),并且一直在 Spark MLlib 中使用 collaborative filtering。
我的环境是 VirtualBox 上的 Ubuntu 14.4。我有一个主节点和两个从节点。我使用了已发布的 Apache Hadoop、Apache Spark、Scala、sbt。代码是用 Scala 编写的。
如何将代码和数据集分发到工作节点上?
import java.lang.Math._
import org.apache.spark.ml.recommendation.ALS
import org.apache.spark.ml.recommendation.ALS.Rating
import org.apache.spark.sql.SQLContext
import org.apache.spark.{SparkConf, SparkContext}
object trainModel extends App {
val conf = new SparkConf()
.setMaster("local[*]")
.setAppName("trainModel")
val sc = new SparkContext(conf)
val rawData = sc.textFile("file:///usr/local/spark/dataset/rating.csv")
val sqlContext = new SQLContext(sc)
val df = sqlContext
.read
.option("header", "true")
.format("csv")
.load("file:///usr/local/spark/dataset/rating.csv")
val ratings = rawData.map(line => line.split(",").take(3) match {
case Array(userId, movieId, rating) =>
Rating(userId.toInt, movieId.toInt, rating.toFloat)
})
println(s"Number of Ratings in Movie file ${ratings.count()} \n")
val ratingsRDD = sc.textFile("file:///usr/local/spark/dataset/rating.csv")
//split data into test&train
val splits = ratingsRDD.randomSplit(Array(0.8, 0.2), seed = 12345)
val trainingRatingsRDD = splits(0).cache()
val testRatingsRDD = splits(1).cache()
val numTraining = trainingRatingsRDD.count()
val numTest = testRatingsRDD.count()
println(s"Training: $numTraining, test: $numTest.")
val rank = 10
val lambdas = 0.01
val numIterations = 10
val model = ALS.train(ratings, rank, numIterations)
//Evaluate the model on training data
val userProducts = ratings.map { case Rating(userId, movieId, rating) =>
(userId, movieId)
}
val predictions = model.predict(userProducts).map { case
Rating(userId, movieId, rating) =>
((userId, movieId), rating)
}
val ratesAndPreds = ratings.map { case Rating(userId, movieId, rating) =>
((userId, movieId),
rating)
}.join(predictions)
val meanSquaredError = ratesAndPreds.map { case ((userId, movieId),
(r1, r2)) =>
val err = r1 - r2
err * err
}.mean
println("Mean Squared Error= " + meanSquaredError)
sqrt(meanSquaredError)
val rmse = math.sqrt(meanSquaredError)
println(s" RMSE = $rmse.")
}
【问题讨论】:
标签: scala apache-spark apache-spark-sql apache-spark-mllib