Skip to content
Closed
Show file tree
Hide file tree
Changes from 11 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
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
290 changes: 290 additions & 0 deletions mllib/src/main/scala/org/apache/spark/ml/feature/lsh/LSH.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,290 @@
/*
* 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.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, 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._

/**
* Params for [[LSH]].
*/
private[ml] trait LSHParams extends HasInputCol with HasOutputCol {
/**
* Param for output dimension.
*
* @group param
*/
final val outputDim: IntParam = new IntParam(this, "outputDim", "output dimension",
Copy link
Contributor

Choose a reason for hiding this comment

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

Strictly speaking this is actually the number of hash buckets/functions. Yes, it is a "dimensionality reduction" and the output vectors have this dimension, but perhaps we can add a bit more documentation here expanding on the role of the buckets?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This is the dimension of LSH OR-amplification. Added in Scaladoc

ParamValidators.gt(0))

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

setDefault(outputDim -> 1)
Copy link
Contributor

Choose a reason for hiding this comment

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

Make this one line, i.e. setDefault(outputDim -> 1, outputCol -> "lsh_output")

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.


setDefault(outputCol -> "lsh_output")

/**
* Transform the Schema for LSH
* @param schema The schema of the input dataset without outputCol
* @return A derived schema with outputCol added
*/
final def transformLSHSchema(schema: StructType): StructType = {
Copy link
Contributor

Choose a reason for hiding this comment

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

This method should be protected. Also, while not strictly required, it's common to call this type of shared method validateAndTransformSchema (it's not defined as an internal API, it's just what has ended up being used commonly in various models & transformers).

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 outputFields = schema.fields :+
StructField($(outputCol), new VectorUDT, nullable = false)
StructType(outputFields)
Copy link
Contributor

Choose a reason for hiding this comment

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

You can use SchemaUtils.appendColumn(schema, $(outputCol), new VectorUDT) for this purpose

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.

}
}

/**
* Model produced by [[LSH]].
*/
abstract class LSHModel[KeyType, T <: LSHModel[KeyType, T]] private[ml]
extends Model[T] with LSHParams {
override def copy(extra: ParamMap): T = defaultCopy(extra)
/**
* :: DeveloperApi ::
*
* The hash function of LSH, mapping a predefined KeyType to a Vector
* @return The mapping of LSH function.
*/
protected[this] val hashFunction: KeyType => Vector

/**
* :: DeveloperApi ::
*
* 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 in double
*/
protected[ml] def keyDistance(x: KeyType, y: KeyType): Double

/**
* :: DeveloperApi ::
*
* Calculate the distance between two different hash Vectors. By default, the distance is the
* minimum distance of two hash values in any dimension.
*
* @param x One of the hash vector
* @param y Another hash vector
* @return The distance between hash vectors x and y in double
*/
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
Copy link

@karlhigley karlhigley Sep 25, 2016

Choose a reason for hiding this comment

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

By default, this is computing the Manhattan distance between hash values, which probably works as a proxy for the distance between hash buckets when using LSH based on p-stable distributions and any other approach that produces vectors of integers/doubles as hash signatures (e.g. MinHash).

However, the default won't work for approaches that produce vectors of booleans as hash signatures (e.g. sign random projection for cosine distance). It could be overridden to compute Hamming distance in that case, though.

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, I am planning to override it for BitSampling (LSH for Hamming distance)

Copy link
Member

Choose a reason for hiding this comment

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

If it's algorithm-specific, I'd recommend making it abstract here so it's more future bug-proof.

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.

}

/**
* Transforms the input dataset.
*/
override def transform(dataset: Dataset[_]): DataFrame = {
transformSchema(dataset.schema, logging = true)
val transformUDF = udf(hashFunction, new VectorUDT)
dataset.withColumn($(outputCol), transformUDF(dataset($(inputCol))))
}

/**
* :: DeveloperApi ::
*
* Check transform validity and derive the output schema from the input schema.
*
* Typical implementation should first conduct verification on schema change and parameter
* validity, including complex parameter interaction checks.
*/
override def transformSchema(schema: StructType): StructType = {
transformLSHSchema(schema)
}

