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
Code review comments
  • Loading branch information
Yun Ni committed Oct 5, 2016
commit df198868f8505a307ac2bc1af33ff345f5207be6
91 changes: 48 additions & 43 deletions mllib/src/main/scala/org/apache/spark/ml/feature/LSH.scala
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ private[ml] trait LSHParams extends HasInputCol with HasOutputCol {
*/
@Since("2.1.0")
Copy link
Member

Choose a reason for hiding this comment

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

These Since annotations within LSHParams, LSH, and LSHModel need to be removed as well. They are correct now, but if a new subclass is added in say spark 2.2, then they will be incorrect for that subclass. Sorry for misdirecting before!

final val outputDim: IntParam = new IntParam(this, "outputDim", "output dimension, where" +
"increasing dimensionality lowers the false negative rate", ParamValidators.gt(0))
"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 */
@Since("2.1.0")
Expand All @@ -56,8 +57,8 @@ private[ml] trait LSHParams extends HasInputCol with HasOutputCol {

/**
* Transform the Schema for LSH
* @param schema The schema of the input dataset without outputCol
* @return A derived schema with outputCol added
* @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 = {
Expand Down Expand Up @@ -117,9 +118,9 @@ private[ml] abstract class LSHModel[T <: LSHModel[T]] extends Model[T] with LSHP

/**
* 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
* the outputCol exists, it will use the outputCol. This allows caching of the transformed data
* when necessary.
* 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)
Expand All @@ -135,11 +136,11 @@ private[ml] abstract class LSHModel[T <: LSHModel[T]] extends Model[T] with LSHP
*/
@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[_] = {
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)
Expand Down Expand Up @@ -177,21 +178,24 @@ private[ml] abstract class LSHModel[T <: LSHModel[T]] extends Model[T] with LSHP
*/
@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[_] = {
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
* Preprocess step for approximate similarity join. Transform and explode the [[outputCol]] to
* explodeCols.
Copy link
Member

Choose a reason for hiding this comment

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

Can you explain more about what the preprocess is? At least add comment about the meanings of each exploded column.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

More details added.

* @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[_] = {
private[this] def processDataset(
dataset: Dataset[_],
inputName: String,
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))
Expand All @@ -200,7 +204,9 @@ private[ml] abstract class LSHModel[T <: LSHModel[T]] extends Model[T] with LSHP
} else {
dataset.toDF()
}
modelDataset.select(col("*"), explode(vectorToMap(col($(outputCol)))).as(explodeCols))
modelDataset.select(
struct(col("*")).as(inputName),
explode(vectorToMap(col($(outputCol)))).as(explodeCols))
}

/**
Expand All @@ -213,18 +219,21 @@ private[ml] abstract class LSHModel[T <: LSHModel[T]] extends Model[T] with LSHP
*/
@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: 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.
* Join two dataset to approximately find all pairs of records 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 record pairs
Expand All @@ -234,21 +243,22 @@ private[ml] abstract class LSHModel[T <: LSHModel[T]] extends Model[T] with LSHP
*/
@Since("2.1.0")
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.

@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[_] = {
datasetA: Dataset[_],
datasetB: Dataset[_],
threshold: Double,
distCol: String): Dataset[_] = {

val explodeCols = Seq("lsh#entry", "lsh#hashValue")
val explodedA = processDataset(datasetA, explodeCols)
val explodeCols = Seq("entry", "hashValue")
val inputName = "input"
val explodedA = processDataset(datasetA, inputName, 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, explodeCols)
processDataset(datasetB, inputName, explodeCols)
} else {
val recreatedB = recreateCol(datasetB, $(inputCol), s"${$(inputCol)}#${Random.nextString(5)}")
processDataset(recreatedB, explodeCols)
processDataset(recreatedB, inputName, explodeCols)
}

// Do a hash join on where the exploded hash values are equal.
Expand All @@ -258,7 +268,8 @@ private[ml] abstract class LSHModel[T <: LSHModel[T]] extends Model[T] with LSHP
// Add a new column to store the distance of the two records.
val distUDF = udf((x: Vector, y: Vector) => keyDistance(x, y), DataTypes.DoubleType)
val joinedDatasetWithDist = joinedDataset.select(col("*"),
distUDF(explodedA($(inputCol)), explodedB($(inputCol))).as(distCol)
distUDF(explodedA(s"$inputName.${$(inputCol)}"),
explodedB(s"$inputName.${$(inputCol)}")).as(distCol)
)

// Filter the joined datasets where the distance are smaller than the threshold.
Expand All @@ -270,9 +281,9 @@ private[ml] abstract class LSHModel[T <: LSHModel[T]] extends Model[T] with LSHP
*/
@Since("2.1.0")
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.

@Since("2.1.0") datasetA: Dataset[_],
@Since("2.1.0") datasetB: Dataset[_],
@Since("2.1.0") threshold: Double): Dataset[_] = {
datasetA: Dataset[_],
datasetB: Dataset[_],
threshold: Double): Dataset[_] = {
approxSimilarityJoin(datasetA, datasetB, threshold, "distCol")
}
}
Expand All @@ -282,19 +293,17 @@ private[ml] abstract class LSHModel[T <: LSHModel[T]] extends Model[T] with LSHP
* hash column, approximate nearest neighbor search with a dataset and a key, and approximate
* similarity join of two datasets.
*
* Currently the following LSH family is implemented:
* - Euclidean Distance: Random Projection
*
* 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).
* @tparam T The class type of lsh
*/
@Experimental
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 mark a private class Experimental

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Removed.

