1

我正在尝试通过 awesome_cossim_top 使用余弦相似度将我们的公司名称与政府的公司名称数据库进行匹配。因此,我将我的 ngram tf-idf 转换为 CSR 矩阵并通过函数运行它。它不会在每个 IDE(Colab、Spyder、PyCharm 和 Jupyter)上运行并重新启动我的内核。它根本行不通。我想明白为什么?

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)```
4

1 回答 1

0

我猜你的内存不足了。您是否尝试过使用较小的数据集?

另外,我认为您应该分别执行拟合和转换步骤:使用两个系列(例如连接它们)拟合矢量化器,然后通过转换获得两个数据集的 tfidf 矩阵。

于 2021-05-04T12:14:19.870 回答