You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by GitBox <gi...@apache.org> on 2020/03/15 22:10:45 UTC

[GitHub] [spark] huaxingao commented on a change in pull request #27895: [SPARK-31138][ML] Add ANOVA Selector for continuous features and categorical labels

huaxingao commented on a change in pull request #27895: [SPARK-31138][ML] Add ANOVA Selector for continuous features and categorical labels
URL: https://github.com/apache/spark/pull/27895#discussion_r392717964
 
 

 ##########
 File path: mllib/src/main/scala/org/apache/spark/ml/stat/ANOVATest.scala
 ##########
 @@ -0,0 +1,167 @@
+/*
+ * 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.stat
+
+import org.apache.commons.math3.distribution.FDistribution
+
+import org.apache.spark.annotation.Since
+import org.apache.spark.ml.feature.LabeledPoint
+import org.apache.spark.ml.linalg.{Vector, Vectors, VectorUDT}
+import org.apache.spark.ml.util.SchemaUtils
+import org.apache.spark.sql._
+import org.apache.spark.sql.functions.col
+import org.apache.spark.util.collection.OpenHashMap
+
+
+/**
+ * ANOVA Test
+ */
+@Since("3.1.0")
+object ANOVATest {
+
+  /** Used to construct output schema of tests */
+  private case class ANOVAResult(
+      pValues: Vector,
+      degreesOfFreedom: Array[Long],
+      fValues: Vector)
+
+  /**
+   * @param dataset  DataFrame of categorical labels and continuous features.
+   * @param featuresCol  Name of features column in dataset, of type `Vector` (`VectorUDT`)
+   * @param labelCol  Name of label column in dataset, of any numerical type
+   * @return DataFrame containing the test result for every feature against the label.
+   *         This DataFrame will contain a single Row with the following fields:
+   *          - `pValues: Vector`
+   *          - `degreesOfFreedom: Array[Long]`
+   *          - `fValues: Vector`
+   *         Each of these fields has one value per feature.
+   */
+  @Since("3.1.0")
+  def test(dataset: DataFrame, featuresCol: String, labelCol: String): DataFrame = {
+    val spark = dataset.sparkSession
+    val testResults = testClassification(dataset, featuresCol, labelCol)
+    val pValues: Vector = Vectors.dense(testResults.map(_.pValue))
+    val degreesOfFreedom: Array[Long] = testResults.map(_.degreesOfFreedom)
+    val fValues: Vector = Vectors.dense(testResults.map(_.statistic))
+    spark.createDataFrame(
+      Seq(new ANOVAResult(pValues, degreesOfFreedom, fValues)))
+  }
+
+  /**
+   * @param dataset  DataFrame of categorical labels and continuous features.
+   * @param featuresCol  Name of features column in dataset, of type `Vector` (`VectorUDT`)
+   * @param labelCol  Name of label column in dataset, of any numerical type
+   * @return Array containing the ANOVATestResult for every feature against the
+   *         label.
+   */
+  private[ml] def testClassification(
+      dataset: Dataset[_],
+      featuresCol: String,
+      labelCol: String): Array[SelectionTestResult] = {
+
+    val spark = dataset.sparkSession
+    import spark.implicits._
+
+    SchemaUtils.checkColumnType(dataset.schema, featuresCol, new VectorUDT)
+    SchemaUtils.checkNumericType(dataset.schema, labelCol)
+
+    val labeledPointRdd = dataset.select(col("label").cast("double"), col("features"))
+      .as[(Double, Vector)]
+      .rdd.map { case (label, features) => LabeledPoint(label, features) }
+
+    val numFeatures = labeledPointRdd.first().features.size
+    val numSamples = labeledPointRdd.count()
+    val numClasses = labeledPointRdd.map(d => d.label).distinct.count
+
+    labeledPointRdd.flatMap { case LabeledPoint(label, features) =>
+      features.iterator.map { case (col, value) =>
+        (col, (label, value, value * value))
+      }
+    }.aggregateByKey[(Double, Double, OpenHashMap[Double, Double], OpenHashMap[Double, Long])](
+      (0.0, 0.0, new OpenHashMap[Double, Double], new OpenHashMap[Double, Long]))(
+      seqOp = {
+        case (
+          (sum: Double, sumOfSq: Double, mapOfSumPerClass, mapOfCountPerClass),
+          (label, feature, featureSq)
+         ) =>
+          mapOfSumPerClass.changeValue(label, feature, _ + feature)
+          mapOfCountPerClass.changeValue(label, 1L, _ + 1L)
+          (mapOfSumPerClass, mapOfCountPerClass)
+          (sum + feature, sumOfSq + featureSq, mapOfSumPerClass, mapOfCountPerClass)
+      },
+      combOp = {
+        case (
+          (sum1, sumOfSq1, mapOfSumPerClass1, mapOfCountPerClass1),
+          (sum2, sumOfSq2, mapOfSumPerClass2, mapOfCountPerClass2)
+        ) =>
+          mapOfSumPerClass2.foreach { case (v, w) =>
+            mapOfSumPerClass1.changeValue(v, w, _ + w)
+          }
+          mapOfCountPerClass2.foreach { case (v, w) =>
+            mapOfCountPerClass1.changeValue(v, w, _ + w)
+          }
+          (sum1 + sum2, sumOfSq1 + sumOfSq2, mapOfSumPerClass1, mapOfCountPerClass1)
+      }
+    ).map {
+      case (col, (sum, sumOfSq, mapOfSumPerClass, mapOfCountPerClass)) =>
+        // e.g. feature is [3.3, 2.5, 1.0, 3.0, 2.0] and labels are [1, 2, 1, 3, 3]
+        // sum: sum of all the features (3.3+2.5+1.0+3.0+2.0)
+        // sumOfSq: sum of squares of all the features (3.3^2+2.5^2+1.0^2+3.0^2+2.0^2)
+        // mapOfSumPerClass key: label, value: sum of features for each label
+        //                                         ( 1 -> 3.3 + 1.0, 2 -> 2.5, 3 -> 3.0 + 2.0 )
+        // mapOfCountPerClass key: label, value: count of features for each label
+        //                                         ( 1 -> 2, 2 -> 2, 3 -> 2 )
+        // sqSum: square of sum of all data ((3.3+2.5+1.0+3.0+2.0)^2)
+        val sqSum = sum * sum
+        val ssTot = sumOfSq - sqSum / numSamples
+
+        // sumOfSqSumPerClass:
+        //     sum( sq_sum_classes[k] / n_samples_per_class[k] for k in range(n_classes))
+        //     e.g. ((3.3+1.0)^2 / 2 + 2.5^2 / 1 + (3.0+2.0)^2 / 2)
+        var sumOfSqSumPerClass = 0.0
+        val (keys1, values1) = mapOfSumPerClass.iterator.toSeq.sortBy(_._1).unzip
 
 Review comment:
   Removed ```.iterator```

----------------------------------------------------------------
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:
users@infra.apache.org


With regards,
Apache Git Services

---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org