NAME MATCHING. Running a sparse_dot_topn function is giving me Warning: Kernel Restarted?

767 views Asked by At

I am trying to match our company names to a government's database of company names using cosine similarity via the awesome_cossim_top. So, I convert my ngrams tf-idf into a CSR matrix and run it through the function. It does not run and restarts my kernels on every IDE (Colab, Spyder, PyCharm and Jupyter). It simply is not working. I want to understand why?

import re
from ftfy import fix_text
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.neighbors import NearestNeighbors
import difflib
import numpy as np
from sparse_dot_topn import awesome_cossim_topn
from scipy.sparse import csr_matrix
import sparse_dot_topn.sparse_dot_topn as ct

def ngrams(string, n=3):
    string = fix_text(string) # fix text encoding issues
    string = string.encode("ascii", errors="ignore").decode() #remove non ascii chars
    string = string.lower() #make lower case
    chars_to_remove = [")","(",".","|","[","]","{","}","'"]
    rx = '[' + re.escape(''.join(chars_to_remove)) + ']'
    string = re.sub(rx, '', string) #remove the list of chars defined above
    string = string.replace('&', 'and')
    string = string.replace(',', ' ')
    string = string.replace('-', ' ')
    string = string.title() # normalise case - capital at start of each word
    string = re.sub(' +',' ',string).strip() # get rid of multiple spaces and replace with a single space
    string = ' '+ string +' ' # pad names for ngrams...
    string = re.sub(r'[,-./]|\sBD',r'', string)
    ngrams = zip(*[string[i:] for i in range(n)])
    
    return [''.join(ngram) for ngram in ngrams]

def awesome_cossim_top(A, B, ntop, lower_bound=0):
    # force A and B as a CSR matrix.
    # If they have already been CSR, there is no overhead
    A = A.tocsr()
    B = B.tocsr()
    M, _ = A.shape
    _, N = B.shape

    idx_dtype = np.int32

    nnz_max = M * ntop

    indptr = np.zeros(M + 1, dtype=idx_dtype)
    indices = np.zeros(nnz_max, dtype=idx_dtype)
    data = np.zeros(nnz_max, dtype=A.dtype)

    ct.sparse_dot_topn(
        M, N, np.asarray(A.indptr, dtype=idx_dtype),
        np.asarray(A.indices, dtype=idx_dtype),
        A.data,
        np.asarray(B.indptr, dtype=idx_dtype),
        np.asarray(B.indices, dtype=idx_dtype),
        B.data,
        ntop,
        lower_bound,
        indptr, indices, data)

    return csr_matrix((data, indices, indptr), shape=(M, N))

def get_matches_df(sparse_matrix, A, B, top=100):
    non_zeros = sparse_matrix.nonzero()

    sparserows = non_zeros[0]
    sparsecols = non_zeros[1]

    if top:
        nr_matches = top
    else:
        nr_matches = sparsecols.size

    left_side = np.empty([nr_matches], dtype=object)
    right_side = np.empty([nr_matches], dtype=object)
    similairity = np.zeros(nr_matches)

    for index in range(0, nr_matches):
        left_side[index] = A[sparserows[index]]
        right_side[index] = B[sparsecols[index]]
        similairity[index] = sparse_matrix.data[index]

    return pd.DataFrame({'left_side': left_side,
                         'right_side': right_side,
                         'similairity': similairity})

govdata = pd.read_csv('companydata2018.csv', encoding='utf-8')
hypxdata = pd.read_csv('enerygycomp.csv', encoding='cp1252')

#X = gov Y = hypx
vectoriser = TfidfVectorizer(analyzer=ngrams)

tfidfgov = vectoriser.fit_transform(govdata['CompanyName'])
tfidfhypx = vectoriser.fit_transform(hypxdata['Name'])

matches = awesome_cossim_top(tfidfgov, tfidfhypx.transpose(), 1, 0)```
1

There are 1 answers

0
eseuteo On

I guess you are running out of memory. Have you tried with a smaller dataset?

Also, I think you should do the fit and transformation steps separately: fit the vectorizer with both series (for example concatenating them) and after that obtain the tfidf matrix for both datasets with transform.