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
SignRandomProjection: LSH Classes for cosine distance metrics
  • Loading branch information
Yun Ni committed Oct 11, 2016
commit fb120afc65fee1badc23d3e502f7196dc1d3c4fe
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/*
* 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 breeze.linalg.normalize

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

/**
* :: Experimental ::
* Model produced by [[SignRandomProjection]]
* @param randUnitVectors An array of random unit vectors. Each vector represents a hash function.
*/
@Experimental
@Since("2.1.0")
class SignRandomProjectionModel private[ml] (
override val uid: String,
val randUnitVectors: Array[Vector])
extends LSHModel[SignRandomProjectionModel] {

@Since("2.1.0")
override protected[this] val hashFunction: (Vector) => Vector = {
key: Vector => {
val hashValues: Array[Double] = randUnitVectors.map({
randUnitVector => Math.signum(BLAS.dot(key, randUnitVector))
})
Vectors.dense(hashValues)
}
}

@Since("2.1.0")
override protected[ml] def keyDistance(x: Vector, y: Vector): Double = {
// 1 - cosine similarity
1 - BLAS.dot(x, y) / (Vectors.norm(x, 2) * Vectors.norm(y, 2))
}

@Since("2.1.0")
override protected[ml] def hashDistance(x: Vector, y: Vector): Double = {
// Since it's generated by hashing, it will be a pair of dense vectors.
x.toDense.values.zip(y.toDense.values).map(x => math.abs(x._1 - x._2)).min
}
}

/**
* :: Experimental ::
* This [[SignRandomProjectionModel]] implements Locality Sensitive Hashing functions for cosine
* distance metrics.
*
* The input is dense or sparse vectors, each of which represents a point in the space. The output
* will be vectors of configurable dimension, taking values from {-1, 1, 0}. Hash value in the same
* dimension is calculated by the same hash function.
*
* References:
* Wang, Jingdong et al. "Hashing for similarity search: A survey." arXiv preprint
* arXiv:1408.2927 (2014).
*/
@Experimental
@Since("2.1.0")
class SignRandomProjection(override val uid: String) extends LSH[SignRandomProjectionModel]
with HasSeed {

@Since("2.1.0")
override def setInputCol(value: String): this.type = super.setInputCol(value)

@Since("2.1.0")
override def setOutputCol(value: String): this.type = super.setOutputCol(value)

@Since("2.1.0")
override def setOutputDim(value: Int): this.type = super.setOutputDim(value)

@Since("2.1.0")
def this() = {
this(Identifiable.randomUID("random projection"))
}

/** @group setParam */
@Since("2.1.0")
def setSeed(value: Long): this.type = set(seed, value)

@Since("2.1.0")
override protected[this] def createRawLSHModel(inputDim: Int): SignRandomProjectionModel = {
val rand = new Random($(seed))
val randUnitVectors: Array[Vector] = {
Array.fill($(outputDim)) {
val randArray = Array.fill(inputDim)(rand.nextGaussian())
Vectors.fromBreeze(normalize(breeze.linalg.Vector(randArray)))
}
}
new SignRandomProjectionModel(uid, randUnitVectors)
}

@Since("2.1.0")
override def transformSchema(schema: StructType): StructType = {
SchemaUtils.checkColumnType(schema, $(inputCol), new VectorUDT)
validateAndTransformSchema(schema)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/*
* 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 breeze.numerics.{cos, sin}
import breeze.numerics.constants.Pi

import org.apache.spark.SparkFunSuite
import org.apache.spark.ml.linalg.Vectors
import org.apache.spark.mllib.util.MLlibTestSparkContext

class SignRandomProjectionSuite extends SparkFunSuite with MLlibTestSparkContext {
test("SignRandomProjection") {
val data = {
for (i <- -5 until 5; j <- -5 until 5) yield Vectors.dense(i.toDouble, j.toDouble)
}
val df = spark.createDataFrame(data.map(Tuple1.apply)).toDF("keys")

val srp = new SignRandomProjection()
.setInputCol("keys")
.setOutputCol("values")
.setSeed(0)

val (falsePositive, falseNegative) = LSHTest.calculateLSHProperty(df, srp, 1.6, 0.4)
assert(falsePositive < 0.1)
assert(falseNegative < 0.1)
}

test("approxNearestNeighbors for cosine distance") {
val data = {
for (i <- -5 until 5; j <- -5 until 5) yield Vectors.dense(i.toDouble, j.toDouble)
}
val df = spark.createDataFrame(data.map(Tuple1.apply)).toDF("keys")
val key = Vectors.dense(1.2, 3.4)

val mh = new SignRandomProjection()
.setInputCol("keys")
.setOutputCol("values")
.setSeed(0)

val (precision, recall) = LSHTest.calculateApproxNearestNeighbors(mh, df, key, 30,
singleProbing = true)
assert(precision >= 0.8)
assert(recall >= 0.8)
}

test("approxSimilarityJoin for cosine distance") {
val dataA = {
for (i <- -5 until 5; j <- -5 until 5) yield Vectors.dense(i.toDouble, j.toDouble)
}
val dfA = spark.createDataFrame(dataA.map(Tuple1.apply)).toDF("keys")

val dataB = {
for (i <- 0 until 24) yield Vectors.dense(10 * sin(Pi / 12 * i), 10 * cos(Pi / 12 * i))
}
val dfB = spark.createDataFrame(dataB.map(Tuple1.apply)).toDF("keys")

val mh = new SignRandomProjection()
.setInputCol("keys")
.setOutputCol("values")
.setSeed(0)

val (precision, recall) = LSHTest.calculateApproxSimilarityJoin(mh, dfA, dfB, 0.5)
assert(precision == 1.0)
assert(recall >= 0.8)
}
}