Сопоставление с использованием косинусного сходства безуспешно - PullRequest
0 голосов
/ 29 мая 2020

Привет, у меня есть два больших набора данных с названиями компаний: один с 352 компаниями, которые я хотел бы сопоставить с большим набором данных из 75k + компаний. Я пытаюсь использовать косинусное сходство, так как нечеткое отображение займет вечность

Я написал код и запустил его на Jupyter, но результаты невероятно плохие. Я знаю, что сценарий должен работать лучше, зная базовые данные в двух наборах данных. Что я делаю не так? Я поигрался с функцией awesome_cossim, но мне кажется, что это может быть в ngrams ...

Вот код '

import pandas as pd

companies = pd.read_csv('path here', header=0)

dbcompanies = pd.read_csv(path, header=0)

import re

def ngrams(string, n=3):
    string = re.sub(r'[,-./]|\sBD',r'', string)
    ngrams = zip(*[string[i:] for i in range(n)])
    return [''.join(ngram) for ngram in ngrams]

from sklearn.feature_extraction.text import TfidfVectorizer

company_names = companies['Company']
vectorizer = TfidfVectorizer(min_df=1, analyzer=ngrams)
tf_idf_matrix1 = vectorizer.fit_transform(companies['Company'])

business_names = dbcompanies['Business name ']
tf_idf_matrix2 = vectorizer.fit_transform(business_names)

import numpy as np
from scipy.sparse import csr_matrix
import sparse_dot_topn.sparse_dot_topn as ct

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

matches = awesome_cossim_top(tf_idf_matrix1.T, tf_idf_matrix2, 3, 0.4)

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})

matches_df = get_matches_df(matches, company_names, business_names, top=3)
matches_df
...