zhengruifeng commented on a change in pull request #27978:
URL: https://github.com/apache/spark/pull/27978#discussion_r417042961



##########
File path: mllib/src/main/scala/org/apache/spark/ml/feature/FValueSelector.scala
##########
@@ -154,111 +45,72 @@ private[feature] trait FValueSelectorParams extends Params
  * set to 50.
  */
 @Since("3.1.0")
-final class FValueSelector @Since("3.1.0") (override val uid: String)
-  extends Estimator[FValueSelectorModel] with FValueSelectorParams
-    with DefaultParamsWritable {
+final class FValueSelector @Since("3.1.0") (@Since("3.1.0") override val uid: 
String) extends
+  Selector[FValueSelectorModel] {
 
   @Since("3.1.0")
   def this() = this(Identifiable.randomUID("FValueSelector"))
 
   /** @group setParam */
   @Since("3.1.0")
-  def setNumTopFeatures(value: Int): this.type = set(numTopFeatures, value)
+  override def setNumTopFeatures(value: Int): this.type = 
super.setNumTopFeatures(value)
 
   /** @group setParam */
   @Since("3.1.0")
-  def setPercentile(value: Double): this.type = set(percentile, value)
+  override def setPercentile(value: Double): this.type = 
super.setPercentile(value)
 
   /** @group setParam */
   @Since("3.1.0")
-  def setFpr(value: Double): this.type = set(fpr, value)
+  override def setFpr(value: Double): this.type = super.setFpr(value)
 
   /** @group setParam */
   @Since("3.1.0")
-  def setFdr(value: Double): this.type = set(fdr, value)
+  override def setFdr(value: Double): this.type = super.setFdr(value)
 
   /** @group setParam */
   @Since("3.1.0")
-  def setFwe(value: Double): this.type = set(fwe, value)
+  override def setFwe(value: Double): this.type = super.setFwe(value)
 
   /** @group setParam */
   @Since("3.1.0")
-  def setSelectorType(value: String): this.type = set(selectorType, value)
+  override def setSelectorType(value: String): this.type = 
super.setSelectorType(value)
 
   /** @group setParam */
   @Since("3.1.0")
-  def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+  override def setFeaturesCol(value: String): this.type = 
super.setFeaturesCol(value)
 
   /** @group setParam */
   @Since("3.1.0")
-  def setOutputCol(value: String): this.type = set(outputCol, value)
+  override def setOutputCol(value: String): this.type = 
super.setOutputCol(value)
 
   /** @group setParam */
   @Since("3.1.0")
-  def setLabelCol(value: String): this.type = set(labelCol, value)
+  override def setLabelCol(value: String): this.type = super.setLabelCol(value)
 
-  @Since("3.1.0")
-  override def fit(dataset: Dataset[_]): FValueSelectorModel = {
-    transformSchema(dataset.schema, logging = true)
-    val spark = dataset.sparkSession
-    import spark.implicits._
-
-    val numFeatures = MetadataUtils.getNumFeatures(dataset, $(featuresCol))
-    val resultDF = FValueTest.test(dataset.toDF, $(featuresCol), $(labelCol), 
true)
-
-    def getTopIndices(k: Int): Array[Int] = {
-      resultDF.sort("pValue", "featureIndex")
-        .select("featureIndex")
-        .limit(k)
-        .as[Int]
-        .collect()
-    }
-
-    val indices = $(selectorType) match {
-      case "numTopFeatures" =>
-        getTopIndices($(numTopFeatures))
-      case "percentile" =>
-        getTopIndices((numFeatures * getPercentile).toInt)
-      case "fpr" =>
-        resultDF.select("featureIndex")
-          .where(col("pValue") < $(fpr))
-          .as[Int].collect()
-      case "fdr" =>
-        // This uses the Benjamini-Hochberg procedure.
-        // 
https://en.wikipedia.org/wiki/False_discovery_rate#Benjamini.E2.80.93Hochberg_procedure
-        val f = $(fdr) / numFeatures
-        val maxIndex = resultDF.sort("pValue", "featureIndex")
-          .select("pValue")
-          .as[Double].rdd
-          .zipWithIndex
-          .flatMap { case (pValue, index) =>
-            if (pValue <= f * (index + 1)) {
-              Iterator.single(index.toInt)
-            } else Iterator.empty
-          }.fold(-1)(math.max)
-        if (maxIndex >= 0) {
-          getTopIndices(maxIndex + 1)
-        } else Array.emptyIntArray
-      case "fwe" =>
-        resultDF.select("featureIndex")
-          .where(condition = col("pValue") < $(fwe) / numFeatures)
-          .as[Int].collect()
-      case errorType =>
-        throw new IllegalStateException(s"Unknown Selector Type: $errorType")
-    }
+  /**
+   * get the SelectionTestResult for every feature against the label
+   */
+  protected[this] override def getSelectionTestResult(df: DataFrame): 
DataFrame = {
+    FValueTest.test(df, getFeaturesCol, getLabelCol, true)
+  }
 
-    copyValues(new FValueSelectorModel(uid, indices.sorted).setParent(this))
+  /**
+   * Create a new instance of concrete SelectorModel.
+   * @param indices The indices of the selected features
+   * @return A new SelectorModel instance
+   */
+  protected[this] def createSelectorModel(
+      uid: String,
+      indices: Array[Int]): FValueSelectorModel = {
+    new FValueSelectorModel(uid, indices)
   }
 
-  @Since("3.1.0")

Review comment:
       keep this since annotation?

##########
File path: mllib/src/main/scala/org/apache/spark/ml/feature/ANOVASelector.scala
##########
@@ -53,111 +46,71 @@ import org.apache.spark.sql.types.{StructField, StructType}
  */
 @Since("3.1.0")
 final class ANOVASelector @Since("3.1.0")(@Since("3.1.0") override val uid: 
String)
-  extends Estimator[ANOVASelectorModel] with FValueSelectorParams
-    with DefaultParamsWritable {
+  extends Selector[ANOVASelectorModel] {
 
   @Since("3.1.0")
   def this() = this(Identifiable.randomUID("ANOVASelector"))
 
   /** @group setParam */
   @Since("3.1.0")
-  def setNumTopFeatures(value: Int): this.type = set(numTopFeatures, value)
+  override def setNumTopFeatures(value: Int): this.type = 
super.setNumTopFeatures(value)
 
   /** @group setParam */
   @Since("3.1.0")
-  def setPercentile(value: Double): this.type = set(percentile, value)
+  override def setPercentile(value: Double): this.type = 
super.setPercentile(value)
 
   /** @group setParam */
   @Since("3.1.0")
-  def setFpr(value: Double): this.type = set(fpr, value)
+  override def setFpr(value: Double): this.type = super.setFpr(value)
 
   /** @group setParam */
   @Since("3.1.0")
-  def setFdr(value: Double): this.type = set(fdr, value)
+  override def setFdr(value: Double): this.type = super.setFdr(value)
 
   /** @group setParam */
   @Since("3.1.0")
-  def setFwe(value: Double): this.type = set(fwe, value)
+  override def setFwe(value: Double): this.type = super.setFwe(value)
 
   /** @group setParam */
   @Since("3.1.0")
-  def setSelectorType(value: String): this.type = set(selectorType, value)
+  override def setSelectorType(value: String): this.type = 
super.setSelectorType(value)
 
   /** @group setParam */
   @Since("3.1.0")
-  def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+  override def setFeaturesCol(value: String): this.type = 
super.setFeaturesCol(value)
 
   /** @group setParam */
   @Since("3.1.0")
-  def setOutputCol(value: String): this.type = set(outputCol, value)
+  override def setOutputCol(value: String): this.type = 
super.setOutputCol(value)
 
   /** @group setParam */
   @Since("3.1.0")
-  def setLabelCol(value: String): this.type = set(labelCol, value)
-
-  @Since("3.1.0")
-  override def fit(dataset: Dataset[_]): ANOVASelectorModel = {
-    transformSchema(dataset.schema, logging = true)
-
-    val spark = dataset.sparkSession
-    import spark.implicits._
+  override def setLabelCol(value: String): this.type = super.setLabelCol(value)
 
-    val numFeatures = MetadataUtils.getNumFeatures(dataset, $(featuresCol))
-    val resultDF = ANOVATest.test(dataset.toDF, $(featuresCol), $(labelCol), 
true)
-
-    def getTopIndices(k: Int): Array[Int] = {
-      resultDF.sort("pValue", "featureIndex")
-        .select("featureIndex")
-        .limit(k)
-        .as[Int]
-        .collect()
-    }
-
-    val indices = $(selectorType) match {
-      case "numTopFeatures" =>
-        getTopIndices($(numTopFeatures))
-      case "percentile" =>
-        getTopIndices((numFeatures * getPercentile).toInt)
-      case "fpr" =>
-        resultDF.select("featureIndex")
-          .where(col("pValue") < $(fpr))
-          .as[Int].collect()
-      case "fdr" =>
-        // This uses the Benjamini-Hochberg procedure.
-        // 
https://en.wikipedia.org/wiki/False_discovery_rate#Benjamini.E2.80.93Hochberg_procedure
-        val f = $(fdr) / numFeatures
-        val maxIndex = resultDF.sort("pValue", "featureIndex")
-          .select("pValue")
-          .as[Double].rdd
-          .zipWithIndex
-          .flatMap { case (pValue, index) =>
-            if (pValue <= f * (index + 1)) {
-              Iterator.single(index.toInt)
-            } else Iterator.empty
-          }.fold(-1)(math.max)
-        if (maxIndex >= 0) {
-          getTopIndices(maxIndex + 1)
-        } else Array.emptyIntArray
-      case "fwe" =>
-        resultDF.select("featureIndex")
-          .where(col("pValue") < $(fwe) / numFeatures)
-          .as[Int].collect()
-      case errorType =>
-        throw new IllegalStateException(s"Unknown Selector Type: $errorType")
-    }
+  /**
+   * get the SelectionTestResult for every feature against the label
+   */
+  protected[this] override def getSelectionTestResult(df: DataFrame): 
DataFrame = {
+    ANOVATest.test(df, getFeaturesCol, getLabelCol, true)
+  }
 
-    copyValues(new ANOVASelectorModel(uid, indices.sorted).setParent(this))
+  /**
+   * Create a new instance of concrete SelectorModel.
+   * @param indices The indices of the selected features
+   * @return A new SelectorModel instance
+   */
+  protected[this] def createSelectorModel(
+      uid: String,
+      indices: Array[Int]): ANOVASelectorModel = {
+    new ANOVASelectorModel(uid, indices)
   }
 
-  @Since("3.1.0")

Review comment:
       keep this since annotation?

##########
File path: mllib/src/main/scala/org/apache/spark/ml/feature/ChiSqSelector.scala
##########
@@ -153,106 +46,71 @@ private[feature] trait ChiSqSelectorParams extends Params
  */
 @Since("1.6.0")
 final class ChiSqSelector @Since("1.6.0") (@Since("1.6.0") override val uid: 
String)
-  extends Estimator[ChiSqSelectorModel] with ChiSqSelectorParams with 
DefaultParamsWritable {
+  extends Selector[ChiSqSelectorModel] {
 
   @Since("1.6.0")
   def this() = this(Identifiable.randomUID("chiSqSelector"))
 
   /** @group setParam */
   @Since("1.6.0")
-  def setNumTopFeatures(value: Int): this.type = set(numTopFeatures, value)
+  override def setNumTopFeatures(value: Int): this.type = 
super.setNumTopFeatures(value)
 
   /** @group setParam */
   @Since("2.1.0")
-  def setPercentile(value: Double): this.type = set(percentile, value)
+  override def setPercentile(value: Double): this.type = 
super.setPercentile(value)
 
   /** @group setParam */
   @Since("2.1.0")
-  def setFpr(value: Double): this.type = set(fpr, value)
+  override def setFpr(value: Double): this.type = super.setFpr(value)
 
   /** @group setParam */
   @Since("2.2.0")
-  def setFdr(value: Double): this.type = set(fdr, value)
+  override def setFdr(value: Double): this.type = super.setFdr(value)
 
   /** @group setParam */
   @Since("2.2.0")
-  def setFwe(value: Double): this.type = set(fwe, value)
+  override def setFwe(value: Double): this.type = super.setFwe(value)
 
   /** @group setParam */
   @Since("2.1.0")
-  def setSelectorType(value: String): this.type = set(selectorType, value)
+  override def setSelectorType(value: String): this.type = 
super.setSelectorType(value)
 
   /** @group setParam */
   @Since("1.6.0")
-  def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+  override def setFeaturesCol(value: String): this.type = 
super.setFeaturesCol(value)
 
   /** @group setParam */
   @Since("1.6.0")
-  def setOutputCol(value: String): this.type = set(outputCol, value)
+  override def setOutputCol(value: String): this.type = 
super.setOutputCol(value)
 
   /** @group setParam */
   @Since("1.6.0")
-  def setLabelCol(value: String): this.type = set(labelCol, value)
+  override def setLabelCol(value: String): this.type = super.setLabelCol(value)
 
-  @Since("2.0.0")
-  override def fit(dataset: Dataset[_]): ChiSqSelectorModel = {
-    transformSchema(dataset.schema, logging = true)
-    val spark = dataset.sparkSession
-    import spark.implicits._
-
-    val numFeatures = MetadataUtils.getNumFeatures(dataset, $(featuresCol))
-    val resultDF = ChiSquareTest.test(dataset.toDF, $(featuresCol), 
$(labelCol), true)
-
-    def getTopIndices(k: Int): Array[Int] = {
-      resultDF.sort("pValue", "featureIndex")
-        .select("featureIndex")
-        .limit(k)
-        .as[Int]
-        .collect()
-    }
+  /**
+   * get the SelectionTestResult for every feature against the label
+   */
+  protected[this] override def getSelectionTestResult(df: DataFrame): 
DataFrame = {
+    ChiSquareTest.test(df, getFeaturesCol, getLabelCol, true)
+  }
 
-    val indices = $(selectorType) match {
-      case "numTopFeatures" =>
-        getTopIndices($(numTopFeatures))
-      case "percentile" =>
-        getTopIndices((numFeatures * getPercentile).toInt)
-      case "fpr" =>
-        resultDF.select("featureIndex")
-          .where(col("pValue") < $(fpr))
-          .as[Int].collect()
-      case "fdr" =>
-        // This uses the Benjamini-Hochberg procedure.
-        // 
https://en.wikipedia.org/wiki/False_discovery_rate#Benjamini.E2.80.93Hochberg_procedure
-        val f = $(fdr) / numFeatures
-        val maxIndex = resultDF.sort("pValue", "featureIndex")
-          .select("pValue")
-          .as[Double].rdd
-          .zipWithIndex
-          .flatMap { case (pValue, index) =>
-            if (pValue <= f * (index + 1)) {
-              Iterator.single(index.toInt)
-            } else Iterator.empty
-          }.fold(-1)(math.max)
-        if (maxIndex >= 0) {
-          getTopIndices(maxIndex + 1)
-        } else Array.emptyIntArray
-      case "fwe" =>
-        resultDF.select("featureIndex")
-          .where(col("pValue") < $(fwe) / numFeatures)
-          .as[Int].collect()
-      case errorType =>
-        throw new IllegalStateException(s"Unknown Selector Type: $errorType")
-    }
+  /**
+   * Create a new instance of concrete SelectorModel.
+   * @param indices The indices of the selected features
+   * @return A new SelectorModel instance
+   */
+  protected[this] def createSelectorModel(
+      uid: String,
+      indices: Array[Int]): ChiSqSelectorModel = {
+    new ChiSqSelectorModel(uid, indices)
+  }
 
-    copyValues(new ChiSqSelectorModel(uid, indices.sorted).setParent(this))

Review comment:
       missing since annotation?
   

##########
File path: mllib/src/main/scala/org/apache/spark/ml/feature/Selector.scala
##########
@@ -0,0 +1,391 @@
+/*
+ * 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.feature
+
+import scala.collection.mutable.ArrayBuilder
+
+import org.apache.spark.annotation.Since
+import org.apache.spark.ml._
+import org.apache.spark.ml.attribute.{AttributeGroup, _}
+import org.apache.spark.ml.linalg._
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util._
+import org.apache.spark.sql.{DataFrame, Dataset}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{StructField, StructType}
+
+
+/**
+ * Params for [[Selector]] and [[SelectorModel]].
+ */
+private[feature] trait SelectorParams extends Params
+  with HasFeaturesCol with HasLabelCol with HasOutputCol {
+
+  /**
+   * Number of features that selector will select, ordered by ascending 
p-value. If the
+   * number of features is less than numTopFeatures, then this will select all 
features.
+   * Only applicable when selectorType = "numTopFeatures".
+   * The default value of numTopFeatures is 50.
+   *
+   * @group param
+   */
+  @Since("3.1.0")
+  final val numTopFeatures = new IntParam(this, "numTopFeatures",
+    "Number of features that selector will select, ordered by ascending 
p-value. If the" +
+      " number of features is < numTopFeatures, then this will select all 
features.",
+    ParamValidators.gtEq(1))
+  setDefault(numTopFeatures -> 50)
+
+  /** @group getParam */
+  @Since("3.1.0")
+  def getNumTopFeatures: Int = $(numTopFeatures)
+
+  /**
+   * Percentile of features that selector will select, ordered by ascending 
p-value.
+   * Only applicable when selectorType = "percentile".
+   * Default value is 0.1.
+   * @group param
+   */
+  @Since("3.1.0")
+  final val percentile = new DoubleParam(this, "percentile",
+    "Percentile of features that selector will select, ordered by ascending 
p-value.",
+    ParamValidators.inRange(0, 1))
+  setDefault(percentile -> 0.1)
+
+  /** @group getParam */
+  @Since("3.1.0")
+  def getPercentile: Double = $(percentile)
+
+  /**
+   * The highest p-value for features to be kept.
+   * Only applicable when selectorType = "fpr".
+   * Default value is 0.05.
+   * @group param
+   */
+  @Since("3.1.0")
+  final val fpr = new DoubleParam(this, "fpr", "The higest p-value for 
features to be kept.",
+    ParamValidators.inRange(0, 1))
+  setDefault(fpr -> 0.05)
+
+  /** @group getParam */
+  @Since("3.1.0")
+  def getFpr: Double = $(fpr)
+
+  /**
+   * The upper bound of the expected false discovery rate.
+   * Only applicable when selectorType = "fdr".
+   * Default value is 0.05.
+   * @group param
+   */
+  @Since("3.1.0")
+  final val fdr = new DoubleParam(this, "fdr",
+    "The upper bound of the expected false discovery rate.", 
ParamValidators.inRange(0, 1))
+  setDefault(fdr -> 0.05)
+
+  /** @group getParam */
+  def getFdr: Double = $(fdr)
+
+  /**
+   * The upper bound of the expected family-wise error rate.
+   * Only applicable when selectorType = "fwe".
+   * Default value is 0.05.
+   * @group param
+   */
+  @Since("3.1.0")
+  final val fwe = new DoubleParam(this, "fwe",
+    "The upper bound of the expected family-wise error rate.", 
ParamValidators.inRange(0, 1))
+  setDefault(fwe -> 0.05)
+
+  /** @group getParam */
+  def getFwe: Double = $(fwe)
+
+  /**
+   * The selector type.
+   * Supported options: "numTopFeatures" (default), "percentile", "fpr", 
"fdr", "fwe"
+   * @group param
+   */
+  @Since("3.1.0")
+  final val selectorType = new Param[String](this, "selectorType",
+    "The selector type. Supported options: numTopFeatures, percentile, fpr, 
fdr, fwe",
+    ParamValidators.inArray(Array("numTopFeatures", "percentile", "fpr", "fdr",
+      "fwe")))
+  setDefault(selectorType -> "numTopFeatures")
+
+  /** @group getParam */
+  @Since("3.1.0")
+  def getSelectorType: String = $(selectorType)
+
+}
+
+/**
+ * Super class for feature selectors.
+ * 1. Chi-Square Selector
+ * This feature selector is for categorical features and categorical labels.
+ * 2. ANOVA F-value Classification Selector
+ * This feature selector is for continuous features and categorical labels.
+ * 3. Regression F-value Selector
+ * This feature selector is for continuous features and continuous labels.
+ * The selector supports different selection methods: `numTopFeatures`, 
`percentile`, `fpr`,
+ * `fdr`, `fwe`.
+ *  - `numTopFeatures` chooses a fixed number of top features according to a 
hypothesis.
+ *  - `percentile` is similar but chooses a fraction of all features instead 
of a fixed number.
+ *  - `fpr` chooses all features whose p-value are below a threshold, thus 
controlling the false
+ *    positive rate of selection.
+ *  - `fdr` uses the [Benjamini-Hochberg procedure]
+ *    
(https://en.wikipedia.org/wiki/False_discovery_rate#Benjamini.E2.80.93Hochberg_procedure)
+ *    to choose all features whose false discovery rate is below a threshold.
+ *  - `fwe` chooses all features whose p-values are below a threshold. The 
threshold is scaled by
+ *    1/numFeatures, thus controlling the family-wise error rate of selection.
+ * By default, the selection method is `numTopFeatures`, with the default 
number of top features
+ * set to 50.
+ */
+@Since("3.1.0")
+private[ml] abstract class Selector[T <: SelectorModel[T]]
+  extends Estimator[T] with SelectorParams with DefaultParamsWritable {
+
+  /** @group setParam */
+  @Since("3.1.0")
+  def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+  /** @group setParam */
+  @Since("3.1.0")
+  def setOutputCol(value: String): this.type = set(outputCol, value)
+
+  /** @group setParam */
+  @Since("3.1.0")
+  def setNumTopFeatures(value: Int): this.type = set(numTopFeatures, value)
+
+  /** @group setParam */
+  @Since("3.1.0")
+  def setPercentile(value: Double): this.type = set(percentile, value)
+
+  /** @group setParam */
+  @Since("3.1.0")
+  def setFpr(value: Double): this.type = set(fpr, value)
+
+  /** @group setParam */
+  @Since("3.1.0")
+  def setFdr(value: Double): this.type = set(fdr, value)
+
+  /** @group setParam */
+  @Since("3.1.0")
+  def setFwe(value: Double): this.type = set(fwe, value)
+
+  /** @group setParam */
+  @Since("3.1.0")
+  def setSelectorType(value: String): this.type = set(selectorType, value)
+
+  /** @group setParam */
+  @Since("3.1.0")
+  def setLabelCol(value: String): this.type = set(labelCol, value)
+
+  /**
+   * get the SelectionTestResult for every feature against the label
+   */
+  protected[this] def getSelectionTestResult(df: DataFrame): DataFrame
+
+  /**
+   * Create a new instance of concrete SelectorModel.
+   * @param indices The indices of the selected features
+   * @return A new SelectorModel instance
+   */
+  protected[this] def createSelectorModel(
+      uid: String,
+      indices: Array[Int]): T
+
+  @Since("3.1.0")
+  override def fit(dataset: Dataset[_]): T = {
+    transformSchema(dataset.schema, logging = true)
+    val spark = dataset.sparkSession
+    import spark.implicits._
+
+    val numFeatures = MetadataUtils.getNumFeatures(dataset, $(featuresCol))
+    val resultDF = getSelectionTestResult(dataset.toDF)
+
+    def getTopIndices(k: Int): Array[Int] = {
+      resultDF.sort("pValue", "featureIndex")
+        .select("featureIndex")
+        .limit(k)
+        .as[Int]
+        .collect()
+    }
+
+    val indices = $(selectorType) match {
+      case "numTopFeatures" =>
+        getTopIndices($(numTopFeatures))
+      case "percentile" =>
+        getTopIndices((numFeatures * getPercentile).toInt)
+      case "fpr" =>
+        resultDF.select("featureIndex")
+          .where(col("pValue") < $(fpr))
+          .as[Int].collect()
+      case "fdr" =>
+        // This uses the Benjamini-Hochberg procedure.
+        // 
https://en.wikipedia.org/wiki/False_discovery_rate#Benjamini.E2.80.93Hochberg_procedure
+        val f = $(fdr) / numFeatures
+        val maxIndex = resultDF.sort("pValue", "featureIndex")
+          .select("pValue")
+          .as[Double].rdd
+          .zipWithIndex
+          .flatMap { case (pValue, index) =>
+            if (pValue <= f * (index + 1)) {
+              Iterator.single(index.toInt)
+            } else Iterator.empty
+          }.fold(-1)(math.max)
+        if (maxIndex >= 0) {
+          getTopIndices(maxIndex + 1)
+        } else Array.emptyIntArray
+      case "fwe" =>
+        resultDF.select("featureIndex")
+          .where(col("pValue") < $(fwe) / numFeatures)
+          .as[Int].collect()
+      case errorType =>
+        throw new IllegalStateException(s"Unknown Selector Type: $errorType")
+    }
+
+    copyValues(createSelectorModel(uid, indices.sorted)
+      .setParent(this))
+  }
+
+  @Since("3.1.0")
+  override def transformSchema(schema: StructType): StructType = {
+    SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+    SchemaUtils.checkNumericType(schema, $(labelCol))
+    SchemaUtils.appendColumn(schema, $(outputCol), new VectorUDT)
+  }
+
+  @Since("3.1.0")
+  override def copy(extra: ParamMap): Selector[T] = defaultCopy(extra)
+}
+
+/**
+ * Model fitted by [[Selector]].
+ */
+@Since("3.1.0")
+private[ml] abstract class SelectorModel[T <: SelectorModel[T]] (
+    @Since("3.1.0") val uid: String,
+    @Since("3.1.0") val selectedFeatures: Array[Int])
+  extends Model[T] with SelectorParams with MLWritable {
+  self: T =>
+
+  if (selectedFeatures.length >= 2) {
+    require(selectedFeatures.sliding(2).forall(l => l(0) < l(1)),
+      "Index should be strictly increasing.")
+  }
+
+  /** @group setParam */
+  @Since("3.1.0")
+  def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+  /** @group setParam */
+  @Since("3.1.0")
+  def setOutputCol(value: String): this.type = set(outputCol, value)
+
+  @Since("3.1.0")
+  override def transform(dataset: Dataset[_]): DataFrame = {
+    val outputSchema = transformSchema(dataset.schema, logging = true)
+
+    SelectorModel.transform(dataset, selectedFeatures, outputSchema, 
$(outputCol), $(featuresCol))
+  }
+
+  @Since("3.1.0")
+  override def transformSchema(schema: StructType): StructType = {
+    SchemaUtils.checkColumnType(schema, $(featuresCol), new VectorUDT)
+    val newField =
+      SelectorModel.prepOutputField(schema, selectedFeatures, $(outputCol), 
$(featuresCol))
+    SchemaUtils.appendColumn(schema, newField)
+  }
+}
+
+object SelectorModel {

Review comment:
       `private [feature]` ?

##########
File path: mllib/src/main/scala/org/apache/spark/ml/feature/Selector.scala
##########
@@ -0,0 +1,391 @@
+/*
+ * 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.feature
+
+import scala.collection.mutable.ArrayBuilder
+
+import org.apache.spark.annotation.Since
+import org.apache.spark.ml._
+import org.apache.spark.ml.attribute.{AttributeGroup, _}
+import org.apache.spark.ml.linalg._
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util._
+import org.apache.spark.sql.{DataFrame, Dataset}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{StructField, StructType}
+
+
+/**
+ * Params for [[Selector]] and [[SelectorModel]].
+ */
+private[feature] trait SelectorParams extends Params
+  with HasFeaturesCol with HasLabelCol with HasOutputCol {
+
+  /**
+   * Number of features that selector will select, ordered by ascending 
p-value. If the
+   * number of features is less than numTopFeatures, then this will select all 
features.
+   * Only applicable when selectorType = "numTopFeatures".
+   * The default value of numTopFeatures is 50.
+   *
+   * @group param
+   */
+  @Since("3.1.0")
+  final val numTopFeatures = new IntParam(this, "numTopFeatures",
+    "Number of features that selector will select, ordered by ascending 
p-value. If the" +
+      " number of features is < numTopFeatures, then this will select all 
features.",
+    ParamValidators.gtEq(1))
+  setDefault(numTopFeatures -> 50)
+
+  /** @group getParam */
+  @Since("3.1.0")
+  def getNumTopFeatures: Int = $(numTopFeatures)
+
+  /**
+   * Percentile of features that selector will select, ordered by ascending 
p-value.
+   * Only applicable when selectorType = "percentile".
+   * Default value is 0.1.
+   * @group param
+   */
+  @Since("3.1.0")
+  final val percentile = new DoubleParam(this, "percentile",
+    "Percentile of features that selector will select, ordered by ascending 
p-value.",
+    ParamValidators.inRange(0, 1))
+  setDefault(percentile -> 0.1)
+
+  /** @group getParam */
+  @Since("3.1.0")
+  def getPercentile: Double = $(percentile)
+
+  /**
+   * The highest p-value for features to be kept.
+   * Only applicable when selectorType = "fpr".
+   * Default value is 0.05.
+   * @group param
+   */
+  @Since("3.1.0")
+  final val fpr = new DoubleParam(this, "fpr", "The higest p-value for 
features to be kept.",
+    ParamValidators.inRange(0, 1))
+  setDefault(fpr -> 0.05)
+
+  /** @group getParam */
+  @Since("3.1.0")
+  def getFpr: Double = $(fpr)
+
+  /**
+   * The upper bound of the expected false discovery rate.
+   * Only applicable when selectorType = "fdr".
+   * Default value is 0.05.
+   * @group param
+   */
+  @Since("3.1.0")
+  final val fdr = new DoubleParam(this, "fdr",
+    "The upper bound of the expected false discovery rate.", 
ParamValidators.inRange(0, 1))
+  setDefault(fdr -> 0.05)
+
+  /** @group getParam */
+  def getFdr: Double = $(fdr)
+
+  /**
+   * The upper bound of the expected family-wise error rate.
+   * Only applicable when selectorType = "fwe".
+   * Default value is 0.05.
+   * @group param
+   */
+  @Since("3.1.0")
+  final val fwe = new DoubleParam(this, "fwe",
+    "The upper bound of the expected family-wise error rate.", 
ParamValidators.inRange(0, 1))
+  setDefault(fwe -> 0.05)
+
+  /** @group getParam */
+  def getFwe: Double = $(fwe)
+
+  /**
+   * The selector type.
+   * Supported options: "numTopFeatures" (default), "percentile", "fpr", 
"fdr", "fwe"
+   * @group param
+   */
+  @Since("3.1.0")
+  final val selectorType = new Param[String](this, "selectorType",
+    "The selector type. Supported options: numTopFeatures, percentile, fpr, 
fdr, fwe",
+    ParamValidators.inArray(Array("numTopFeatures", "percentile", "fpr", "fdr",
+      "fwe")))
+  setDefault(selectorType -> "numTopFeatures")
+
+  /** @group getParam */
+  @Since("3.1.0")
+  def getSelectorType: String = $(selectorType)
+
+}
+
+/**
+ * Super class for feature selectors.
+ * 1. Chi-Square Selector
+ * This feature selector is for categorical features and categorical labels.
+ * 2. ANOVA F-value Classification Selector
+ * This feature selector is for continuous features and categorical labels.
+ * 3. Regression F-value Selector
+ * This feature selector is for continuous features and continuous labels.
+ * The selector supports different selection methods: `numTopFeatures`, 
`percentile`, `fpr`,
+ * `fdr`, `fwe`.
+ *  - `numTopFeatures` chooses a fixed number of top features according to a 
hypothesis.
+ *  - `percentile` is similar but chooses a fraction of all features instead 
of a fixed number.
+ *  - `fpr` chooses all features whose p-value are below a threshold, thus 
controlling the false
+ *    positive rate of selection.
+ *  - `fdr` uses the [Benjamini-Hochberg procedure]
+ *    
(https://en.wikipedia.org/wiki/False_discovery_rate#Benjamini.E2.80.93Hochberg_procedure)
+ *    to choose all features whose false discovery rate is below a threshold.
+ *  - `fwe` chooses all features whose p-values are below a threshold. The 
threshold is scaled by
+ *    1/numFeatures, thus controlling the family-wise error rate of selection.
+ * By default, the selection method is `numTopFeatures`, with the default 
number of top features
+ * set to 50.
+ */
+@Since("3.1.0")

Review comment:
       since it is private, we do not need the since annotations? like `LSH`

##########
File path: mllib/src/main/scala/org/apache/spark/ml/feature/Selector.scala
##########
@@ -0,0 +1,391 @@
+/*
+ * 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.feature
+
+import scala.collection.mutable.ArrayBuilder
+
+import org.apache.spark.annotation.Since
+import org.apache.spark.ml._
+import org.apache.spark.ml.attribute.{AttributeGroup, _}
+import org.apache.spark.ml.linalg._
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared._
+import org.apache.spark.ml.util._
+import org.apache.spark.sql.{DataFrame, Dataset}
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{StructField, StructType}
+
+
+/**
+ * Params for [[Selector]] and [[SelectorModel]].
+ */
+private[feature] trait SelectorParams extends Params
+  with HasFeaturesCol with HasLabelCol with HasOutputCol {
+
+  /**
+   * Number of features that selector will select, ordered by ascending 
p-value. If the
+   * number of features is less than numTopFeatures, then this will select all 
features.
+   * Only applicable when selectorType = "numTopFeatures".
+   * The default value of numTopFeatures is 50.
+   *
+   * @group param
+   */
+  @Since("3.1.0")
+  final val numTopFeatures = new IntParam(this, "numTopFeatures",
+    "Number of features that selector will select, ordered by ascending 
p-value. If the" +
+      " number of features is < numTopFeatures, then this will select all 
features.",
+    ParamValidators.gtEq(1))
+  setDefault(numTopFeatures -> 50)
+
+  /** @group getParam */
+  @Since("3.1.0")
+  def getNumTopFeatures: Int = $(numTopFeatures)
+
+  /**
+   * Percentile of features that selector will select, ordered by ascending 
p-value.
+   * Only applicable when selectorType = "percentile".
+   * Default value is 0.1.
+   * @group param
+   */
+  @Since("3.1.0")
+  final val percentile = new DoubleParam(this, "percentile",
+    "Percentile of features that selector will select, ordered by ascending 
p-value.",
+    ParamValidators.inRange(0, 1))
+  setDefault(percentile -> 0.1)
+
+  /** @group getParam */
+  @Since("3.1.0")
+  def getPercentile: Double = $(percentile)
+
+  /**
+   * The highest p-value for features to be kept.
+   * Only applicable when selectorType = "fpr".
+   * Default value is 0.05.
+   * @group param
+   */
+  @Since("3.1.0")
+  final val fpr = new DoubleParam(this, "fpr", "The higest p-value for 
features to be kept.",
+    ParamValidators.inRange(0, 1))
+  setDefault(fpr -> 0.05)
+
+  /** @group getParam */
+  @Since("3.1.0")
+  def getFpr: Double = $(fpr)
+
+  /**
+   * The upper bound of the expected false discovery rate.
+   * Only applicable when selectorType = "fdr".
+   * Default value is 0.05.
+   * @group param
+   */
+  @Since("3.1.0")
+  final val fdr = new DoubleParam(this, "fdr",
+    "The upper bound of the expected false discovery rate.", 
ParamValidators.inRange(0, 1))
+  setDefault(fdr -> 0.05)
+
+  /** @group getParam */
+  def getFdr: Double = $(fdr)
+
+  /**
+   * The upper bound of the expected family-wise error rate.
+   * Only applicable when selectorType = "fwe".
+   * Default value is 0.05.
+   * @group param
+   */
+  @Since("3.1.0")
+  final val fwe = new DoubleParam(this, "fwe",
+    "The upper bound of the expected family-wise error rate.", 
ParamValidators.inRange(0, 1))
+  setDefault(fwe -> 0.05)
+
+  /** @group getParam */
+  def getFwe: Double = $(fwe)
+
+  /**
+   * The selector type.
+   * Supported options: "numTopFeatures" (default), "percentile", "fpr", 
"fdr", "fwe"
+   * @group param
+   */
+  @Since("3.1.0")
+  final val selectorType = new Param[String](this, "selectorType",
+    "The selector type. Supported options: numTopFeatures, percentile, fpr, 
fdr, fwe",
+    ParamValidators.inArray(Array("numTopFeatures", "percentile", "fpr", "fdr",
+      "fwe")))
+  setDefault(selectorType -> "numTopFeatures")
+
+  /** @group getParam */
+  @Since("3.1.0")
+  def getSelectorType: String = $(selectorType)
+
+}
+
+/**
+ * Super class for feature selectors.
+ * 1. Chi-Square Selector
+ * This feature selector is for categorical features and categorical labels.
+ * 2. ANOVA F-value Classification Selector
+ * This feature selector is for continuous features and categorical labels.
+ * 3. Regression F-value Selector
+ * This feature selector is for continuous features and continuous labels.
+ * The selector supports different selection methods: `numTopFeatures`, 
`percentile`, `fpr`,
+ * `fdr`, `fwe`.
+ *  - `numTopFeatures` chooses a fixed number of top features according to a 
hypothesis.
+ *  - `percentile` is similar but chooses a fraction of all features instead 
of a fixed number.
+ *  - `fpr` chooses all features whose p-value are below a threshold, thus 
controlling the false
+ *    positive rate of selection.
+ *  - `fdr` uses the [Benjamini-Hochberg procedure]
+ *    
(https://en.wikipedia.org/wiki/False_discovery_rate#Benjamini.E2.80.93Hochberg_procedure)
+ *    to choose all features whose false discovery rate is below a threshold.
+ *  - `fwe` chooses all features whose p-values are below a threshold. The 
threshold is scaled by
+ *    1/numFeatures, thus controlling the family-wise error rate of selection.
+ * By default, the selection method is `numTopFeatures`, with the default 
number of top features
+ * set to 50.
+ */
+@Since("3.1.0")
+private[ml] abstract class Selector[T <: SelectorModel[T]]
+  extends Estimator[T] with SelectorParams with DefaultParamsWritable {
+
+  /** @group setParam */
+  @Since("3.1.0")
+  def setFeaturesCol(value: String): this.type = set(featuresCol, value)
+
+  /** @group setParam */
+  @Since("3.1.0")
+  def setOutputCol(value: String): this.type = set(outputCol, value)
+
+  /** @group setParam */
+  @Since("3.1.0")
+  def setNumTopFeatures(value: Int): this.type = set(numTopFeatures, value)
+
+  /** @group setParam */
+  @Since("3.1.0")
+  def setPercentile(value: Double): this.type = set(percentile, value)
+
+  /** @group setParam */
+  @Since("3.1.0")
+  def setFpr(value: Double): this.type = set(fpr, value)
+
+  /** @group setParam */
+  @Since("3.1.0")
+  def setFdr(value: Double): this.type = set(fdr, value)
+
+  /** @group setParam */
+  @Since("3.1.0")
+  def setFwe(value: Double): this.type = set(fwe, value)
+
+  /** @group setParam */
+  @Since("3.1.0")
+  def setSelectorType(value: String): this.type = set(selectorType, value)
+
+  /** @group setParam */
+  @Since("3.1.0")
+  def setLabelCol(value: String): this.type = set(labelCol, value)
+
+  /**
+   * get the SelectionTestResult for every feature against the label
+   */
+  protected[this] def getSelectionTestResult(df: DataFrame): DataFrame

Review comment:
       since we use df to contain results, 
`org.apache.spark.ml.stat.SelectionTestResult` will be useless




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
[email protected]



---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to