Here's what I do:
import numpy as np
import pandas as pd
from sklearn.random_projection import SparseRandomProjection
from sklearn.metrics.pairwise import cosine_similarity
import time
class LSH:
def init(self, n_components, n_hashes):
# Dimensionalty of projected data
self.n_components = n_components
# number of buckets
self.n_hashes = n_hashes
# https://scikit-learn.org/stable/modules/generated/sklearn.random_projection.SparseRandomProjection.html
self.hash_tables = [SparseRandomProjection(n_components=n_components) for _ in range(n_hashes)]
def fit(self, data):
if isinstance(data, pd.DataFrame):
self.item_ids = data.index.tolist()
data = data.values
else:
self.item_ids = np.arange(len(data))
# initialize the hash buckets
self.hash_buckets = [{} for _ in range(self.n_hashes)]
for i, hash_table in enumerate(self.hash_tables):
# For each hash table the function applies SparseRandomProjection.
# This step reduce the dimentionality of the data while tryigng to preserve the relative distance between points.
# Purpose: approximate high-dimentional to low-dimensional data and similar items stays together.
projections = hash_table.fit_transform(data)
for j, projection in enumerate(projections):
# After projecting data for each hash table, the funtion iterates over these projections.
# For each data points projection, it creates a hash key. The key is generate by the sign of each component.
# The idea is if two points are close in high-dimensional space, their projections must also be closed.
# Ex projection: [ 0.72199595 -0.6867862 -0.5098184 0.55619763 4.24497602 1.08506354
# -2.26010595 -2.79241899 6.01301565 -4.82428779 1.05509869 -2.29027826
# -2.13740946 1.06065566 -1.57524544 0.58627834]
# Ex hash_key: (1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1)
hash_key = tuple(np.where(projection > 0, 1, 0))
if hash_key not in self.hash_buckets[i]:
# Create the item with the hash_key
self.hash_buckets[i][hash_key] = []
# Append to that specific hash_bucket, j, with the unique and shared hash_key
self.hash_buckets[i][hash_key].append(j)
return self.hash_buckets
def query(self, point):
if isinstance(point, pd.Series):
point = point.to_numpy().reshape(1, -1) # Correct way to handle Series
elif isinstance(point, np.ndarray):
point = point.reshape(1, -1)
# To eliminate the chance of duplicates
similar_items = set()
for i, hash_table in enumerate(self.hash_tables):
projection = hash_table.transform(point)
hash_key = tuple(np.where(projection > 0, 1, 0)[0])
similar_items.update(self.hash_buckets[i].get(hash_key, []))
similar_item_ids = [self.item_ids[i] for i in similar_items]
return similar_item_ids
def find_top_similar(data, query_input, similar_inputs, top_n=10):
if isinstance(data, pd.DataFrame):
query_item = data.loc[query_input].values.reshape(1, -1)
else:
query_item = data[query_input].reshape(1, -1)
similarities = []
for input_ in similar_inputs:
if input_ != query_input:
if isinstance(data, pd.DataFrame):
item = data.loc[input_].values.reshape(1, -1)
else:
item = data[input_].reshape(1, -1)
similarity_score = cosine_similarity(query_item, item)[0][0]
similarities.append((input_, similarity_score))
sorted_similarities = sorted(similarities, key=lambda x: x[1], reverse=True)
top_similar_indices = [item[0] for item in sorted_similarities[:top_n]]
return top_similar_indices
Params
n_components = int(0.1 * n_features)
n_hashes = 15
DataFrame
lsh = LSH(n_components=n_components, n_hashes=n_hashes)
hash_buckets = lsh.fit(data)
top_n = 20
query_id = data.index[2]
start_time = time.time()
similar_ids = lsh.query(data.loc[query_id])
end_time = time.time()
print("Time taken to query similar items (DataFrame):", end_time - start_time, "seconds")
top_n_similar_ids = find_top_similar(data, query_id, similar_ids, top_n=top_n)
print(f"Top {top_n} Similar Items (DataFrame) for {query_id}:", top_n_similar_ids)
from joblib import dump
model_name_base = f"lsh_model_{part_name}".lower().replace(' ', '_')
model_name = model_name_base + ".joblib"
data_name = model_name_base + ".pkl"
Save the LSH model to a file
print(f'Saving: {model_name}')
dump(lsh, model_name)
same associalted data
data.to_pickle(data_name)
print(f'Saving: {data_name}')
create a model.tar.gz archive after saving the model with joblib:
import tarfile
Create a tar.gz archive
with tarfile.open(model_name_base + ".tar.gz", mode='w:gz') as archive:
archive.add(model_name, arcname=model_name)
archive.add(data_name, arcname=data_name)
archive.close() is not necessary as the ‘with’ context already closes the file
In inference in another environment I do:
import boto3
import gzip
import tarfile
import io
import os
from joblib import load
Initialize a boto3 S3 client
s3 = boto3.client('s3')
def initialize(context):
# Specify the name of the S3 bucket and the key of the .tar.gz file
# bucket_name = 'ivt-gemini1-uswest2-models'
# object_key = 's3://ivt-gemini1-uswest2-models/serving/lsh_model_tongue_lining.tar.gz'
bucket_name = 'nike-geminipoc-test-serverless-deployments'
object_key = 'serverless/gemini-poc-opensearch-api-es/test/lsh_model_tongue_lining.tar.gz'
# Download the .tar..gz file from S3 to an in-memory buffer
buffer = io.BytesIO()
s3.download_fileobj(bucket_name, object_key, buffer)
buffer.seek(0)
# Use the gzip library to decompress the buffer
decompressed_buffer = io.BytesIO(gzip.decompress(buffer.read()))
decompressed_buffer.seek(0)
# Use the tarfile library to extract the contents of the .tar.gz file
tar = tarfile.open(fileobj=decompressed_buffer)
tar.extractall()
tar.close()
# Substitute 'lsh_model.joblib' with your actual model filename, if different.
base_with_extention = os.path.basename(object_key)
base_no_extention = base_with_extention.rsplit(".")[0]
model_path = base_no_extention + '.joblib'
data_path = base_no_extention + '.pkl'
print(f"Reading model from: {model_path}")
print(f"Reading data from: {data_path}")
lsh_model_loaded = load(model_path)
data = pd.read_pickle(data_path)
return lsh_model_loaded, data
def inference(model, data, query):
# Assuming 'data' and 'query_id' are predefined and you have a sample query
# print(f'query_id: {query_id}')
query_data = np.array(data.loc[query_id])
query_result = model.query(query_data)
# Do something with the query result, like printing or validating it
top_n_similar_ids = find_top_similar(data, query_id, query_result, top_n=top_n)
return top_n_similar_ids
Get the ids
payload = {"part_name": "tongue_lining", "query_id": '61a99df7-f298-43ac-ad41-bed28b109a31'}
context = payload["part_name"]
query_id_ =payload["query_id"]
initialize
model_, data_ = initialize(context)
Operate inerence
top_n_similar_ids = inference(model_, data_, query_id_)
print(top_n_similar_ids)
# At this point, the contents of the .tar.gz file have been extracted to the current
# working directory. You can now use Python's built-in file handling functions
# to read the extracted files.
for member in tar.getmembers():
if member.isfile():
with tar.extractfile(member) as f:
print(f.read().decode('utf-8'))
But I get the error:
AttributeError Traceback (most recent call last)
Cell In[1], line 65
62 query_id_ =payload["query_id"]
64 # initialize
---> 65 model_, data_ = initialize(context)
67 # Operate inerence
68 top_n_similar_ids = inference(model_, data_, query_id_)
Cell In[1], line 41, in initialize(context)
39 print(f"Reading model from: {model_path}")
40 print(f"Reading data from: {data_path}")
---> 41 lsh_model_loaded = load(model_path)
42 data = pd.read_pickle(data_path)
44 return lsh_model_loaded, data
File ~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/joblib/numpy_pickle.py:658, in load(filename, mmap_mode)
652 if isinstance(fobj, str):
653 # if the returned file object is a string, this means we
654 # try to load a pickle file generated with an version of
655 # Joblib so we load it with joblib compatibility function.
656 return load_compatibility(fobj)
--> 658 obj = _unpickle(fobj, filename, mmap_mode)
659 return obj
File ~/anaconda3/envs/pytorch_p310/lib/python3.10/site-packages/joblib/numpy_pickle.py:577, in _unpickle(fobj, filename, mmap_mode)
575 obj = None
576 try:
--> 577 obj = unpickler.load()
578 if unpickler.compat_mode:
579 warnings.warn("The file '%s' has been generated with a "
580 "joblib version less than 0.10. "
581 "Please regenerate this pickle file."
582 % filename,
583 DeprecationWarning, stacklevel=3)
File ~/anaconda3/envs/pytorch_p310/lib/python3.10/pickle.py:1213, in _Unpickler.load(self)
1211 raise EOFError
1212 assert isinstance(key, bytes_types)
-> 1213 dispatchkey[0]
1214 except _Stop as stopinst:
1215 return stopinst.value
File ~/anaconda3/envs/pytorch_p310/lib/python3.10/pickle.py:1538, in _Unpickler.load_stack_global(self)
1536 if type(name) is not str or type(module) is not str:
1537 raise UnpicklingError("STACK_GLOBAL requires str")
-> 1538 self.append(self.find_class(module, name))
File ~/anaconda3/envs/pytorch_p310/lib/python3.10/pickle.py:1582, in _Unpickler.find_class(self, module, name)
1580 import(module, level=0)
1581 if self.proto >= 4:
-> 1582 return _getattribute(sys.modules[module], name)[0]
1583 else:
1584 return getattr(sys.modules[module], name)
File ~/anaconda3/envs/pytorch_p310/lib/python3.10/pickle.py:331, in _getattribute(obj, name)
329 obj = getattr(obj, subpath)
330 except AttributeError:
--> 331 raise AttributeError("Can't get attribute {!r} on {!r}"
332 .format(name, obj)) from None
333 return obj, parent
AttributeError: Can't get attribute 'LSH' on <module 'main'>