-
Notifications
You must be signed in to change notification settings - Fork 28.9k
[SPARK-14409][ML] Adding a RankingEvaluator to ML #12461
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
bd324cd
[SPARK-14409][ML][WIP] Adding a RankingEvaluator to ML
yongtang 05580e0
[SPARK-14409][ML][WIP] Adding a RankingEvaluator to ML
yongtang 19ea63b
[SPARK-14409][ML][WIP] Adding a RankingEvaluator to ML
yongtang 78f13ad
[SPARK-14409][ML] Adding a RankingEvaluator to ML
yongtang File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
134 changes: 134 additions & 0 deletions
134
mllib/src/main/scala/org/apache/spark/ml/evaluation/RankingEvaluator.scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,134 @@ | ||
| /* | ||
| * Licensed to the Apache Software Foundation (ASF) under one or more | ||
| * contributor license agreements. See the NOTICE file distributed with | ||
| * this work for additional information regarding copyright ownership. | ||
| * The ASF licenses this file to You under the Apache License, Version 2.0 | ||
| * (the "License"); you may not use this file except in compliance with | ||
| * the License. You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| package org.apache.spark.ml.evaluation | ||
|
|
||
| import scala.reflect.ClassTag | ||
|
|
||
| import org.apache.spark.annotation.{Experimental, Since} | ||
| import org.apache.spark.internal.Logging | ||
| import org.apache.spark.ml.param.{IntParam, Param, ParamMap, ParamValidators} | ||
| import org.apache.spark.ml.param.shared.{HasLabelCol, HasPredictionCol} | ||
| import org.apache.spark.ml.util.{DefaultParamsReadable, DefaultParamsWritable, Identifiable} | ||
| import org.apache.spark.mllib.evaluation.RankingMetrics | ||
| import org.apache.spark.sql.{DataFrame, Dataset, Row, SQLContext} | ||
| import org.apache.spark.sql.functions._ | ||
|
|
||
| /** | ||
| * :: Experimental :: | ||
| * Evaluator for ranking, which expects two input columns: prediction and label. | ||
| * Both prediction and label columns need to be instances of Array[T] where T is the ClassTag. | ||
| */ | ||
| @Since("2.0.0") | ||
| @Experimental | ||
| final class RankingEvaluator[T: ClassTag] @Since("2.0.0") (@Since("2.0.0") override val uid: String) | ||
| extends Evaluator with HasPredictionCol with HasLabelCol with DefaultParamsWritable with Logging { | ||
|
|
||
| @Since("2.0.0") | ||
| def this() = this(Identifiable.randomUID("rankingEval")) | ||
|
|
||
| @Since("2.0.0") | ||
| final val k = new IntParam(this, "k", "Top-K cutoff", (x: Int) => x > 0) | ||
|
|
||
| /** @group getParam */ | ||
| @Since("2.0.0") | ||
| def getK: Int = $(k) | ||
|
|
||
| /** @group setParam */ | ||
| @Since("2.0.0") | ||
| def setK(value: Int): this.type = set(k, value) | ||
|
|
||
| setDefault(k -> 1) | ||
|
|
||
| /** | ||
| * Param for metric name in evaluation. Supports: | ||
| * - `"map"` (default): Mean Average Precision | ||
| * - `"mapk"`: Mean Average Precision@K | ||
| * - `"ndcg"`: Normalized Discounted Cumulative Gain | ||
| * - `"mrr"`: Mean Reciprocal Rank | ||
| * | ||
| * @group param | ||
| */ | ||
| @Since("2.0.0") | ||
| val metricName: Param[String] = { | ||
| val allowedParams = ParamValidators.inArray(Array("map", "mapk", "ndcg", "mrr")) | ||
| new Param(this, "metricName", "metric name in evaluation (map|mapk|ndcg|mrr)", allowedParams) | ||
| } | ||
|
|
||
| /** @group getParam */ | ||
| @Since("2.0.0") | ||
| def getMetricName: String = $(metricName) | ||
|
|
||
| /** @group setParam */ | ||
| @Since("2.0.0") | ||
| def setMetricName(value: String): this.type = set(metricName, value) | ||
|
|
||
| /** @group setParam */ | ||
| @Since("2.0.0") | ||
| def setPredictionCol(value: String): this.type = set(predictionCol, value) | ||
|
|
||
| /** @group setParam */ | ||
| @Since("2.0.0") | ||
| def setLabelCol(value: String): this.type = set(labelCol, value) | ||
|
|
||
| setDefault(metricName -> "map") | ||
|
|
||
| @Since("2.0.0") | ||
| override def evaluate(dataset: Dataset[_]): Double = { | ||
| val schema = dataset.schema | ||
| val predictionColName = $(predictionCol) | ||
| val predictionType = schema($(predictionCol)).dataType | ||
| val labelColName = $(labelCol) | ||
| val labelType = schema($(labelCol)).dataType | ||
| require(predictionType == labelType, | ||
| s"Prediction column $predictionColName and Label column $labelColName " + | ||
|
||
| s"must be of the same type, but Prediction column $predictionColName is $predictionType " + | ||
| s"and Label column $labelColName is $labelType") | ||
|
|
||
| val predictionAndLabels = dataset | ||
| .select(col($(predictionCol)).cast(predictionType), col($(labelCol)).cast(labelType)) | ||
| .rdd. | ||
| map { case Row(prediction: Seq[T], label: Seq[T]) => (prediction.toArray, label.toArray) } | ||
|
|
||
| val metrics = new RankingMetrics[T](predictionAndLabels) | ||
| val metric = $(metricName) match { | ||
| case "map" => metrics.meanAveragePrecision | ||
| case "ndcg" => metrics.ndcgAt($(k)) | ||
| case "mapk" => metrics.precisionAt($(k)) | ||
| case "mrr" => metrics.meanReciprocalRank | ||
| } | ||
| metric | ||
| } | ||
|
|
||
| @Since("2.0.0") | ||
| override def isLargerBetter: Boolean = $(metricName) match { | ||
| case "map" => false | ||
| case "ndcg" => false | ||
| case "mapk" => false | ||
| case "mrr" => false | ||
| } | ||
|
|
||
| @Since("2.0.0") | ||
| override def copy(extra: ParamMap): RankingEvaluator[T] = defaultCopy(extra) | ||
| } | ||
|
|
||
| @Since("2.0.0") | ||
| object RankingEvaluator extends DefaultParamsReadable[RankingEvaluator[_]] { | ||
|
|
||
| @Since("2.0.0") | ||
| override def load(path: String): RankingEvaluator[_] = super.load(path) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
60 changes: 60 additions & 0 deletions
60
mllib/src/test/scala/org/apache/spark/ml/evaluation/RankingEvaluatorSuite.scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| /* | ||
| * Licensed to the Apache Software Foundation (ASF) under one or more | ||
| * contributor license agreements. See the NOTICE file distributed with | ||
| * this work for additional information regarding copyright ownership. | ||
| * The ASF licenses this file to You under the Apache License, Version 2.0 | ||
| * (the "License"); you may not use this file except in compliance with | ||
| * the License. You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| package org.apache.spark.ml.evaluation | ||
|
|
||
| import org.apache.spark.SparkFunSuite | ||
| import org.apache.spark.ml.param.ParamsSuite | ||
| import org.apache.spark.ml.util.DefaultReadWriteTest | ||
| import org.apache.spark.mllib.util.MLlibTestSparkContext | ||
| import org.apache.spark.mllib.util.TestingUtils._ | ||
|
|
||
| class RankingEvaluatorSuite | ||
| extends SparkFunSuite with MLlibTestSparkContext with DefaultReadWriteTest { | ||
|
|
||
| test("params") { | ||
| ParamsSuite.checkParams(new RankingEvaluator) | ||
| } | ||
|
|
||
| test("Ranking Evaluator: default params") { | ||
| val sqlContext = new org.apache.spark.sql.SQLContext(sc) | ||
| import sqlContext.implicits._ | ||
|
|
||
| val predictionAndLabels = sqlContext.createDataFrame(sc.parallelize( | ||
| Seq( | ||
| (Array[Int](1, 6, 2, 7, 8, 3, 9, 10, 4, 5), Array[Int](1, 2, 3, 4, 5)), | ||
| (Array[Int](4, 1, 5, 6, 2, 7, 3, 8, 9, 10), Array[Int](1, 2, 3)), | ||
| (Array[Int](1, 2, 3, 4, 5), Array[Int]()) | ||
| ), 2)).toDF(Seq("prediction", "label"): _*) | ||
|
|
||
| // default = map, k = 1 | ||
| val evaluator = new RankingEvaluator() | ||
| assert(evaluator.evaluate(predictionAndLabels) ~== 0.355026 absTol 0.01) | ||
|
|
||
| // mapk, k = 5 | ||
| evaluator.setMetricName("mapk").setK(5) | ||
| assert(evaluator.evaluate(predictionAndLabels) ~== 0.8/3 absTol 0.01) | ||
|
|
||
| // ndcg, k = 5 | ||
| evaluator.setMetricName("ndcg") | ||
| assert(evaluator.evaluate(predictionAndLabels) ~== 0.328788 absTol 0.01) | ||
|
|
||
| // mrr | ||
| evaluator.setMetricName("mrr") | ||
| assert(evaluator.evaluate(predictionAndLabels) ~== 0.5 absTol 0.01) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think we need a little more documentation here, perhaps mentioning the exact input types of these columns (as they're not just Double, they're Arrays, and this differs from the other evaluators).