zhengruifeng commented on a change in pull request #31160: URL: https://github.com/apache/spark/pull/31160#discussion_r556295900
########## File path: docs/ml-features.md ########## @@ -1793,13 +1793,16 @@ for more details on the API. </div> </div> -## ANOVASelector - -`ANOVASelector` operates on categorical labels with continuous features. It uses the -[one-way ANOVA F-test](https://en.wikipedia.org/wiki/F-test#Multiple-comparison_ANOVA_problems) to decide which -features to choose. +## UnivariateFeatureSelector + +`UnivariateFeatureSelector` operates on categorical/continuous labels with categorical/continuous features. +User can set `featureType` and `labelType`, and Spark will pick the score function to use based on the specified Review comment: Totally nit: using a table instead? ########## File path: mllib/src/main/scala/org/apache/spark/ml/feature/UnivariateFeatureSelector.scala ########## @@ -0,0 +1,511 @@ +/* + * 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.hadoop.fs.Path + +import org.apache.spark.annotation.Since +import org.apache.spark.ml.{Estimator, Model} +import org.apache.spark.ml.attribute.{Attribute, AttributeGroup, NominalAttribute, NumericAttribute} +import org.apache.spark.ml.linalg.{DenseVector, SparseVector, Vector, Vectors, VectorUDT} +import org.apache.spark.ml.param._ +import org.apache.spark.ml.param.shared.{HasFeaturesCol, HasLabelCol, HasOutputCol} +import org.apache.spark.ml.stat.{ANOVATest, ChiSquareTest, FValueTest} +import org.apache.spark.ml.util._ +import org.apache.spark.sql.{DataFrame, Dataset} +import org.apache.spark.sql.functions.{col, udf} +import org.apache.spark.sql.types.{StructField, StructType} + + +/** + * Params for [[UnivariateFeatureSelector]] and [[UnivariateFeatureSelectorModel]]. + */ +private[feature] trait UnivariateFeatureSelectorParams extends Params + with HasFeaturesCol with HasLabelCol with HasOutputCol { + + /** + * The feature type. + * Supported options: "categorical", "continuous" + * @group param + */ + @Since("3.1.0") + final val featureType = new Param[String](this, "featureType", + "Feature type. Supported options: categorical, continuous.", + ParamValidators.inArray(Array("categorical", "continuous"))) + + /** @group getParam */ + @Since("3.1.0") + def getFeatureType: String = $(featureType) + + /** + * The label type. + * Supported options: "categorical", "continuous" + * @group param + */ + @Since("3.1.0") + final val labelType = new Param[String](this, "labelType", + "Label type. Supported options: categorical, continuous.", + ParamValidators.inArray(Array("categorical", "continuous"))) + + /** @group getParam */ + @Since("3.1.0") + def getLabelType: String = $(labelType) + + /** + * 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"))) + + /** @group getParam */ + @Since("3.1.0") + def getSelectorType: String = $(selectorType) + + /** + * 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)) + + /** @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)) + + /** @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 highest p-value for features to be kept.", + ParamValidators.inRange(0, 1)) + + /** @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)) + + /** @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)) + + /** @group getParam */ + def getFwe: Double = $(fwe) + + setDefault(numTopFeatures -> 50, percentile -> 0.1, fpr -> 0.05, fdr -> 0.05, fwe -> 0.05, + selectorType -> "numTopFeatures") +} + +/** + * UnivariateFeatureSelector + * The user can set featureType and labelType, and Spark will pick the score function based on + * the specified featureType and labelType. + * The following combination of featureType and labelType are supported: + * 1. featureType categorical and labelType categorical: Spark uses chi2 + * 2. featureType continuous and labelType categorical: Spark uses f_classif + * 3. featureType continuous and labelType continuous: Spark uses f_regression + * + * The UnivariateFeatureSelector 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") +final class UnivariateFeatureSelector @Since("3.1.0")(@Since("3.1.0") override val uid: String) + extends Estimator[UnivariateFeatureSelectorModel] with UnivariateFeatureSelectorParams + with DefaultParamsWritable { + + @Since("3.1.0") + def this() = this(Identifiable.randomUID("UnivariateFeatureSelector")) + + /** @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 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 setLabelCol(value: String): this.type = set(labelCol, value) + + /** @group setParam */ + @Since("3.1.0") + def setFeatureType(value: String): this.type = set(featureType, value) + + /** @group setParam */ + @Since("3.1.0") + def setLabelType(value: String): this.type = set(labelType, value) + + @Since("3.1.0") + override def fit(dataset: Dataset[_]): UnivariateFeatureSelectorModel = { + transformSchema(dataset.schema, logging = true) + val spark = dataset.sparkSession + import spark.implicits._ + + val numFeatures = MetadataUtils.getNumFeatures(dataset, $(featuresCol)) + + val resultDF = if (isSet(featureType) && isSet(labelType)) { Review comment: Is this clearer: ``` require(isSet(featureType) && isSet(labelType), "featureType and labelType need to be set") ($(featureType), $(labelType)) match { case ("categorical", "categorical") => ChiSquareTest.test(dataset.toDF, getFeaturesCol, getLabelCol, true) case ("continuous", "categorical") => ANOVATest.test(dataset.toDF, getFeaturesCol, getLabelCol, true) case ("continuous", "continuous") => FValueTest.test(dataset.toDF, getFeaturesCol, getLabelCol, true) case _ => throw new IllegalStateException(s"Unsupported combination: featureType=${$(featureType)}, labelType=${$(labelType)}") } ``` ---------------------------------------------------------------- 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]
