spark-reviews mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Yunni <...@git.apache.org>
Subject [GitHub] spark pull request #15148: [SPARK-5992][ML] Locality Sensitive Hashing
Date Wed, 05 Oct 2016 17:31:47 GMT
Github user Yunni commented on a diff in the pull request:

    https://github.com/apache/spark/pull/15148#discussion_r82027003
  
    --- Diff: mllib/src/main/scala/org/apache/spark/ml/feature/LSH.scala ---
    @@ -0,0 +1,334 @@
    +/*
    + * 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.util.Random
    +
    +import org.apache.spark.annotation.{Experimental, Since}
    +import org.apache.spark.ml.{Estimator, Model}
    +import org.apache.spark.ml.linalg.{Vector, VectorUDT}
    +import org.apache.spark.ml.param.{IntParam, ParamMap, ParamValidators}
    +import org.apache.spark.ml.param.shared.{HasInputCol, HasOutputCol}
    +import org.apache.spark.ml.util.SchemaUtils
    +import org.apache.spark.sql._
    +import org.apache.spark.sql.expressions.UserDefinedFunction
    +import org.apache.spark.sql.functions._
    +import org.apache.spark.sql.types._
    +
    +/**
    + * Params for [[LSH]].
    + */
    +@Experimental
    +@Since("2.1.0")
    +private[ml] trait LSHParams extends HasInputCol with HasOutputCol {
    +  /**
    +   * Param for the dimension of LSH OR-amplification.
    +   *
    +   * In this implementation, we use LSH OR-amplification to reduce the false negative
rate. The
    +   * higher the dimension is, the lower the false negative rate.
    +   * @group param
    +   */
    +  @Since("2.1.0")
    +  final val outputDim: IntParam = new IntParam(this, "outputDim", "output dimension,
where" +
    +    "increasing dimensionality lowers the false negative rate", ParamValidators.gt(0))
    +
    +  /** @group getParam */
    +  @Since("2.1.0")
    +  final def getOutputDim: Int = $(outputDim)
    +
    +  // TODO: Decide about this default. It should probably depend on the particular LSH
algorithm.
    +  setDefault(outputDim -> 1, outputCol -> "lshFeatures")
    +
    +  /**
    +   * Transform the Schema for LSH
    +   * @param schema The schema of the input dataset without outputCol
    +   * @return A derived schema with outputCol added
    +   */
    +  @Since("2.1.0")
    +  protected[this] final def validateAndTransformSchema(schema: StructType): StructType
= {
    +    SchemaUtils.appendColumn(schema, $(outputCol), new VectorUDT)
    +  }
    +}
    +
    +/**
    + * Model produced by [[LSH]].
    + */
    +@Experimental
    +@Since("2.1.0")
    +private[ml] abstract class LSHModel[T <: LSHModel[T]] extends Model[T] with LSHParams
{
    +  self: T =>
    +
    +  @Since("2.1.0")
    +  override def copy(extra: ParamMap): T = defaultCopy(extra)
    +
    +  /**
    +   * The hash function of LSH, mapping a predefined KeyType to a Vector
    +   * @return The mapping of LSH function.
    +   */
    +  @Since("2.1.0")
    +  protected[this] val hashFunction: Vector => Vector
    +
    +  /**
    +   * Calculate the distance between two different keys using the distance metric corresponding
    +   * to the hashFunction
    +   * @param x One of the point in the metric space
    +   * @param y Another the point in the metric space
    +   * @return The distance between x and y
    +   */
    +  @Since("2.1.0")
    +  protected[ml] def keyDistance(x: Vector, y: Vector): Double
    +
    +  /**
    +   * Calculate the distance between two different hash Vectors.
    +   *
    +   * @param x One of the hash vector
    +   * @param y Another hash vector
    +   * @return The distance between hash vectors x and y
    +   */
    +  @Since("2.1.0")
    +  protected[ml] def hashDistance(x: Vector, y: Vector): Double
    +
    +  @Since("2.1.0")
    +  override def transform(dataset: Dataset[_]): DataFrame = {
    +    transformSchema(dataset.schema, logging = true)
    +    val transformUDF = udf(hashFunction, new VectorUDT)
    +    dataset.withColumn($(outputCol), transformUDF(dataset($(inputCol))))
    +  }
    +
    +  @Since("2.1.0")
    +  override def transformSchema(schema: StructType): StructType = {
    +    validateAndTransformSchema(schema)
    +  }
    +
    +  /**
    +   * Given a large dataset and an item, approximately find at most k items which have
the closest
    +   * distance to the item. If the outputCol is missing, the method will transform the
data; if the
    +   * the outputCol exists, it will use the outputCol. This allows caching of the transformed
data
    +   * when necessary.
    +   *
    +   * This method implements two ways of fetching k nearest neighbors:
    +   *  - Single Probing: Fast, return at most k elements (Probing only one buckets)
    +   *  - Multiple Probing: Slow, return exact k elements (Probing multiple buckets close
to the key)
    +   *
    +   * @param dataset the dataset to search for nearest neighbors of the key
    +   * @param key Feature vector representing the item to search for
    +   * @param numNearestNeighbors The maximum number of nearest neighbors
    +   * @param singleProbing True for using Single Probing; false for multiple probing
    +   * @param distCol Output column for storing the distance between each result record
and the key
    +   * @return A dataset containing at most k items closest to the key. A distCol is added
to show
    +   *         the distance between each record and the key.
    +   */
    +  @Since("2.1.0")
    +  def approxNearestNeighbors(
    +      @Since("2.1.0") dataset: Dataset[_],
    +      @Since("2.1.0") key: Vector,
    +      @Since("2.1.0") numNearestNeighbors: Int,
    +      @Since("2.1.0") singleProbing: Boolean,
    +      @Since("2.1.0") distCol: String): Dataset[_] = {
    +    require(numNearestNeighbors > 0, "The number of nearest neighbors cannot be less
than 1")
    +    // Get Hash Value of the key
    +    val keyHash = hashFunction(key)
    +    val modelDataset: DataFrame = if (!dataset.columns.contains($(outputCol))) {
    +        transform(dataset)
    +      } else {
    +        dataset.toDF()
    +      }
    +
    +    // In the origin dataset, find the hash value that is closest to the key
    +    val hashDistUDF = udf((x: Vector) => hashDistance(x, keyHash), DataTypes.DoubleType)
    +    val hashDistCol = hashDistUDF(col($(outputCol)))
    +
    +    val modelSubset = if (singleProbing) {
    +      modelDataset.filter(hashDistCol === 0.0)
    +    } else {
    +      // Compute threshold to get exact k elements.
    +      val modelDatasetSortedByHash = modelDataset.sort(hashDistCol).limit(numNearestNeighbors)
    +      val thresholdDataset = modelDatasetSortedByHash.select(max(hashDistCol))
    +      val hashThreshold = thresholdDataset.take(1).head.getDouble(0)
    +
    +      // Filter the dataset where the hash value is less than the threshold.
    +      modelDataset.filter(hashDistCol <= hashThreshold)
    +    }
    +
    +    // Get the top k nearest neighbor by their distance to the key
    +    val keyDistUDF = udf((x: Vector) => keyDistance(x, key), DataTypes.DoubleType)
    +    val modelSubsetWithDistCol = modelSubset.withColumn(distCol, keyDistUDF(col($(inputCol))))
    +    modelSubsetWithDistCol.sort(distCol).limit(numNearestNeighbors)
    +  }
    +
    +  /**
    +   * Overloaded method for approxNearestNeighbors. Use Single Probing as default way
to search
    +   * nearest neighbors and "distCol" as default distCol.
    +   */
    +  @Since("2.1.0")
    +  def approxNearestNeighbors(
    +      @Since("2.1.0") dataset: Dataset[_],
    +      @Since("2.1.0") key: Vector,
    +      @Since("2.1.0") numNearestNeighbors: Int): Dataset[_] = {
    +    approxNearestNeighbors(dataset, key, numNearestNeighbors, true, "distCol")
    +  }
    +
    +  /**
    +   * Preprocess step for approximate similarity join. Transform and explode the outputCol
to
    +   * explodeCols.
    +   * @param dataset The dataset to transform and explode.
    +   * @param explodeCols The alias for the exploded columns, must be a seq of two strings.
    +   * @return A dataset containing idCol, inputCol and explodeCols
    +   */
    +  @Since("2.1.0")
    +  private[this] def processDataset(dataset: Dataset[_], explodeCols: Seq[String]): Dataset[_]
= {
    +    require(explodeCols.size == 2, "explodeCols must be two strings.")
    +    val vectorToMap: UserDefinedFunction = udf((x: Vector) => x.asBreeze.iterator.toMap,
    +      MapType(DataTypes.IntegerType, DataTypes.DoubleType))
    +    val modelDataset: DataFrame = if (!dataset.columns.contains($(outputCol))) {
    +      transform(dataset)
    +    } else {
    +      dataset.toDF()
    +    }
    +    modelDataset.select(col("*"), explode(vectorToMap(col($(outputCol)))).as(explodeCols))
    +  }
    +
    +  /**
    +   * Recreate a column using the same column name but different attribute id. Used in
approximate
    +   * similarity join.
    +   * @param dataset The dataset where a column need to recreate
    +   * @param colName The name of the column to recreate
    +   * @param tmpColName A temporary column name which does not conflict with existing
columns
    +   * @return
    +   */
    +  @Since("2.1.0")
    +  private[this] def recreateCol(
    +      @Since("2.1.0") dataset: Dataset[_],
    +      @Since("2.1.0") colName: String,
    +      @Since("2.1.0") tmpColName: String): Dataset[_] = {
    +    dataset
    +      .withColumnRenamed(colName, tmpColName)
    +      .withColumn(colName, col(tmpColName))
    +      .drop(tmpColName)
    +  }
    +
    +  /**
    +   * Join two dataset to approximately find all pairs of records whose distance are smaller
    +   * than the threshold.
    +   * @param datasetA One of the datasets to join
    +   * @param datasetB Another dataset to join
    +   * @param threshold The threshold for the distance of record pairs
    +   * @param distCol Output column for storing the distance between each result record
and the key
    +   * @return A joined dataset containing pairs of records. A distCol is added to show
the distance
    +   *         between each pair of records.
    +   */
    +  @Since("2.1.0")
    +  def approxSimilarityJoin(
    +      @Since("2.1.0") datasetA: Dataset[_],
    +      @Since("2.1.0") datasetB: Dataset[_],
    +      @Since("2.1.0") threshold: Double,
    +      @Since("2.1.0") distCol: String): Dataset[_] = {
    +
    +    val explodeCols = Seq("lsh#entry", "lsh#hashValue")
    --- End diff --
    
    Yes, I used this kind of code in early implementations:
    `df1.join(df2, shareHashBucket(df1($(outputCol)), df2($(outputCol))))`
    However, it seems this is broadcast join + filter. I am wondering if explode is more feasible
since it's doing hash join?


---
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 infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

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


Mime
View raw message