/**
* Given a large dataset and an item, approximately find at most k items which have the closest
* distance to the item.
* @param dataset the dataset to look for the key
* @param key The key to hash for the item
* @param k The maximum number of 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(dataset: Dataset[_], key: KeyType, k: Int = 1,
distCol: String = "distance"): Dataset[_] = {
assert(k > 0, "The number of nearest neighbors cannot be less than 1")
// Get Hash Value of the key v
val keyHash = hashFunction(key)
val modelDataset = transform(dataset)
Copy link

@karlhigley karlhigley Sep 25, 2016

Choose a reason for hiding this comment

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

Does this transform the original dataset for each key lookup? If so, it seems inefficient for repeated lookups. I can imagine a few possibilities to help with that:

  • Allowing lookups of multiple keys simultaneously (to amortize the cost of building the hash tables), and/or
  • Providing a way to pre-compute the hash tables (i.e. modelDataset) and execute multiple lookups against them, and/or
  • Storing the hash tables on the model and making it possible to cache them in memory

The ability to load and save models with their modelDatasets would also help, but that's probably out of scope for this initial PR. Structuring the model so that hash tables can be pre-computed/cached would set up that future work nicely, though.

Copy link
Contributor Author

@Yunni Yunni Sep 26, 2016

Choose a reason for hiding this comment

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

Based on my discussion with @jkbradley, storing the hash tables on the model is not an option. To make the interface cleaner, I went with option (2) in the new commit. Basically, transforms() will skip the computation if outputCol is already there. So users can do the following to avoid inefficiency in repeated lookups.
val model = new MinHash()...fit(df)
val transformedDf = model.transform(df).cache()
model.approxNearestNeighbor(transformedDf, key1, k=3)
model.approxNearestNeighbor(transformedDf, key2, k=5)

Meanwhile, putting the raw Df works as well, but with low performance for multiple queries,
val model = new MinHash()...fit(df)
model.approxNearestNeighbor(df, key, k=3)

Copy link
Contributor

Choose a reason for hiding this comment

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

Can you elaborate on this discussion? I don't see it referenced anywhere on the PR, JIRA or design doc.

Copy link
Member

Choose a reason for hiding this comment

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

@MLnick I believe the discussion is in the resolved comments in the design doc.

The main issue is that, currently, no MLlib models store the entire dataset. Some do store transient references, but those do not need to be saved when models are saved. If a model method like approxNearestNeighbor assumed that the dataset were part of the model, then model.save would need to save the entire dataset.

I'm in favor of supporting pre-computation too. I'd recommend that approxNearestNeighbor implement the logic to check whether outputCol already exists; this should not belong in transform (to be consistent with the rest of MLlib).

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Moved the checking logic to approxNearestNeighbor and approxSimilarityJoin


// In the origin dataset, find the hash value u that is closest to v
val hashDistUDF = udf((x: Vector) => hashDistance(x, keyHash), DataTypes.DoubleType)
val hashDistCol = hashDistUDF(col($(outputCol)))

// Compute threshold to get exact k elements.
val modelDatasetSortedByHash = modelDataset.sort(hashDistCol).limit(k)
val thresholdDataset = modelDatasetSortedByHash.select(max(hashDistCol))
val hashThreshold = thresholdDataset.collect()(0)(0).asInstanceOf[Double]

// Filter the dataset where the hash value is less than the threshold.
val modelSubset = modelDataset.filter(hashDistCol <= hashThreshold)

Choose a reason for hiding this comment

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

This looks like a variant of multi-probe LSH, which seems extensible to the other distance measures and hashing schemes that are likely candidates for future work. It might be nice to have an option to select between probing a single bucket and probing multiple buckets though -- in some cases, the user may be happy to accept less than exactly k neighbors (i.e. a non-zero miss rate) in exchange for faster lookups.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This is a really good advice. Added an option for Single/Multiple probing.


// 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)
}

/**
* 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[_] = {
Copy link
Contributor

Choose a reason for hiding this comment

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

Ditto here for indentation style

Copy link
Member

Choose a reason for hiding this comment

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

Btw, it'd also be good to avoid default parameter values in methods since they are not Java-friendly. You can write a version of the method which does not take distCol as an arg in order to implement the default.

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 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.
// TODO: Remove recreateCol logic once SPARK-17154 is resolved.
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.filter(col(distCol) < threshold).distinct()
}
}

/**
* 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.
*
* 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 KeyType The input key type of LSH
* @tparam T The class type of lsh
*/
abstract class LSH[KeyType, T <: LSHModel[KeyType, T]] extends Estimator[T] with LSHParams {
/** @group setParam */
def setInputCol(value: String): this.type = set(inputCol, value)
Copy link
Contributor

@MLnick MLnick Sep 26, 2016

Choose a reason for hiding this comment

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

These methods that return this.type need to be overridden in the concrete subclasses for Java compat in the method chaining style (sadly)... see RandomForestClassifier for an example.

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.


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

/** @group setParam */
def setOutputDim(value: Int): this.type = set(outputDim, value)

/**
* :: DeveloperApi ::
*
* 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 input dimension of input dataset
* @return A new LSHModel instance without any params
*/
protected[this] def createRawLSHModel(inputDim: Int): T

override def copy(extra: ParamMap): Estimator[T] = defaultCopy(extra)

/**
* Fits a model to the input data.
*/
override def fit(dataset: Dataset[_]): T = {
val inputDim = dataset.select(col($(inputCol))).head().get(0).asInstanceOf[Vector].size
val model = createRawLSHModel(inputDim).setParent(this)
copyValues(model)
}

/**
* :: DeveloperApi ::
*
* Check transform validity and derive the output schema from the input schema.
*
* Typical implementation should first conduct verification on schema change and parameter
* validity, including complex parameter interaction checks.
*/
override def transformSchema(schema: StructType): StructType = {
transformLSHSchema(schema)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
/*
* 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.lsh

import scala.util.Random

import breeze.linalg.normalize

import org.apache.spark.ml.linalg.{BLAS, Vector, Vectors}
import org.apache.spark.ml.param.{DoubleParam, Params, ParamValidators}
import org.apache.spark.ml.util.Identifiable

/**
* Params for [[RandomProjection]].
*/
private[ml] trait RandomProjectionParams extends Params {
val bucketLength: DoubleParam = new DoubleParam(this, "bucketLength",
Copy link
Contributor

Choose a reason for hiding this comment

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

Need getBucketLength

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 length of each hash bucket", ParamValidators.gt(0))
}

class RandomProjectionModel(
override val uid: String,
val randUnitVectors: Array[Vector])
extends LSHModel[Vector, RandomProjectionModel] with RandomProjectionParams {

override protected[this] val hashFunction: (Vector) => Vector = {
key: Vector => {
val hashValues: Array[Double] = randUnitVectors.map({
randUnitVector => Math.floor(BLAS.dot(key, randUnitVector) / $(bucketLength))
})
Vectors.dense(hashValues)
}
}

override protected[ml] def keyDistance(x: Vector, y: Vector): Double = {
Math.sqrt(Vectors.sqdist(x, y))
}
}

/**
* This [[RandomProjection]] implements Locality Sensitive Hashing functions with 2-stable
* distributions. If you are looking for LSH for cos distance, please use [[SignRandomProjection]]
*
* References:
* Wang, Jingdong et al. "Hashing for similarity search: A survey." arXiv preprint
* arXiv:1408.2927 (2014).
*/
class RandomProjection(override val uid: String) extends LSH[Vector, RandomProjectionModel]
with RandomProjectionParams {

private[this] var inputDim = -1
Copy link
Contributor

Choose a reason for hiding this comment

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

See below comment, I think we can do without this var.


private[this] lazy val randUnitVectors: Array[Vector] = {
Copy link
Contributor

Choose a reason for hiding this comment

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

How about

  private[this] lazy val randUnitVectors: Int => Array[Vector] = (d: Int) => {
    Array.fill($(outputDim)) {
      val randArray = Array.fill(d)(Random.nextGaussian())
      Vectors.fromBreeze(normalize(breeze.linalg.Vector(randArray)))
    }
  }
...
  override protected[this] def createRawLSHModel(dataset: Dataset[_]): RandomProjectionModel = {
    val inputDim = dataset.select(col($(inputCol))).head().get(0).asInstanceOf[Vector].size
    new RandomProjectionModel(uid, randUnitVectors(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.

Moved to Superclass. Removed var inputDim = -1

Array.fill($(outputDim)) {
val randArray = Array.fill(inputDim)(Random.nextGaussian())
Vectors.fromBreeze(normalize(breeze.linalg.Vector(randArray)))
}
}

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

/** @group setParam */
def setBucketLength(value: Double): this.type = set(bucketLength, value)

override protected[this] def createRawLSHModel(inputDim: Int): RandomProjectionModel = {
this.inputDim = inputDim
new RandomProjectionModel(uid, randUnitVectors)
}
}
Loading