@Since("2.1.0")
private[ml] abstract class LSH[T <: LSHModel[T]] extends Estimator[T] with LSHParams {
Copy link
Member

Choose a reason for hiding this comment

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

self: T => here too

Copy link
Contributor Author

Choose a reason for hiding this comment

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

T is the model class. You mean self: Estimator[T] => ?

Copy link
Member

Choose a reason for hiding this comment

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

Right, sorry!

self: Estimator[T] =>

/** @group setParam */
@Since("2.1.0")
def setInputCol(value: String): this.type = set(inputCol, value)
Expand Down Expand Up @@ -322,13 +331,9 @@ private[ml] abstract class LSH[T <: LSHModel[T]] extends Estimator[T] with LSHPa

@Since("2.1.0")
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)
}

@Since("2.1.0")
override def transformSchema(schema: StructType): StructType = {
validateAndTransformSchema(schema)
}
}
12 changes: 10 additions & 2 deletions mllib/src/main/scala/org/apache/spark/ml/feature/MinHash.scala
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,9 @@ package org.apache.spark.ml.feature
import scala.util.Random

import org.apache.spark.annotation.{Experimental, Since}
import org.apache.spark.ml.linalg.{Vector, Vectors}
import org.apache.spark.ml.linalg.{Vector, Vectors, VectorUDT}
import org.apache.spark.ml.util.Identifiable
import org.apache.spark.sql.types.StructType

/**
* Model produced by [[MinHash]]
Expand Down Expand Up @@ -87,7 +88,7 @@ class MinHash private[ml] (override val uid: String) extends LSH[MinHashModel] {
@Since("2.1.0")
override protected[this] def createRawLSHModel(inputDim: Int): MinHashModel = {
val numEntry = inputDim * 2
Copy link
Member

Choose a reason for hiding this comment

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

This could overflow. Use inputDim < prime / 2 + 1 instead?

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.

assert(numEntry < prime, "The input vector dimension is too large for MinHash to handle.")
require(numEntry < prime, "The input vector dimension is too large for MinHash to handle.")
val hashFunctions: Seq[Int => Long] = {
(0 until $(outputDim)).map { i: Int =>
Copy link
Member

Choose a reason for hiding this comment

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

It could be worth writing this as a while loop for efficiency.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Changed it to be generated directly from randSeq.

// Perfect Hash function, use 2n buckets to reduce collision.
Expand All @@ -96,4 +97,11 @@ class MinHash private[ml] (override val uid: String) extends LSH[MinHashModel] {
}
new MinHashModel(uid, hashFunctions)
}

@Since("2.1.0")
override def transformSchema(schema: StructType): StructType = {
require(schema.apply($(inputCol)).dataType.sameType(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.

You can use SchemaUtils.checkColumnType

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.

s"${$(inputCol)} must be vectors")
validateAndTransformSchema(schema)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,10 @@ import scala.util.Random
import breeze.linalg.normalize

import org.apache.spark.annotation.{Experimental, Since}
import org.apache.spark.ml.linalg.{BLAS, Vector, Vectors}
import org.apache.spark.ml.linalg.{BLAS, Vector, Vectors, VectorUDT}
import org.apache.spark.ml.param.{DoubleParam, Params, ParamValidators}
import org.apache.spark.ml.util.Identifiable
import org.apache.spark.sql.types.StructType

/**
* Params for [[RandomProjection]].
Expand All @@ -43,7 +44,7 @@ private[ml] trait RandomProjectionParams extends Params {
}

/**
* Model produced by [[LSH]]
* Model produced by [[RandomProjection]]
Copy link
Member

Choose a reason for hiding this comment

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

For Experimental classes, begin the Scaladoc with a line with:

:: Experimental ::

(See e.g. MultilayerPerceptronClassifier)

Also, add doc for randUnitVectors since it shows up in the API as member data:

@param randUnitVectors  ...

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.

Copy link
Member

Choose a reason for hiding this comment

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

It would be good to document about normalization:

  • The input vectors are not normalized, so the number of buckets will be (max L2 norm of input vectors) / bucketLength.
  • The randUnitVectors are normalized to be unit vectors.

*/
@Experimental
@Since("2.1.0")
Expand Down Expand Up @@ -116,4 +117,11 @@ class RandomProjection private[ml] (
}
new RandomProjectionModel(uid, randUnitVectors)
}

@Since("2.1.0")
override def transformSchema(schema: StructType): StructType = {
require(schema.apply($(inputCol)).dataType.sameType(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.

Same here: SchemaUtils.checkColumnType

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.

s"${$(inputCol)} must be vectors")
validateAndTransformSchema(schema)
}
}