Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SPARK-5992][ML] Locality Sensitive Hashing #15148

Closed
wants to merge 46 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
46 commits
Select commit Hold shift + click to select a range
1bbd48c
First Commit of LSH function implementation. Implement basic Estimato…
Yunni Sep 13, 2016
ca46d82
Implementation of Approximate Nearest Neighbors. Add distCol as anoth…
Yunni Sep 13, 2016
c693f5b
Implement approxSimilarityJoin(). Remove modelDataset and distCol as …
Yunni Sep 15, 2016
c9ee0f9
Add test utility method to check LSH property. Tested on random proje…
Yunni Sep 19, 2016
fc838e0
Add testing utility for approximate nearest neighbor. Run the testing…
Yunni Sep 19, 2016
aa138e8
Add testing utility for approximate similarity join. Run the testing …
Yunni Sep 19, 2016
bbcbcf0
Code review comments. A new unit test of k nearest neighbor for large k
Yunni Sep 19, 2016
d389159
Code review comments. A new unit test of k nearest neighbor for large k
Yunni Sep 19, 2016
19d012a
(1) Refactor hashDistCol for nearest neighbor search. (2) Add scalado…
Yunni Sep 19, 2016
269c8c9
Code Review comments: (1) Rewrite hashDistance (2) Move the lsh packa…
Yunni Sep 20, 2016
9065f7d
Add comment to clarify the implementation of RandomProjection
Yunni Sep 20, 2016
d22dff4
Implementation of MinHash with unit tests
Yunni Sep 26, 2016
7e6d938
Add options for Probing Single/Multiple bucket(s) in approxNearestNei…
Yunni Sep 26, 2016
0fad3ef
Allow users to transform datasets themselves before doing approxNeare…
Yunni Sep 26, 2016
0080b87
Generalize Input types to Vector. For MinHash, use Sparse Vectors to …
Yunni Sep 28, 2016
a1c344b
Code Review Comments
Yunni Sep 28, 2016
396ad60
Bug fixed. Typo of distCol
Yunni Sep 28, 2016
b79ebbd
Fix Jenkins Build. Explicitly annotate type of modelDataset
Yunni Sep 28, 2016
7936315
Move all code to org.apache.spark.ml.feature
Yunni Sep 28, 2016
f805658
Tune threshold for approxNearestNeighbors unit tests
Yunni Sep 28, 2016
8f04ee8
Fix import ordering
Yunni Sep 28, 2016
f82f3fe
Add scaladoc for overloaded methods
Yunni Sep 28, 2016
ccd98f7
Code review comments
Yunni Oct 4, 2016
69efc84
Move private[ml] to MinHash constructor
Yunni Oct 4, 2016
eced98d
Detailed doc on bucketLength. Move private[ml] to Model constructor
Yunni Oct 4, 2016
3487bcc
Tune threshold for MinHash
Yunni Oct 4, 2016
df19886
Code review comments
Yunni Oct 5, 2016
efe323c
Code Review Comments
Yunni Oct 10, 2016
142d8e9
Revert unrelated changes
Yunni Oct 10, 2016
40d1f1b
Code review comments for MinHash: (1) Compute unionSize based on setS…
Yunni Oct 10, 2016
2c95e5c
Code review comments
Yunni Oct 11, 2016
fb120af
SignRandomProjection: LSH Classes for cosine distance metrics
Yunni Oct 11, 2016
19f6d89
Change hashFunctions to Arrays
Yunni Oct 11, 2016
1b63173
BitSampling: LSH Class for Hamming Distance
Yunni Oct 12, 2016
126d980
Merge remote-tracking branch 'upstream/master' into SPARK-5992-yunn-lsh
Yunni Oct 13, 2016
a35e261
Move distinct() before calculating the distance to improve running time
Yunni Oct 13, 2016
66d553a
For similarity join, expose leftCol and rightCol as parameters
Yunni Oct 17, 2016
cad4ecb
Code Review comments: (1) Save BitSampling and SignRandomProjection f…
Yunni Oct 22, 2016
e14f73e
(1) Reset all random seed != 0 (2) Add docstring about the output sch…
Yunni Oct 23, 2016
1c4b9fb
(1) Add readers/writers (2) Change unit tests thresholds to more rebo…
Yunni Oct 27, 2016
20a9ebf
Change a few Since annotations
Yunni Oct 27, 2016
9bb3fd6
Code Review Comments: (1) Remove all Since in LSH (2) Add doc on hash…
Yunni Oct 27, 2016
9a3704c
Organize the scaladoc
Yunni Oct 27, 2016
6cda936
Remove default values for outputCol
Yunni Oct 28, 2016
97e1238
Remove default values for outputCol
Yunni Oct 28, 2016
3570845
Add more scaladoc
Yunni Oct 28, 2016
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
313 changes: 313 additions & 0 deletions mllib/src/main/scala/org/apache/spark/ml/feature/LSH.scala
@@ -0,0 +1,313 @@
/*
* 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.ml.{Estimator, Model}
import org.apache.spark.ml.linalg.{Vector, VectorUDT}
import org.apache.spark.ml.param.{IntParam, ParamValidators}
import org.apache.spark.ml.param.shared.{HasInputCol, HasOutputCol}
import org.apache.spark.ml.util._
import org.apache.spark.sql._
import org.apache.spark.sql.functions._
import org.apache.spark.sql.types._

/**
* Params for [[LSH]].
*/
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
*/
final val outputDim: IntParam = new IntParam(this, "outputDim", "output dimension, where" +
"increasing dimensionality lowers the false negative rate, and decreasing dimensionality" +
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does increasing dimensionality lower the false negative rate?
I think increasing dimensionality should lower false positive rate, right?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No. Since we are implementing OR-amplification, increasing dimensionality lower the false negative rate.

In AND-amplification, increasing dimensionality will lower the false positive rate.

" improves the running performance", ParamValidators.gt(0))

