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 2019/07/16 14:05:06 UTC

[GitHub] [spark] srowen commented on a change in pull request #25160: [SPARK-28399][ML] implement RobustScaler

srowen commented on a change in pull request #25160: [SPARK-28399][ML] implement RobustScaler
URL: https://github.com/apache/spark/pull/25160#discussion_r303925618
 
 

 ##########
 File path: mllib/src/main/scala/org/apache/spark/ml/feature/RobustScaler.scala
 ##########
 @@ -0,0 +1,290 @@
+/*
+ * 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 org.apache.hadoop.fs.Path
+
+import org.apache.spark.annotation.Since
+import org.apache.spark.ml.{Estimator, Model}
+import org.apache.spark.ml.linalg._
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.param.shared.{HasInputCol, HasOutputCol}
+import org.apache.spark.ml.util._
+import org.apache.spark.mllib.util.MLUtils
+import org.apache.spark.sql._
+import org.apache.spark.sql.catalyst.util.QuantileSummaries
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.types.{StructField, StructType}
+
+/**
+ * Params for [[RobustScaler]] and [[RobustScalerModel]].
+ */
+private[feature] trait RobustScalerParams extends Params with HasInputCol with HasOutputCol {
+
+  /**
+   * lower quantile to calculate quantile range, shared by all features
+   * Default: 0.25
+   * @group param
+   */
+  val lower: DoubleParam = new DoubleParam(this, "lower",
+    "lower quantile to calculate quantile range",
+    ParamValidators.inRange(0, 1, false, false))
+
+  /** @group getParam */
+  def getLower: Double = $(lower)
+
+  setDefault(lower -> 0.25)
+
+  /**
+   * upper quantile to calculate quantile range, shared by all features
+   * Default: 0.75
+   * @group param
+   */
+  val upper: DoubleParam = new DoubleParam(this, "upper",
+    "upper quantile to calculate quantile range",
+    ParamValidators.inRange(0, 1, false, false))
+
+  /** @group getParam */
+  def getUpper: Double = $(upper)
+
+  setDefault(upper -> 0.75)
+
+  /**
+   * Whether to center the data with median before scaling.
+   * It will build a dense output, so take care when applying to sparse input.
+   * Default: false
+   * @group param
+   */
+  val withCentering: BooleanParam = new BooleanParam(this, "withCentering",
+    "Whether to center data with median")
+
+  /** @group getParam */
+  def getWithCentering: Boolean = $(withCentering)
+
+  setDefault(withCentering -> false)
+
+  /**
+   * Whether to scale the data to interquartile range.
+   * Default: true
+   * @group param
+   */
+  val withScaling: BooleanParam = new BooleanParam(this, "withScaling",
+    "Whether to scale the data to interquartile range")
+
+  /** @group getParam */
+  def getWithScaling: Boolean = $(withScaling)
+
+  setDefault(withScaling -> true)
+
+  /** Validates and transforms the input schema. */
+  protected def validateAndTransformSchema(schema: StructType): StructType = {
+    require($(lower) < $(upper), s"The specified lower quantile(${$(lower)}) is " +
+      s"larger or equal to upper quantile(${$(upper)})")
+    SchemaUtils.checkColumnType(schema, $(inputCol), new VectorUDT)
+    require(!schema.fieldNames.contains($(outputCol)),
+      s"Output column ${$(outputCol)} already exists.")
+    val outputFields = schema.fields :+ StructField($(outputCol), new VectorUDT, false)
+    StructType(outputFields)
+  }
+}
+
+
+/**
+ * Scale features using statistics that are robust to outliers.
+ * This Scaler removes the median and scales the data according to the quantile range
+ * (defaults to IQR: Interquartile Range). The IQR is the range between the 1st quartile
+ * (25th quantile) and the 3rd quartile (75th quantile).
+ * Centering and scaling happen independently on each feature by computing the relevant
+ * statistics on the samples in the training set. Median and interquartile range are then
+ * stored to be used on later data using the transform method.
+ * Standardization of a dataset is a common requirement for many machine learning estimators.
+ * Typically this is done by removing the mean and scaling to unit variance. However,
+ * outliers can often influence the sample mean / variance in a negative way.
+ * In such cases, the median and the interquartile range often give better results.
+ */
+@Since("3.0.0")
+class RobustScaler (override val uid: String)
+  extends Estimator[RobustScalerModel] with RobustScalerParams with DefaultParamsWritable {
+
+  def this() = this(Identifiable.randomUID("robustScal"))
+
+  /** @group setParam */
+  def setInputCol(value: String): this.type = set(inputCol, value)
+
+  /** @group setParam */
+  def setOutputCol(value: String): this.type = set(outputCol, value)
+
+  /** @group setParam */
+  def setLower(value: Double): this.type = set(lower, value)
+
+  /** @group setParam */
+  def setUpper(value: Double): this.type = set(upper, value)
+
+  /** @group setParam */
+  def setWithCentering(value: Boolean): this.type = set(withCentering, value)
+
+  /** @group setParam */
+  def setWithScaling(value: Boolean): this.type = set(withScaling, value)
+
+  override def fit(dataset: Dataset[_]): RobustScalerModel = {
+    transformSchema(dataset.schema, logging = true)
+
+    val summaries = dataset.select($(inputCol)).rdd.map {
+      case Row(vec: Vector) => vec
+    }.mapPartitions { iter =>
+      var localAgg: Array[QuantileSummaries] = null
+      while (iter.hasNext) {
+        val vec = iter.next()
+        if (localAgg == null) {
+          localAgg = Array.fill(vec.size)(
+            new QuantileSummaries(QuantileSummaries.defaultCompressThreshold, 0.001))
+        }
+        require(vec.size == localAgg.length)
+        var i = 0
+        while (i < vec.size) {
+          localAgg(i) = localAgg(i).insert(vec(i))
+          i += 1
+        }
+      }
+
+      if (localAgg != null) {
 
 Review comment:
   This might be clearer as:
   ```
   if (localAgg == null) {
     Iterator.empty
   } else {
     ...
   }
   ```

----------------------------------------------------------------
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