I have a list of phrases and a corpus which is a string of text with millions of words. For each phrase in my phrase list, I want to find and record the most similar phrases found in the corpus-string.
For my purposes I need to use SBERT similarity, and found the sentence-transformers lib to the best.
My problem is that while there exists documentation for finding similarities between two lists, I couldn’t find any for finding a list of phrases within a large string. I tried splitting my string into a list of sentence, but compute-time is incredibly long because for each phrase in the phrases list I need to loop thru each sentence (and there are plenty) and then append all matches to a dictionary I am creating.
phrase_list = ['Gregor Samse', 'in his bed into', 'horrible creature'...] # mine has 156 phrases
very_long_string= 'One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into a horrible vermin. He lay on his armour-like back, and if he lifted his head a little he could see his brown belly, slightly domed and divided by arches into stiff sections. The bedding was hardly able to cover it and seemed ready to slide off any moment. His many legs, pitifully thin compared with the size of the rest of him, waved about helplessly as he looked...'
# mine has around 11 million words
# convert text corpus string to list of sentences
string_to_sent_list = very_long_string.split(".")
from sentence_transformers import SentenceTransformer, util
model = SentenceTransformer('all-mpnet-base-v2')
phrase_embeddings = model.encode(phrase_list, convert_to_tensor=True)
sent_embeddings = model.encode(string_to_sent_list, convert_to_tensor=True)
similarity_dict = {}
for i, phraselist_phrase in enumerate(phrase_list):
similarities = util.cos_sim(phrase_embeddings[i], sent_embeddings)
matches = [string_to_sent_list[j] for j, sim in enumerate(similarities[0]) if sim > 0.65]
similarity_dict[phraselist_phrase] = matches
print(similarity_dict)
similarity_dict.to_csv('similarity dict.csv')
Are there alternative ways to accomplish this, either thru looping in a different way or using a different library? Open to any ideas. My goal is very simply to save all the corresponding phrase-matches within the corpus for each phrase in my phrase list.
P.S. Anyone know if this method saves as a match multiple version of the same phrase for example, for phrase ‘must complete this’ would it consider ‘we must complete this project’, and ‘we must’ , ‘must complete’, ‘complete this’ as matches even-tho they are from the same sentence?
3
You can use a set of algorithms to solve this problem. Of course, since the problem is complicated, the solution is also complex.
-
First break both your string and phrases into words and record the indices. Now you have both of them as words.
-
Loop through words of phrases and words of string, and check if you have an exactly similar word. If you do, then you “may” have a possible output within a close window of string. Here, you can create a window, and see if your phrase is in the window, “exactly” or “partially”. For “partially” you can use Levenshtein, and for “exact” you can use KMP.
I did not code the whole algorithm, will take you some time to do so. Partially, I did though, and you can do the rest.
import re, string, collections
def _matches(s, p):
return [(match.group(0), match.start(), match.end()) for match in re.finditer(p, s)]
def get_lps(p):
lps, j = [0] * len(p), 0
for i in range(1, len(p)):
while j and p[i] != p[j]:
j = lps[j - 1]
if p[i] == p[j]:
j += 1
lps[i] = j
return lps
def kmp(s, p):
lps, indices, j = get_lps(p), [], 0
for i in range(len(s)):
while j and s[i] != p[j]:
j = lps[j - 1]
if s[i] == p[j]:
j += 1
if j == len(p):
indices.append(i - len(p) + 1)
j = lps[j - 1]
return indices
def levenshtein_edit_distance(A, B):
dp = [[0] * (len(B) + 1) for _ in range(len(A) + 1)]
for i in range(len(A) + 1):
dp[i][0] = i
for j in range(len(B) + 1):
dp[0][j] = j
for i in range(1, len(A) + 1):
for j in range(1, len(B) + 1):
if A[i - 1] == B[j - 1]:
dp[i][j] = dp[i - 1][j - 1]
else:
dp[i][j] = 1 + min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1])
return dp[-1][-1]
phrase_list = ['Gregor Samse', 'in his bed into', 'horrible creature']
phs = list(set(phrase_list))
s = ' ' * 50 +
"""
One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into a horrible vermin.
He lay on his armour-like back, and if he lifted his head a little he could see his brown belly, slightly domed and divided by arches into stiff sections. The bedding was hardly able to cover it and seemed ready to slide off any moment.
His many legs, pitifully thin compared with the size of the rest of him, waved about helplessly as he looked..."""
+ ' ' * 50
p = r'(?:b[^rnst,?:;'"!_-]+?b)'
s_matches = _matches(s, p)
print(s_matches)
d = {ph: _matches(ph, p) for ph in phs}
print(d)
res = []
possibles = collections.defaultdict(list)
for k, val in d.items():
for (word_a, st_a, end_a) in val:
for (word_s, st_s, end_s) in s_matches:
if word_a == word_s:
search_window = s[st_s - 10:end_s + 10]
found = kmp(search_window, word_a)[0]
print(st_s, found, search_window)
possibles[k] += [(st_s, found, search_window)]
# break
print(possibles)
Levenshtein Distance
Knuth–Morris–Pratt algorithm
Similarity
Note that Levenshtein calculates the distance of two strings.
- If their distance is 0, it is an exact match.
- If their distance is close, it is a close match.
- If their distance is not close, it is not a match.
def levenshtein_edit_distance(A, B):
dp = [[0] * (len(B) + 1) for _ in range(len(A) + 1)]
for i in range(len(A) + 1):
dp[i][0] = i
for j in range(len(B) + 1):
dp[0][j] = j
for i in range(1, len(A) + 1):
for j in range(1, len(B) + 1):
if A[i - 1] == B[j - 1]:
dp[i][j] = dp[i - 1][j - 1]
else:
dp[i][j] = 1 + min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1])
return dp[-1][-1]
phrase = 'horrible creature'
s = 'horrible vermin'
dist = levenshtein_edit_distance(phrase, s)
if levenshtein_edit_distance(phrase, s) < len(phrase) // 2:
print(f"'{s}' and '{phrase}' are similar matches with a character distance of {dist}.")
Prints
‘horrible vermin’ and ‘horrible creature’ are similar matches with a
character distance of 7.