Suppose I have a dataframe with 3 rows of text:
#(needed libraries):
from keybert import KeyBERT
from sentence_transformers import SentenceTransformer
from keyphrase_vectorizers import KeyphraseCountVectorizer
import pandas as pd
sentence_model = SentenceTransformer("all-MiniLM-L6-v2")
st_model = KeyBERT(model=sentence_model)
data = pd.DataFrame({'text':['Machine learning (ML) is a type of artificial intelligence (AI) that allows software applications to become more accurate at predicting outcomes without being explicitly programmed to do so. Machine learning algorithms use historical data as input to predict new output values.','Physics is the natural science that studies matter, its fundamental constituents, its motion and behavior through space and time, and the related entities of energy and force. Physics is one of the most fundamental scientific disciplines, with its main goal being to understand how the universe behaves.','Chemistry is the branch of science that deals with the properties, composition, and structure of elements and compounds, how they can change, and the energy that is released or absorbed when they change.']})
I want to go through each text (row) and pick the most relevant if they follow a specific pattern, do to this I made a double loop (nested loop) which does the job but takes a lot of computational time, my method is as follow:
pt = []
patterns = ['<J.*>*<N.*>+', '<V.*>+', '<N.*>*<V.*>+', '<J.*>*<N.*>*<V.*>+']
for j in range(len(data)):
for i in range(len(patterns)):
vectorizer = KeyphraseCountVectorizer(pos_pattern = patterns[i])
pt.append(st_model.extract_keywords(data.text.iloc[j],stop_words = "english", vectorizer=vectorizer,use_mmr=True, diversity=0.4))
as you can see there is 4 patterns that should be applied to 3 rows of texts. I wonder how can I make this nested loop computationally light as my original dataset contains 1000s of rows and using this method will take hours to be executed.
Bear in mind I've provided the libraries and the exact context so my problem would be reproduceable but the real issue happens in the second block of code where the nested loop is located.
UPDATE: I have also now tried to use itertools product as:
pt = []
vecz = []
patterns = ['<J.*>*<N.*>+', '<V.*>+', '<N.*>*<V.*>+', '<J.*>*<N.*>*<V.*>+']
for i in range(len(patterns)):
vectorizer = KeyphraseCountVectorizer(pos_pattern = patterns[i])
vecz.append(vectorizer)
from itertools import product
for j, i in product(range(len(data)), range(len(vecz))):
pt.append(st_model.extract_keywords(data.text.iloc[j],stop_words = "english", vectorizer=vecz[i],use_mmr=True, diversity=0.4))
but the performance did not improve drastically.