Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
Sep 19, 2016
d389159
Code review comments. A new unit test of k nearest neighbor for large k
Sep 19, 2016
19d012a
(1) Refactor hashDistCol for nearest neighbor search. (2) Add scalado…
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
Oct 4, 2016
df19886
Code review comments
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…
Oct 10, 2016
2c95e5c
Code review comments
Yunni Oct 11, 2016
fb120af
SignRandomProjection: LSH Classes for cosine distance metrics
Oct 11, 2016
19f6d89
Change hashFunctions to Arrays
Oct 11, 2016
1b63173
BitSampling: LSH Class for Hamming Distance
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…
Oct 27, 2016
20a9ebf
Change a few Since annotations
Oct 27, 2016
9bb3fd6
Code Review Comments: (1) Remove all Since in LSH (2) Add doc on hash…
Oct 27, 2016
9a3704c
Organize the scaladoc
Oct 27, 2016
6cda936
Remove default values for outputCol
Oct 28, 2016
97e1238
Remove default values for outputCol
Oct 28, 2016
3570845
Add more scaladoc
Oct 28, 2016
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Implement approxSimilarityJoin(). Remove modelDataset and distCol as …
…discussed in the Design Doc.
  • Loading branch information
Yunni committed Sep 19, 2016
commit c693f5b2deec621bf8dbf617d1fb2367bf8b3397
120 changes: 85 additions & 35 deletions mllib/src/main/scala/org/apache/spark/ml/lsh/LSH.scala
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,16 @@

package org.apache.spark.ml.lsh

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, Param, ParamMap, ParamValidators}
import org.apache.spark.ml.param.{IntParam, ParamMap, ParamValidators}
import org.apache.spark.ml.param.shared.{HasInputCol, HasOutputCol}
import org.apache.spark.sql._
import org.apache.spark.sql.expressions.UserDefinedFunction
import org.apache.spark.sql.functions._
import org.apache.spark.sql.types.{DataTypes, StructField, StructType}
import org.apache.spark.sql.types._

/**
* Params for [[LSH]].
Expand All @@ -37,25 +40,13 @@ private[ml] trait LSHParams extends HasInputCol with HasOutputCol {
final val outputDim: IntParam = new IntParam(this, "outputDim", "output dimension",
ParamValidators.gt(0))

/**
* Param for distance column name.
*
* @group param
*/
final val distCol: Param[String] = new Param[String](this, "distCol", "distance column name")

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

/** @group getParam */
final def getDistCol: String = $(distCol)

setDefault(outputDim -> 1)

setDefault(outputCol -> "lsh_output")

setDefault(distCol -> "lsh_distance")

/**
* Transform the Schema for LSH
* @param schema The schema of the input dataset without outputCol
Expand All @@ -74,9 +65,6 @@ private[ml] trait LSHParams extends HasInputCol with HasOutputCol {
abstract class LSHModel[KeyType, T <: LSHModel[KeyType, T]] private[ml]
extends Model[T] with LSHParams {
override def copy(extra: ParamMap): T = defaultCopy(extra)

protected var modelDataset: DataFrame = null

/**
* :: DeveloperApi ::
*
Expand Down Expand Up @@ -116,8 +104,7 @@ abstract class LSHModel[KeyType, T <: LSHModel[KeyType, T]] private[ml]
override def transform(dataset: Dataset[_]): DataFrame = {
transformSchema(dataset.schema, logging = true)
val transformUDF = udf(hashFunction, new VectorUDT)
modelDataset = dataset.withColumn($(outputCol), transformUDF(dataset($(inputCol))))
modelDataset
dataset.withColumn($(outputCol), transformUDF(dataset($(inputCol))))
}

/**
Expand All @@ -132,26 +119,23 @@ abstract class LSHModel[KeyType, T <: LSHModel[KeyType, T]] private[ml]
transformLSHSchema(schema)
}

/**
* Get the dataset inside the model. This is used in approximate similarity join or when user
* wants to run their own algorithm on the LSH dataset.
* @return The dataset inside the model
*/
def getModelDataset: Dataset[_] = modelDataset

