Github user jkbradley commented on a diff in the pull request:
https://github.com/apache/spark/pull/16715#discussion_r104331119
--- Diff: python/pyspark/ml/feature.py ---
@@ -120,6 +122,196 @@ def getThreshold(self):
return self.getOrDefault(self.threshold)
+class LSHParams(Params):
+ """
+ Mixin for Locality Sensitive Hashing (LSH) algorithm parameters.
+ """
+
+ numHashTables = Param(Params._dummy(), "numHashTables", "number of
hash tables, where " +
+ "increasing number of hash tables lowers the
false negative rate, " +
+ "and decreasing it improves the running
performance.",
+ typeConverter=TypeConverters.toInt)
+
+ def __init__(self):
+ super(LSHParams, self).__init__()
+
+ def setNumHashTables(self, value):
+ """
+ Sets the value of :py:attr:`numHashTables`.
+ """
+ return self._set(numHashTables=value)
+
+ def getNumHashTables(self):
+ """
+ Gets the value of numHashTables or its default value.
+ """
+ return self.getOrDefault(self.numHashTables)
+
+
+class LSHModel(JavaModel):
+ """
+ Mixin for Locality Sensitive Hashing (LSH) models.
+ """
+
+ def approxNearestNeighbors(self, dataset, key, numNearestNeighbors,
distCol="distCol"):
+ """
+ Given a large dataset and an item, approximately find at most k
items which have the
+ closest distance to the item. If the :py:attr:`outputCol` is
missing, the method will
+ transform the data; if the :py:attr:`outputCol` exists, it will
use that. This allows
+ caching of the transformed data when necessary.
+
+ .. note:: This method is experimental and will likely change
behavior in the next release.
+
+ :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 distCol: Output column for storing the distance between
each result row and the key.
+ Use "distCol" as default value if it's not
specified.
+ :return: A dataset containing at most k items closest to the key.
A column "distCol" is
+ added to show the distance between each row and the key.
+ """
+ return self._call_java("approxNearestNeighbors", dataset, key,
numNearestNeighbors,
+ distCol)
+
+ def approxSimilarityJoin(self, datasetA, datasetB, threshold,
distCol="distCol"):
+ """
+ Join two datasets to approximately find all pairs of rows whose
distance are smaller than
+ the threshold. If the :py:attr:`outputCol` is missing, the method
will transform the data;
+ if the :py:attr:`outputCol` exists, it will use that. 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 pair of rows. Use
+ "distCol" as default value if it's not specified.
+ :return: A joined dataset containing pairs of rows. The original
rows are in columns
+ "datasetA" and "datasetB", and a column "distCol" is
added to show the distance
+ between each pair.
+ """
+ return self._call_java("approxSimilarityJoin", datasetA, datasetB,
threshold, distCol)
+
+
+@inherit_doc
+class BucketedRandomProjectionLSH(JavaEstimator, LSHParams, HasInputCol,
HasOutputCol, HasSeed,
+ JavaMLReadable, JavaMLWritable):
+ """
+ .. note:: Experimental
+
+ LSH class for Euclidean distance metrics.
+ The input is dense or sparse vectors, each of which represents a point
in the Euclidean
+ distance space. The output will be vectors of configurable dimension.
Hash values in the same
+ dimension are calculated by the same hash function.
+
+ .. seealso:: `Stable Distributions \
+
<https://en.wikipedia.org/wiki/Locality-sensitive_hashing#Stable_distributions>`_
+ .. seealso:: `Hashing for Similarity Search: A Survey
<https://arxiv.org/abs/1408.2927>`_
+
+ >>> from pyspark.ml.linalg import Vectors
+ >>> from pyspark.sql.functions import col
+ >>> data = [(0, Vectors.dense([-1.0, -1.0 ]),),
+ ... (1, Vectors.dense([-1.0, 1.0 ]),),
+ ... (2, Vectors.dense([1.0, -1.0 ]),),
+ ... (3, Vectors.dense([1.0, 1.0]),)]
+ >>> df = spark.createDataFrame(data, ["id", "features"])
+ >>> brp = BucketedRandomProjectionLSH(inputCol="features",
outputCol="hashes",
+ ... seed=12345, bucketLength=1.0)
+ >>> model = brp.fit(df)
+ >>> model.transform(df).head()
+ Row(id=0, features=DenseVector([-1.0, -1.0]),
hashes=[DenseVector([-1.0])])
+ >>> data2 = [(4, Vectors.dense([2.0, 2.0 ]),),
+ ... (5, Vectors.dense([2.0, 3.0 ]),),
+ ... (6, Vectors.dense([3.0, 2.0 ]),),
+ ... (7, Vectors.dense([3.0, 3.0]),)]
+ >>> df2 = spark.createDataFrame(data2, ["id", "features"])
+ >>> model.approxNearestNeighbors(df2, Vectors.dense([1.0, 2.0]),
1).collect()
+ [Row(id=4, features=DenseVector([2.0, 2.0]),
hashes=[DenseVector([1.0])], distCol=1.0)]
+ >>> model.approxSimilarityJoin(df, df2, 3.0,
distCol="EuclideanDistance").select(
+ ... col("datasetA.id").alias("idA"),
+ ... col("datasetB.id").alias("idB"),
+ ... col("EuclideanDistance")).show()
+ +---+---+-----------------+
+ |idA|idB|EuclideanDistance|
+ +---+---+-----------------+
+ | 3| 6| 2.23606797749979|
+ +---+---+-----------------+
+ ...
+ >>> brpPath = temp_path + "/brp"
+ >>> brp.save(brpPath)
+ >>> brp2 = BucketedRandomProjectionLSH.load(brpPath)
+ >>> brp2.getBucketLength() == brp.getBucketLength()
+ True
+ >>> modelPath = temp_path + "/brp-model"
+ >>> model.save(modelPath)
+ >>> model2 = BucketedRandomProjectionLSHModel.load(modelPath)
+ >>> model.transform(df).head().hashes ==
model2.transform(df).head().hashes
+ True
+
+ .. versionadded:: 2.2.0
+ """
+
+ bucketLength = Param(Params._dummy(), "bucketLength", "the length of
each hash bucket, " +
+ "a larger bucket lowers the false negative rate.",
+ typeConverter=TypeConverters.toFloat)
+
+ @keyword_only
+ def __init__(self, inputCol=None, outputCol=None, seed=None,
numHashTables=1,
+ bucketLength=None):
+ """
+ __init__(self, inputCol=None, outputCol=None, seed=None,
numHashTables=1,
--- End diff --
Oh, I thought it was necessary for proper doc generation, but maybe it's
not.
---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at [email protected] or file a JIRA ticket
with INFRA.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]