Github user mengxr commented on a diff in the pull request: https://github.com/apache/spark/pull/3098#discussion_r27707356 --- Diff: examples/src/main/scala/org/apache/spark/examples/mllib/MovieLensALS.scala --- @@ -167,23 +169,66 @@ object MovieLensALS { .setProductBlocks(params.numProductBlocks) .run(training) - val rmse = computeRmse(model, test, params.implicitPrefs) - - println(s"Test RMSE = $rmse.") + params.metrics match { + case "rmse" => + val rmse = computeRmse(model, test, params.implicitPrefs) + println(s"Test RMSE = $rmse") + case "map" => + val (map, users) = computeRankingMetrics(model, training, test, numMovies.toInt) + println(s"Test users $users MAP $map") + case _ => println(s"Metrics not defined, options are rmse/map") + } sc.stop() } /** Compute RMSE (Root Mean Squared Error). */ - def computeRmse(model: MatrixFactorizationModel, data: RDD[Rating], implicitPrefs: Boolean) - : Double = { - - def mapPredictedRating(r: Double) = if (implicitPrefs) math.max(math.min(r, 1.0), 0.0) else r - + def computeRmse( + model: MatrixFactorizationModel, + data: RDD[Rating], + implicitPrefs: Boolean) : Double = { val predictions: RDD[Rating] = model.predict(data.map(x => (x.user, x.product))) - val predictionsAndRatings = predictions.map{ x => - ((x.user, x.product), mapPredictedRating(x.rating)) + val predictionsAndRatings = predictions.map { x => + ((x.user, x.product), mapPredictedRating(x.rating, implicitPrefs)) }.join(data.map(x => ((x.user, x.product), x.rating))).values math.sqrt(predictionsAndRatings.map(x => (x._1 - x._2) * (x._1 - x._2)).mean()) } + + def mapPredictedRating(r: Double, implicitPrefs: Boolean) = { + if (implicitPrefs) math.max(math.min(r, 1.0), 0.0) else r + } + + /** Compute MAP (Mean Average Precision) statistics for top N product Recommendation */ + def computeRankingMetrics( + model: MatrixFactorizationModel, + train: RDD[Rating], + test: RDD[Rating], + n: Int) : (Double, Long) = { + val ord = Ordering.by[(Int, Double), Double](x => x._2) + + val testUserLabels = test.map { --- End diff -- Please use the topByKey implementation to compute top items for users: https://github.com/apache/spark/blob/master/mllib/src/main/scala/org/apache/spark/mllib/rdd/MLPairRDDFunctions.scala
--- If your project is set up for it, you can reply to this email and have your reply appear on GitHub as well. If your project does not have this feature enabled and wishes so, or if the feature is enabled but not working, please contact infrastructure at infrastruct...@apache.org or file a JIRA ticket with INFRA. --- --------------------------------------------------------------------- To unsubscribe, e-mail: reviews-unsubscr...@spark.apache.org For additional commands, e-mail: reviews-h...@spark.apache.org