问题描述
我想使用 Python 进行名称匹配,并找到了一些使用 ngrams 和余弦相似度函数来做到这一点的文章。
这是我的 ngrams
函数:
def ngrams(string,n=3):
string = str(string)
string = fix_text(string) # fix text
string = string.encode("ascii",errors="ignore").decode() #remove non ascii chars
string = string.lower()
chars_to_remove = [")","(",".","|","[","]","{","}","'"]
rx = "[" + re.escape("".join(chars_to_remove)) + "]"
string = re.sub(rx,"",string)
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
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]
使用这个函数,我可以像这样使用 TF IDF Vectorizer 获取我的数据的矩阵。
from sklearn.feature_extraction.text import TfidfVectorizer
vectorizer = TfidfVectorizer(min_df=1,analyzer=ngrams)
tf_idf_matrix = vectorizer.fit_transform(name)
我制作了 2 个矩阵 A 和 B,以便稍后使用余弦相似度函数进行比较。
def awesome_cossim_top(A,B,ntop,lower_bound=0):
if not isspmatrix_csr(A):
A = A.tocsr()
if not isspmatrix_csr(B):
B = B.tocsr()
M,K1 = A.shape
K2,N = B.shape
idx_dtype = np.int32
nnz_max = M*ntop
indptr = np.empty(M+1,dtype=idx_dtype)
indices = np.empty(nnz_max,dtype=idx_dtype)
data = np.empty(nnz_max,dtype=A.dtype)
ct.sparse_dot_topn(
M,N,np.asarray(A.indptr,dtype=idx_dtype),np.asarray(A.indices,A.data,np.asarray(B.indptr,np.asarray(B.indices,B.data,lower_bound,indptr,indices,data)
return csr_matrix((data,indptr),shape=(M,N))
并使用以下代码调用它:
matches = awesome_cossim_top(tf_idf_matrix_A,tf_idf_matrix_B.transpose(),10,0)
但我没有得到一致的结果。例如,我针对此数据运行它:
index | name A | name B |
---|---|---|
0 | 亚伯兰 | 亚伯兰 |
1 | 王牌 | 王牌 |
结果是:
A | B | 相似性 |
---|---|---|
0 | 0 | 1 |
1 | 1 | 1 |
当我反转数据时,它不会返回类似的结果。
index | name A | name B |
---|---|---|
0 | 亚伯兰 | 王牌 |
1 | 王牌 | 亚伯兰 |
结果是:
A | B | 相似性 |
---|---|---|
0 | 0 | 0,571239953724207 |
0 | 1 | 0,27197690175892 |
1 | 0 | 0,571239953724207 |
1 | 1 | 0,543953803517839 |
为什么结果相差甚远,我该怎么做才能使其保持一致?类似的东西:
A | B | 相似性 |
---|---|---|
0 | 0 | 0,571239953724207 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 0,543953803517839 |
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)