fix this code: import numpy as np import pandas as pd import faiss import torch from…
- User
fix this code: import numpy as np import pandas as pd import faiss import torch from sentence_transformers import SentenceTransformer from scipy.spatial.distance import cdist as scipy_cdist import math
np.random.seed(13) # Set seed for reproducibility pd.set_option("max_colwidth", 1500) # Allow to see full column width
k_nearest = 10 # Closet k responses
external_query = "hogwarts, magic, harry"
Use GPU if available
torch_device = 'cuda' if torch.cuda.is_available() else 'cpu'
Select and load sentence transformer model
encoder = SentenceTransformer('paraphrase-mpnet-base-v2', device=torch_device)
sme_df = pd.read_csv('wiki_movie_plots_deduped_with_summaries.csv', usecols=['Title', 'PlotSummary']) sme_df.drop_duplicates(subset='PlotSummary', inplace=True) sme_df.reset_index(drop=True, inplace=True)
Always encode the second column
if 'embeddings' not in locals(): print("Embeddings not found. Please encode first.") embeddings = encoder.encode(sme_df.iloc[:, 1].tolist(), show_progress_bar=True, device=torch_device)
Encode external query
xq = encoder.encode([external_query], device=torch_device)
Dimension of the vectors
dim = embeddings[0].size
Number of clusters | There will be to 1%
nlist = (5 * math.ceil((len(embeddings)/100) / 5))
PQ Hyperparmeters
nbits = 8 # Number of bits for PQ encoding | make fiass seems to allow is 8 when using IVF+PQ
Calculate L2 distances between vectors
vecs = faiss.IndexFlatL2(dim)
m = 16
index = faiss.IndexIVFPQ(vecs, dim, nlist, m, nbits)
index.train(vecs)
AttributeError Traceback (most recent call last) Cell In[16], line 1 ----> 1 index.train(vecs)
File /opt/conda/lib/python3.10/site-packages/faiss/class_wrappers.py:295, in handle_Index..replacement_train(self, x) 285 def replacement_train(self, x): 286 """Trains the index on a representative set of vectors. 287 The index must be trained before vectors can be added to it. 288 (...) 293
dtypemust be float32. 294 """ --> 295 n, d = x.shape 296 assert d == self.d 297 x = np.ascontiguousarray(x, dtype='float32')AttributeError: 'IndexFlatL2' object has no attribute 'shape'
- Assistant
import numpy as np import pandas as pd import faiss import torch from sentence_transformers import SentenceTransformer from scipy.spatial.distance import cdist as scipy_cdist import math
np.random.seed(13) # Set seed for reproducibility pd.set_option("max_colwidth", 1500) # Allow to see full column width
k_nearest = 10 # Closet k responses
external_query = "hogwarts, magic, harry"
Use GPU if available
torch_device = 'cuda' if torch.cuda.is_available() else 'cpu'
Select and load sentence transformer model
encoder = SentenceTransformer('paraphrase-mpnet-base-v2', device=torch_device)
sme_df = pd.read_csv('wiki_movie_plots_deduped_with_summaries.csv', usecols=['Title', 'PlotSummary']) sme_df.drop_duplicates(subset='PlotSummary', inplace=True) sme_df.reset_index(drop=True, inplace=True)