how would i change this code to work on a pretrained model like bert: modelfilename =…
- User
how would i change this code to work on a pretrained model like bert: model_file_name = 'TI_recommendation_algorithm/ti_rec_model_doc2vec' model_file_path = model_file_name #! #! model_file_path = temp_file_path + '/' + model_file_name
# Checks if doc2vec file exist; if not download file from Azure Storage container #!is_model_file_found = os.path.isfile(model_file_path) #!if is_model_file_found == False: #! azure_helper.download_file('ml-models', model_file_name, model_file_path) rec_model = Doc2Vec.load(model_file_path) open_inq_clean_text = result_open[0][1] if open_inq_clean_text == None: clean_text_result = clean_inquiry_text.clean_text_now(int(open_inquiry_id[0])) if clean_text_result['status'] == True: open_inq_clean_text = clean_text_result['clean_text'] if open_inq_clean_text != None: open_inq_text = word_tokenize(open_inq_clean_text) open_inq_vector = rec_model.infer_vector(open_inq_text) id_tuple = rec_model.dv.most_similar(open_inq_vector, topn = len(rec_model.dv.vectors)) results = pd.DataFrame(id_tuple, columns = ['inquiry_id', 'similarity']) results['inquiry_id'] = results['inquiry_id'].astype(int) linked_inqs = [] for i in range(len(result_link)): linked_inqs.append(result_link[i][1]) # [1] is the linked inquiry_id, [0] is the original inquiry_id results = results[~(results['inquiry_id'].isin(linked_inqs))] results['orignal'] = open_inquiry_id_original - Assistant
To use a pretrained model like BERT, you need to replace the code related to loading and using the
Doc2Vecmodel with the appropriate code for BERT. Here's an example of how you could modify the code:from transformers import BertTokenizer, BertModel model_name = 'bert-base-uncased' tokenizer = BertTokenizer.from_pretrained(model_name) model = BertModel.from_pretrained(model_name) open_inq_clean_text = result_open[0][1] if open_inq_clean_text == None: clean_text_result = clean_inquiry_text.clean_text_now(int(open_inquiry_id[0])) if clean_text_result['status'] == True: open_inq_clean_text = clean_text_result['clean_text'] if open_inq_clean_text != None: encoded_input = tokenizer.encode_plus(open_inq_clean_text, padding=True, truncation=True, return_tensors='pt') input_ids = encoded_input['input_ids'] attention_mask = encoded_input['attention_mask'] outputs = model(input_ids, attention_mask=attention_mask) open_inq_vector = outputs[0].squeeze() # Assuming the pretrained model outputs a single vector representation # Rest of the code remains mostly the same, assuming you use the vector representation for similarity calculations id_tuple = rec_model.dv.most_similar(open_inq_vector, topn=len(rec_model.dv.vectors)) ... - User
change bert to a sentence transformer
- Assistant
To use a pretrained model like Sentence Transformers, you need to replace the code related to loading and using BERT with the appropriate code for Sentence Transformers. Here's an example of how you could modify the code:
from sentence_transformers import SentenceTransformer model_name = 'bert-base-nli-mean-tokens' model = SentenceTransformer(model_name) open_inq_clean_text = result_open[0][1] if open_inq_clean_text == None: clean_text_result = clean_inquiry_text.clean_text_now(int(open_inquiry_id[0])) if clean_text_result['status'] == True: open_inq_clean_text = clean_text_result['clean_text'] if open_inq_clean_text != None: open_inq_vector = model.encode([open_inq_clean_text]) # Rest of the code remains mostly the same, assuming you use the vector representation for similarity calculations id_tuple = rec_model.dv.most_similar(open_inq_vector, topn=len(rec_model.dv.vectors)) ...Note that you'll need to install the
sentence-transformerslibrary usingpip install sentence-transformersif you haven't already. Also, make sure to check the documentation of the pretrained model you're using for any model-specific details or modifications required. - User
NameError Traceback (most recent call last) Cell In[74], line 1 ----> 1 find_sim_bert(i)
Cell In[73], line 70, in find_sim_bert(open_inquiry_id) 68 if open_inq_clean_text != None: 69 open_inq_vector = model.encode([open_inq_clean_text]) ---> 70 id_tuple = rec_model.dv.most_similar(open_inq_vector, topn = len(rec_model.dv.vectors)) 72 results = pd.DataFrame(id_tuple, columns = ['inquiry_id', 'similarity']) 73 results['inquiry_id'] = results['inquiry_id'].astype(int)
NameError: name 'rec_model' is not defined
- Assistant
Apologies for the error. It seems that the variable
rec_modelis not defined in the modified code. To fix this, you can replacerec_modelwithmodelsince you are using Sentence Transformers in this case. Here's the updated code:from sentence_transformers import SentenceTransformer model_name = 'bert-base-nli-mean-tokens' model = SentenceTransformer(model_name) open_inq_clean_text = result_open[0][1] if open_inq_clean_text == None: clean_text_result = clean_inquiry_text.clean_text_now(int(open_inquiry_id[0])) if clean_text_result['status'] == True: open_inq_clean_text = clean_text_result['clean_text'] if open_inq_clean_text != None: open_inq_vector = model.encode([open_inq_clean_text]) id_tuple = model.query(open_inq_vector, top_k=len(model)) results = pd.DataFrame(id_tuple, columns=['inquiry_id', 'similarity']) results['inquiry_id'] = results['inquiry_id'].astype(int) ...Please note that the
querymethod in Sentence Transformers retrieves the most similar vectors instead of using themost_similarmethod like in Doc2Vec. Also, ensure that the necessary packages like and are installed using before running the code. - User
AttributeError Traceback (most recent call last) Cell In[76], line 1 ----> 1 find_sim_bert(i)
Cell In[75], line 70, in find_sim_bert(open_inquiry_id) 68 if open_inq_clean_text != None: 69 open_inq_vector = model.encode([open_inq_clean_text]) ---> 70 id_tuple = model.query(open_inq_vector, top_k=len(model)) 71 results = pd.DataFrame(id_tuple, columns=['inquiry_id', 'similarity']) 72 results['inquiry_id'] = results['inquiry_id'].astype(int)
File ~\AppData\Roaming\Python\Python310\site-packages\torch\nn\modules\module.py:1614, in Module.getattr(self, name) 1612 if name in modules: 1613 return modules[name] -> 1614 raise AttributeError("'{}' object has no attribute '{}'".format( 1615 type(self).name, name))
AttributeError: 'SentenceTransformer' object has no attribute 'query'
- Assistant
Apologies for the confusion. It seems that there is no
querymethod in the Sentence Transformers library. To find the most similar vectors, you can use theutil.pytorch_cos_sim.cosine_similarityfunction provided by Sentence Transformers. Here's the updated code:from sentence_transformers import SentenceTransformer, util model_name = 'bert-base-nli-mean-tokens' model = SentenceTransformer(model_name) open_inq_clean_text = result_open[0][1] if open_inq_clean_text == None: clean_text_result = clean_inquiry_text.clean_text_now(int(open_inquiry_id[0])) if clean_text_result['status'] == True: open_inq_clean_text = clean_text_result['clean_text'] if open_inq_clean_text != None: open_inq_vector = model.encode([open_inq_clean_text]) id_tuple = util.cosine_similarity(open_inq_vector, model.encode(result_documents)) id_tuple = [(i, sim) for i, sim in enumerate(id_tuple[0])] id_tuple.sort(key=lambda x: x[1], reverse=True) id_tuple = id_tuple[:len(model)] results = pd.DataFrame(id_tuple, columns=['inquiry_id', 'similarity']) results['inquiry_id'] = results['inquiry_id'].astype(int) ... - User
NameError Traceback (most recent call last) Cell In[78], line 1 ----> 1 find_sim_bert(i)
Cell In[77], line 70, in find_sim_bert(open_inquiry_id) 68 if open_inq_clean_text != None: 69 open_inq_vector = model.encode([open_inq_clean_text]) ---> 70 id_tuple = util.cosine_similarity(open_inq_vector, model.encode(result_documents)) 71 id_tuple = [(i, sim) for i, sim in enumerate(id_tuple[0])] 72 id_tuple.sort(key=lambda x: x[1], reverse=True)
NameError: name 'util' is not defined
- Assistant
Apologies for the oversight. It seems that the
utilmodule was not imported in the code. To resolve this error, please make sure to import it along withSentenceTransformer. Here's the updated code:from sentence_transformers import SentenceTransformer, util model_name = 'bert-base-nli-mean-tokens' model = SentenceTransformer(model_name) open_inq_clean_text = result_open[0][1] if open_inq_clean_text == None: clean_text_result = clean_inquiry_text.clean_text_now(int(open_inquiry_id[0])) if clean_text_result['status'] == True: open_inq_clean_text = clean_text_result['clean_text'] if open_inq_clean_text != None: open_inq_vector = model.encode([open_inq_clean_text]) id_tuple = util.cosine_similarity(open_inq_vector, model.encode(result_documents)) id_tuple = [(i, sim) for i, sim in enumerate(id_tuple[0])] id_tuple.sort(key=lambda x: x[1], reverse=True) id_tuple = id_tuple[:len(model)] results = pd.DataFrame(id_tuple, columns=['inquiry_id', 'similarity']) results['inquiry_id'] = results['inquiry_id'].astype(int) ... - User
AttributeError Traceback (most recent call last) Cell In[80], line 1 ----> 1 find_sim_bert(i)
Cell In[79], line 71, in find_sim_bert(open_inquiry_id) 69 if open_inq_clean_text != None: 70 open_inq_vector = model.encode([open_inq_clean_text]) ---> 71 id_tuple = util.cosine_similarity(open_inq_vector, model.encode(result_documents)) 72 id_tuple = [(i, sim) for i, sim in enumerate(id_tuple[0])] 73 id_tuple.sort(key=lambda x: x[1], reverse=True)
AttributeError: module 'sentence_transformers.util' has no attribute 'cosine_similarity'
- Assistant
I apologize for the confusion once again. It seems that there is no
cosine_similarityfunction in theutilmodule of Sentence Transformers. To calculate cosine similarity in Sentence Transformers, you can use thepairwise_cosine_similarityfunction. Here's the updated code:from sentence_transformers import SentenceTransformer, util model_name = 'bert-base-nli-mean-tokens' model = SentenceTransformer(model_name) open_inq_clean_text = result_open[0][1] if open_inq_clean_text == None: clean_text_result = clean_inquiry_text.clean_text_now(int(open_inquiry_id[0])) if clean_text_result['status'] == True: open_inq_clean_text = clean_text_result['clean_text'] if open_inq_clean_text != None: open_inq_vector = model.encode([open_inq_clean_text]) id_tuple = util.pairwise_cosine_similarity([open_inq_vector], model.encode(result_documents)) id_tuple = [(i, sim) for i, sim in enumerate(id_tuple[0])] id_tuple.sort(key=lambda x: x[1], reverse=True) id_tuple = id_tuple[:len(model)] results = pd.DataFrame(id_tuple, columns=['inquiry_id', 'similarity']) results['inquiry_id'] = results['inquiry_id'].astype(int) ...
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.