Github user mengxr commented on a diff in the pull request:

    https://github.com/apache/spark/pull/7987#discussion_r39621892
  
    --- Diff: 
mllib/src/main/scala/org/apache/spark/ml/feature/Interaction.scala ---
    @@ -0,0 +1,243 @@
    +/*
    + * 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.{ArrayBuffer, ArrayBuilder}
    +
    +import org.apache.spark.SparkException
    +import org.apache.spark.annotation.Experimental
    +import org.apache.spark.ml.attribute._
    +import org.apache.spark.ml.param._
    +import org.apache.spark.ml.param.shared._
    +import org.apache.spark.ml.util.Identifiable
    +import org.apache.spark.ml.{Estimator, Model, Pipeline, PipelineModel, 
PipelineStage, Transformer}
    +import org.apache.spark.mllib.linalg.{Vector, VectorUDT, Vectors}
    +import org.apache.spark.sql.{DataFrame, Row}
    +import org.apache.spark.sql.functions._
    +import org.apache.spark.sql.types._
    +
    +/**
    + * :: Experimental ::
    + * Implements the transforms required for R-style feature interactions. 
This transformer takes in
    + * Double and Vector columns and outputs a flattened vector of 
interactions. To handle interaction,
    + * we first one-hot encode nominal columns. Then, a vector of all their 
cross-products is
    + * produced.
    + *
    + * For example, given the inputs Double(2), Vector(3, 4), the result would 
be Vector(6, 8) if
    + * all columns were numeric. If the first input was nominal with four 
different values, the result
    + * would then be Vector(0, 0, 0, 0, 3, 4, 0, 0).
    + *
    + * See 
https://stat.ethz.ch/R-manual/R-devel/library/base/html/formula.html for more
    + * information about interactions in R formulae.
    + */
    +@Experimental
    +class Interaction(override val uid: String) extends Transformer
    +  with HasInputCols with HasOutputCol {
    +
    +  def this() = this(Identifiable.randomUID("interaction"))
    +
    +  /** @group setParam */
    +  def setInputCols(values: Array[String]): this.type = set(inputCols, 
values)
    +
    +  /** @group setParam */
    +  def setOutputCol(value: String): this.type = set(outputCol, value)
    +
    +  // optimistic schema; does not contain any ML attributes
    +  override def transformSchema(schema: StructType): StructType = {
    +    checkParams()
    +    StructType(schema.fields :+ StructField($(outputCol), new VectorUDT, 
true))
    +  }
    +
    +  override def transform(dataset: DataFrame): DataFrame = {
    +    checkParams()
    +    val fieldIterators = getIterators(dataset)
    +
    +    def interactFunc = udf { row: Row =>
    +      var indices = ArrayBuilder.make[Int]
    +      var values = ArrayBuilder.make[Double]
    +      var size = 1
    +      indices += 0
    +      values += 1.0
    +      var fieldIndex = row.length - 1
    +      while (fieldIndex >= 0) {
    +        val prevIndices = indices.result()
    +        val prevValues = values.result()
    +        val prevSize = size
    +        val currentIterator = fieldIterators(fieldIndex)
    +        indices = ArrayBuilder.make[Int]
    +        values = ArrayBuilder.make[Double]
    +        size *= currentIterator.size
    +        currentIterator.foreachActive(row(fieldIndex), (i, a) => {
    +          var j = 0
    +          while (j < prevIndices.length) {
    +            indices += prevIndices(j) + i * prevSize
    +            values += prevValues(j) * a
    +            j += 1
    +          }
    +        })
    +        fieldIndex -= 1
    +      }
    +      Vectors.sparse(size, indices.result(), values.result()).compressed
    +    }
    +
    +    val args = $(inputCols).map { c =>
    +      dataset.schema(c).dataType match {
    +        case DoubleType => dataset(c)
    +        case _: VectorUDT => dataset(c)
    +        case _: NumericType | BooleanType => dataset(c).cast(DoubleType)
    +      }
    +    }
    +    val attrs = generateAttrs($(inputCols).map(col => dataset.schema(col)))
    +    dataset.select(
    +      col("*"),
    +      interactFunc(struct(args: _*)).as($(outputCol), attrs.toMetadata()))
    +  }
    +
    +  private def getIterators(dataset: DataFrame): Array[EncodingIterator] = {
    +    def getCardinality(attr: Attribute): Int = {
    +      attr match {
    +        case nominal: NominalAttribute =>
    +          nominal.getNumValues.getOrElse(
    +            throw new SparkException("Nominal fields must have attr 
numValues defined."))
    +        case _ =>
    +          0  // treated as numeric
    +      }
    +    }
    +    $(inputCols).map { col =>
    +      val field = dataset.schema(col)
    +      val cardinalities = field.dataType match {
    +        case _: NumericType | BooleanType =>
    +          Array(getCardinality(Attribute.fromStructField(field)))
    +        case _: VectorUDT =>
    +          val attrs = 
AttributeGroup.fromStructField(field).attributes.getOrElse(
    +            throw new SparkException("Vector attributes must be defined 
for interaction."))
    +          attrs.map(getCardinality).toArray
    +      }
    +      new EncodingIterator(cardinalities)
    +    }.toArray
    +  }
    +
    +  private def generateAttrs(schema: Seq[StructField]): AttributeGroup = {
    --- End diff --
    
    * missing API doc
    * `schema` -> `fields` (`schema` should be a `StructType`)


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at [email protected] or file a JIRA ticket
with INFRA.
---

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

Reply via email to