/**
* Given a large dataset and an item, approximately find at most k items which have the closest
* distance to the item.
* @param key The key to hash for the item
* @param k The maximum number of items closest to the key
* @return A dataset containing at most k items closest to the key.
* @param distCol The column to store the distance between pairs
* @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.
*/
def approxNearestNeighbors(key: KeyType, k: Int = 1): Dataset[_] = {
def approxNearestNeighbors(dataset: Dataset[_], key: KeyType, k: Int = 1,
distCol: String = "distance"): Dataset[_] = {
if (k < 1) {
Copy link
Member

Choose a reason for hiding this comment

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

Usually we use assert for this. And more informative error message might be The number of nearest neighbors cannot be less than 1.

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.

throw new Exception(s"Invalid number of nearest neighbors $k")
}
// Get Hash Value of the key v
val keyHash = hashFunction(key)
val modelDataset = transform(dataset)

// In the origin dataset, find the hash value u that is closest to v
val hashDistUDF = udf((x: Vector) => hashDistance(x, keyHash), DataTypes.DoubleType)
Expand All @@ -163,8 +147,79 @@ abstract class LSHModel[KeyType, T <: LSHModel[KeyType, T]] private[ml]

// Get the top k nearest neighbor by their distance to the key
val keyDistUDF = udf((x: KeyType) => keyDistance(x, key), DataTypes.DoubleType)
val modelSubsetWithDistCol = modelSubset.withColumn($(distCol), keyDistUDF(col($(inputCol))))
modelSubsetWithDistCol.sort($(distCol)).limit(k)
val modelSubsetWithDistCol = modelSubset.withColumn(distCol, keyDistUDF(col($(inputCol))))
modelSubsetWithDistCol.sort(distCol).limit(k)
}

/**
* 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
*/
private[this] def processDataset(dataset: Dataset[_], explodeCols: Seq[String]): Dataset[_] = {
if (explodeCols.size != 2) {
throw new Exception("explodeCols must be two strings.")
}
val vectorToMap: UserDefinedFunction = udf((x: Vector) => x.asBreeze.iterator.toMap,
MapType(DataTypes.IntegerType, DataTypes.DoubleType))
transform(dataset)
.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
*/
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 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 The column to store the distance between pairs
* @return A joined dataset containing pairs of records. A distCol is added to show the distance
* between each pair of records.
*/
def approxSimilarityJoin(datasetA: Dataset[_], datasetB: Dataset[_], threshold: Double,
distCol: String = "distance"): Dataset[_] = {

val explodeCols = Seq("lsh#entry", "lsh#hashValue")
val explodedA = processDataset(datasetA, explodeCols)

// If this is a self join, we need to recreate the inputCol of datasetB to avoid ambiguity.
Copy link
Member

Choose a reason for hiding this comment

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

Do we need this? I think we already do dedup operation in Analyzer for self-join.

Copy link
Member

Choose a reason for hiding this comment

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

Got it. You want to access inputCol from both left and right sides.

Copy link
Member

Choose a reason for hiding this comment

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

Once #14719 is merged, I think we can skip this redundant operation.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Added a TODO.

val explodedB = if (datasetA != datasetB) {
processDataset(datasetB, explodeCols)
} else {
val recreatedB = recreateCol(datasetB, $(inputCol), s"${$(inputCol)}#${Random.nextString(5)}")
processDataset(recreatedB, explodeCols)
}

// Do a hash join on where the exploded hash values are equal.
val joinedDataset = explodedA.join(explodedB, explodeCols)
.drop(explodeCols: _*)

// Add a new column to store the distance of the two records.
val distUDF = udf((x: KeyType, y: KeyType) => keyDistance(x, y), DataTypes.DoubleType)
val joinedDatasetWithDist = joinedDataset.select(col("*"),
distUDF(explodedA($(inputCol)), explodedB($(inputCol))).as(distCol)
)

// Filter the joined datasets where the distance are smaller than the threshold.
joinedDatasetWithDist.distinct().filter(col(distCol) < threshold)
Copy link
Member

Choose a reason for hiding this comment

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

I think do distinct after filter should be better as you will filter out most of records.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Very good point. Done.

}
}

Expand All @@ -178,9 +233,6 @@ abstract class LSH[KeyType, T <: LSHModel[KeyType, T]] extends Estimator[T] with
/** @group setParam */
def setOutputDim(value: Int): this.type = set(outputDim, value)

/** @group setParam */
def setDistCol(value: String): this.type = set(distCol, value)

/**
* :: DeveloperApi ::
*
Expand All @@ -201,8 +253,6 @@ abstract class LSH[KeyType, T <: LSHModel[KeyType, T]] extends Estimator[T] with
val inputDim = dataset.select(col($(inputCol))).head().get(0).asInstanceOf[Vector].size
val model = createRawLSHModel(inputDim).setParent(this)
copyValues(model)
model.transform(dataset)
model
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ class RandomProjectionSuite extends SparkFunSuite with MLlibTestSparkContext {

val model = rp.fit(df)

model.getModelDataset.show()
model.approxNearestNeighbors(Vectors.dense(1.2, 3.4), k = 20).show()
model.transform(df).show()
model.approxNearestNeighbors(df, Vectors.dense(1.2, 3.4), k = 20).show()
model.approxSimilarityJoin(df, df, 1.1).filter("distance != 0.0").show()
}
}