lshashing
python library to perform Locality-Sensitive Hashing to search for nearest neighbors in high dimensional data.
For now it only supports random projections but future versions will support more methods and techniques.
Implementation
pip install lshashing
Make sure the data and query points are numpy arrays!.
from lshashing import LSHRandom
import numpy as np
sample_data = np.random.randint(size = (20, 20), low = 0, high = 100)
point = np.random.randint(size = (1,20), low = 0, high = 100)
lshashing = LSHRandom(sample_data, hash_len = 4, num_tables = 2)
print(lshashing.tables[0].hash_table)
print(lshashing.knn_search(sample_data, point[0], k = 4, buckets = 3, radius = 2))
First column is the distances while the second column is the indices of the neighbors.
lshashing also supports parallelism using joblib library.
sample_data = np.random.randint(size = (20, 20), low = 0, high = 100)
point = np.random.randint(size = (1, 20), low = 0, high = 100)
lsh_random_parallel = LSHRandom(sample_data, 4, parallel = True)
lsh_random_parallel.knn_search(sample_data, point[0], 4, 3, parallel = True)
Adding new entries
Simply you can add new entries to the hash tables using the add_new_entry method.
from lshashing import LSHRandom
import numpy as np
sample_data = np.random.randint(size = (15, 20), low = 0, high = 100)
point = np.random.randint(size = (1, 20), low = 0, high = 100)
lshashing = LSHRandom(sample_data, hash_len = 3, num_tables = 2)
print(lshashing.tables[0].hash_table)
print(lshashing.n_rows)
lshashing.add_new_entry(point)
print(lshashing.n_rows)
print(lshashing.tables[0].hash_table)
Locality-sensitive hashing is an approximate nearest neighbors search technique which means that the resulted neighbors may not always be the exact nearest neighbor to the query point.
To enhance and ensure better extactness, hash length used, number of hash tables and the buckets to search need to be tweaked.
I also made some comparison between lshashing, linear method to get KNNs and scikit-learn's BallTree and KDTree and here are the results.
python examples/lshashing_compare.py
LSHashing performs the search a little bit slower than sklearn tree implementations, sometimes better but much faster to construct. However, the main advantage comes when we need to add new entry or remove from our data, i.e. updating the table. In sklearn trees this can be hard as we may need to reconstruct the trees all over again. It is clearly obvious that it takes much more time to construct the trees than creating the buckets with LSHashing. LSHashing also allows addition of new data easily and in no time.
Also as we can see the nearest neighbors returned by the LSHashing are not the exact neighbors, that's why it is called approximate nearest neighbor search. Of course, when dealing with reasonable amount of data it is better to go with normal nearest neighbor searching. However with very big data, this will be time consuming so it is more efficient to approach it differently.