/** @group getParam */
final def getOutputDim: Int = $(outputDim)

setDefault(outputDim -> 1)

/**
* Transform the Schema for LSH
* @param schema The schema of the input dataset without [[outputCol]]
* @return A derived schema with [[outputCol]] added
*/
protected[this] final def validateAndTransformSchema(schema: StructType): StructType = {
SchemaUtils.appendColumn(schema, $(outputCol), new VectorUDT)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The inputCol cannot be checked here since its type may be algorithm-dependent, but it should be checked in transformSchema or a similar validateAndTransformSchema in the MinHash and RP algorithms below.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, I did not get it, there is no check for inputCol here.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I meant that transformSchema should validate that inputCol has the correct DataType. That can be done by putting a line in each algorithm's transformSchema.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see. I will add that.

}
}

/**
* Model produced by [[LSH]].
*/
private[ml] abstract class LSHModel[T <: LSHModel[T]]
extends Model[T] with LSHParams with MLWritable {
self: T =>

/**
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style: newline between methods

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

* The hash function of LSH, mapping a predefined KeyType to a Vector
* @return The mapping of LSH function.
*/
protected[ml] val hashFunction: Vector => Vector

/**
* Calculate the distance between two different keys using the distance metric corresponding
* to the hashFunction
* @param x One input vector in the metric space
* @param y One input vector in the metric space
* @return The distance between x and y
*/
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
*/
protected[ml] def hashDistance(x: Vector, y: Vector): Double

override def transform(dataset: Dataset[_]): DataFrame = {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need to copy documentation for overridden methods, unless the docs are specialized for this class

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

transformSchema(dataset.schema, logging = true)
val transformUDF = udf(hashFunction, new VectorUDT)
dataset.withColumn($(outputCol), transformUDF(dataset($(inputCol))))
}

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
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This method needs to document that it checks for the outputCol and transforms the data if it is missing, allowing caching of the transformed data when necessary.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

* distance to the item. If the [[outputCol]] is missing, the method will transform the data; if
* 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 row 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 row and the key.
*/
def approxNearestNeighbors(
dataset: Dataset[_],
key: Vector,
numNearestNeighbors: Int,
singleProbing: Boolean,
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)
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The above section looks weird for me.

You sort modelDataset by hash distance and get the top k items. From the top k items, you get the largest hash distance. Then you use this largest hash distance to filter modelDataset again.

Isn't it the same as modelDataset.sort(hashDistCol).limit(numNearestNeighbors)?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh. I see. nvm.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wait, now I'm looking at this. Aren't they the same?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not really, modelDataset.filter(hashDistCol === 0.0) might return < k rows but the second method will guarantee >= k rows are returned

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, no I mean this: modelDatasetSortedByHash in line 143 and modelDataset.filter(hashDistCol <= hashThreshold) in line 148 are the same, I believe.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I could see one reason for computing a threshold: It gets some expensive computation done, which will help users who are careless about caching the result Dataset before querying it. But for careful users, it does mean a little extra computation. I'm OK either way.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

L143-145 is for computing the threshold for hashValues.
L148 is getting data in all buckets which distance <= threshold.

L143 and L148 are different on the last bucket(distance = threshold). In some cases like all results are in the last bucket, they could be very different.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, good point about the last bucket


// 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.
*/
def approxNearestNeighbors(
dataset: Dataset[_],
key: Vector,
numNearestNeighbors: Int): Dataset[_] = {
approxNearestNeighbors(dataset, key, numNearestNeighbors, true, "distCol")
}

/**
* Preprocess step for approximate similarity join. Transform and explode the [[outputCol]] to
* two explodeCols: entry and value. "entry" is the index in hash vector, and "value" is the
* value of corresponding value of the index in the vector.
*
* @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
*/
private[this] def processDataset(
dataset: Dataset[_],
inputName: String,
explodeCols: Seq[String]): Dataset[_] = {
require(explodeCols.size == 2, "explodeCols must be two strings.")
val vectorToMap = 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(
struct(col("*")).as(inputName),
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
*/
private[this] def recreateCol(
dataset: Dataset[_],
colName: String,
tmpColName: String): Dataset[_] = {
dataset
.withColumnRenamed(colName, tmpColName)
.withColumn(colName, col(tmpColName))
.drop(tmpColName)
}

/**
* Join two dataset to approximately find all pairs of rows whose distance are smaller than
* the threshold. If the [[outputCol]] is missing, the method will transform the data; if the
* [[outputCol]] exists, it will use the [[outputCol]]. This allows caching of the transformed
* data when necessary.
*
* @param datasetA One of the datasets to join
* @param datasetB Another dataset to join
* @param threshold The threshold for the distance of row pairs
* @param distCol Output column for storing the distance between each result row and the key
* @return A joined dataset containing pairs of rows. The original rows are in columns
* "datasetA" and "datasetB", and a distCol is added to show the distance of each pair
*/
def approxSimilarityJoin(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This too should document that it transforms data if needed, just like approxNearestNeighbors.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

datasetA: Dataset[_],
datasetB: Dataset[_],
threshold: Double,
distCol: String): Dataset[_] = {

val leftColName = "datasetA"
val rightColName = "datasetB"
val explodeCols = Seq("entry", "hashValue")
val explodedA = processDataset(datasetA, leftColName, explodeCols)

// If this is a self join, we need to recreate the inputCol of datasetB to avoid ambiguity.
// TODO: Remove recreateCol logic once SPARK-17154 is resolved.
val explodedB = if (datasetA != datasetB) {
processDataset(datasetB, rightColName, explodeCols)
} else {
val recreatedB = recreateCol(datasetB, $(inputCol), s"${$(inputCol)}#${Random.nextString(5)}")
processDataset(recreatedB, rightColName, explodeCols)
}

// Do a hash join on where the exploded hash values are equal.
val joinedDataset = explodedA.join(explodedB, explodeCols)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With this approach, we would expect the false negative will be high, right?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Compare to what approach?
The false negative is controlled by outputDim, which is the dimension of amplification. The higher the outputDim, the lower the false negative rate.

Copy link
Member

@viirya viirya Oct 10, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have a question in this part, maybe you can clarify it more.

From your implementation, looks like you explode the hash vector to a map of (dimension, value). Then you join two exploded datasets. So we are expecting the matched records from two datasets which have the same values at the same dimensions, is it right?

Is it OR-amplification? As two records in exploded dataset A and B, must have the same values at all dimensions, so they can be matched by joining. Looks it is an AND relation (i.e., dimension 1 AND dimension 2 AND ... dimension n all matching) not an OR relation (i.e., dimension 1 matching but all other dimensions not matching).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As two records in exploded dataset A and B, must have the same values at all dimensions

Not exactly. In the exploded dataset, each row represents one dimension for one original record. For example,

hashFeature: (1.0, 2.0) -> hashVector: (1.4, 2.5, 3.6, 4.7)

will be explode to

hashFeature: (1.0, 2.0) -> (0, 1.4)
hashFeature: (1.0, 2.0) -> (1, 2.5)
hashFeature: (1.0, 2.0) -> (2, 3.6)
hashFeature: (1.0, 2.0) -> (3, 4.7)

Join two exploded datasets will match 1 dimension for each pair in each row.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for clarifying it!

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One concern I think is if your data set is big, after exploding it for hash dimensions, the size of data set will grow accordingly.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, the exploded dataset size is n * d, where n is the input data size, d is the output dimension.

The exploded datasets enable us to do inner join, which should be more feasible than full join.

.drop(explodeCols: _*).distinct()

// Add a new column to store the distance of the two rows.
val distUDF = udf((x: Vector, y: Vector) => keyDistance(x, y), DataTypes.DoubleType)
val joinedDatasetWithDist = joinedDataset.select(col("*"),
distUDF(col(s"$leftColName.${$(inputCol)}"), col(s"$rightColName.${$(inputCol)}")).as(distCol)
)

// Filter the joined datasets where the distance are smaller than the threshold.
joinedDatasetWithDist.filter(col(distCol) < threshold)
}

/**
* Overloaded method for approxSimilarityJoin. Use "distCol" as default distCol.
*/
def approxSimilarityJoin(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The default distCol needs to be documented

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Scaladoc added.

datasetA: Dataset[_],
datasetB: Dataset[_],
threshold: Double): Dataset[_] = {
approxSimilarityJoin(datasetA, datasetB, threshold, "distCol")
}
}

/**
* Locality Sensitive Hashing for different metrics space. Support basic transformation with a new
* hash column, approximate nearest neighbor search with a dataset and a key, and approximate
* similarity join of two datasets.
*
* This LSH class implements OR-amplification: more than 1 hash functions can be chosen, and each
* input vector are hashed by all hash functions. Two input vectors are defined to be in the same
* bucket as long as ANY one of the hash value matches.
*
* References:
* (1) Gionis, Aristides, Piotr Indyk, and Rajeev Motwani. "Similarity search in high dimensions
* via hashing." VLDB 7 Sep. 1999: 518-529.
* (2) Wang, Jingdong et al. "Hashing for similarity search: A survey." arXiv preprint
* arXiv:1408.2927 (2014).
*/
private[ml] abstract class LSH[T <: LSHModel[T]]
extends Estimator[T] with LSHParams with DefaultParamsWritable {
self: Estimator[T] =>

/** @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 setOutputDim(value: Int): this.type = set(outputDim, value)

/**
* Validate and create a new instance of concrete LSHModel. Because different LSHModel may have
* different initial setting, developer needs to define how their LSHModel is created instead of
* using reflection in this abstract class.
* @param inputDim The dimension of the input dataset
* @return A new LSHModel instance without any params
*/
protected[this] def createRawLSHModel(inputDim: Int): T

override def fit(dataset: Dataset[_]): T = {
transformSchema(dataset.schema, logging = true)
val inputDim = dataset.select(col($(inputCol))).head().get(0).asInstanceOf[Vector].size
Copy link
Member

@jkbradley jkbradley Oct 4, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

get[Vector](0)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd call transformSchema here before extracting inputDim

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

val model = createRawLSHModel(inputDim).setParent(this)
copyValues(model)
}
}