【发布时间】:2020-06-23 19:00:27
【问题描述】:
我正在做一个模糊匹配项目,我发现了一个非常有趣的方法:awesome_cossim_top
我全面理解了定义,但不明白当我们执行 fit_transform 时会发生什么
import pandas as pd
import sqlite3 as sql
from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np
from scipy.sparse import csr_matrix
import sparse_dot_topn.sparse_dot_topn as ct
import re
def ngrams(string, n=3):
string = re.sub(r'[,-./]|\sBD',r'', re.sub(' +', ' ',str(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)
print('ct.sparse_dot_topn: ', ct.sparse_dot_topn)
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})
这是我遇到困惑的脚本: 为什么我们应该首先使用 fit_transform 然后只使用 SAME 矢量化器进行转换。 我尝试从矢量化器和矩阵打印一些输出,例如 print(vectorizer.get_feature_names()) 但不理解逻辑。
有人可以帮我澄清一下吗?
非常感谢!!
Col_clean = 'fruits_normalized'
Col_dirty = 'fruits'
#read table
data_dirty={f'{Col_dirty}':['I am an apple', 'You are an apple', 'Aple', 'Appls', 'Apples']}
data_clean= {f'{Col_clean}':['apple', 'pear', 'banana', 'apricot', 'pineapple']}
df_clean = pd.DataFrame(data_clean)
df_dirty = pd.DataFrame(data_dirty)
Name_clean = df_clean[f'{Col_clean}'].unique()
Name_dirty= df_dirty[f'{Col_dirty}'].unique()
vectorizer = TfidfVectorizer(min_df=1, analyzer=ngrams)
clean_idf_matrix = vectorizer.fit_transform(Name_clean)
dirty_idf_matrix = vectorizer.transform(Name_dirty)
matches = awesome_cossim_top(dirty_idf_matrix, clean_idf_matrix.transpose(),1,0)
matches_df = get_matches_df(matches, Name_dirty, Name_clean, top = 0)
with pd.option_context('display.max_rows', None, 'display.max_columns', None):
matches_df.to_excel("output_apple.xlsx")
print('done')
【问题讨论】:
标签: python machine-learning scikit-learn sparse-matrix fuzzy-logic